PR symtab/11198:
[platform/upstream/binutils.git] / gdb / symfile.c
1 /* Generic symbol file reading for the GNU debugger, GDB.
2
3    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5    Free Software Foundation, Inc.
6
7    Contributed by Cygnus Support, using pieces from other GDB modules.
8
9    This file is part of GDB.
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
23
24 #include "defs.h"
25 #include "arch-utils.h"
26 #include "bfdlink.h"
27 #include "symtab.h"
28 #include "gdbtypes.h"
29 #include "gdbcore.h"
30 #include "frame.h"
31 #include "target.h"
32 #include "value.h"
33 #include "symfile.h"
34 #include "objfiles.h"
35 #include "source.h"
36 #include "gdbcmd.h"
37 #include "breakpoint.h"
38 #include "language.h"
39 #include "complaints.h"
40 #include "demangle.h"
41 #include "inferior.h"
42 #include "regcache.h"
43 #include "filenames.h"          /* for DOSish file names */
44 #include "gdb-stabs.h"
45 #include "gdb_obstack.h"
46 #include "completer.h"
47 #include "bcache.h"
48 #include "hashtab.h"
49 #include "readline/readline.h"
50 #include "gdb_assert.h"
51 #include "block.h"
52 #include "observer.h"
53 #include "exec.h"
54 #include "parser-defs.h"
55 #include "varobj.h"
56 #include "elf-bfd.h"
57 #include "solib.h"
58 #include "remote.h"
59
60 #include <sys/types.h>
61 #include <fcntl.h>
62 #include "gdb_string.h"
63 #include "gdb_stat.h"
64 #include <ctype.h>
65 #include <time.h>
66 #include <sys/time.h>
67
68
69 int (*deprecated_ui_load_progress_hook) (const char *section, unsigned long num);
70 void (*deprecated_show_load_progress) (const char *section,
71                             unsigned long section_sent,
72                             unsigned long section_size,
73                             unsigned long total_sent,
74                             unsigned long total_size);
75 void (*deprecated_pre_add_symbol_hook) (const char *);
76 void (*deprecated_post_add_symbol_hook) (void);
77
78 static void clear_symtab_users_cleanup (void *ignore);
79
80 /* Global variables owned by this file */
81 int readnow_symbol_files;       /* Read full symbols immediately */
82
83 /* External variables and functions referenced. */
84
85 extern void report_transfer_performance (unsigned long, time_t, time_t);
86
87 /* Functions this file defines */
88
89 #if 0
90 static int simple_read_overlay_region_table (void);
91 static void simple_free_overlay_region_table (void);
92 #endif
93
94 static void load_command (char *, int);
95
96 static void symbol_file_add_main_1 (char *args, int from_tty, int flags);
97
98 static void add_symbol_file_command (char *, int);
99
100 bfd *symfile_bfd_open (char *);
101
102 int get_section_index (struct objfile *, char *);
103
104 static struct sym_fns *find_sym_fns (bfd *);
105
106 static void decrement_reading_symtab (void *);
107
108 static void overlay_invalidate_all (void);
109
110 void list_overlays_command (char *, int);
111
112 void map_overlay_command (char *, int);
113
114 void unmap_overlay_command (char *, int);
115
116 static void overlay_auto_command (char *, int);
117
118 static void overlay_manual_command (char *, int);
119
120 static void overlay_off_command (char *, int);
121
122 static void overlay_load_command (char *, int);
123
124 static void overlay_command (char *, int);
125
126 static void simple_free_overlay_table (void);
127
128 static void read_target_long_array (CORE_ADDR, unsigned int *, int, int,
129                                     enum bfd_endian);
130
131 static int simple_read_overlay_table (void);
132
133 static int simple_overlay_update_1 (struct obj_section *);
134
135 static void add_filename_language (char *ext, enum language lang);
136
137 static void info_ext_lang_command (char *args, int from_tty);
138
139 static void init_filename_language_table (void);
140
141 static void symfile_find_segment_sections (struct objfile *objfile);
142
143 void _initialize_symfile (void);
144
145 /* List of all available sym_fns.  On gdb startup, each object file reader
146    calls add_symtab_fns() to register information on each format it is
147    prepared to read. */
148
149 static struct sym_fns *symtab_fns = NULL;
150
151 /* Flag for whether user will be reloading symbols multiple times.
152    Defaults to ON for VxWorks, otherwise OFF.  */
153
154 #ifdef SYMBOL_RELOADING_DEFAULT
155 int symbol_reloading = SYMBOL_RELOADING_DEFAULT;
156 #else
157 int symbol_reloading = 0;
158 #endif
159 static void
160 show_symbol_reloading (struct ui_file *file, int from_tty,
161                        struct cmd_list_element *c, const char *value)
162 {
163   fprintf_filtered (file, _("\
164 Dynamic symbol table reloading multiple times in one run is %s.\n"),
165                     value);
166 }
167
168 /* If non-zero, shared library symbols will be added automatically
169    when the inferior is created, new libraries are loaded, or when
170    attaching to the inferior.  This is almost always what users will
171    want to have happen; but for very large programs, the startup time
172    will be excessive, and so if this is a problem, the user can clear
173    this flag and then add the shared library symbols as needed.  Note
174    that there is a potential for confusion, since if the shared
175    library symbols are not loaded, commands like "info fun" will *not*
176    report all the functions that are actually present. */
177
178 int auto_solib_add = 1;
179
180 /* For systems that support it, a threshold size in megabytes.  If
181    automatically adding a new library's symbol table to those already
182    known to the debugger would cause the total shared library symbol
183    size to exceed this threshhold, then the shlib's symbols are not
184    added.  The threshold is ignored if the user explicitly asks for a
185    shlib to be added, such as when using the "sharedlibrary"
186    command. */
187
188 int auto_solib_limit;
189 \f
190
191 /* This compares two partial symbols by names, using strcmp_iw_ordered
192    for the comparison.  */
193
194 static int
195 compare_psymbols (const void *s1p, const void *s2p)
196 {
197   struct partial_symbol *const *s1 = s1p;
198   struct partial_symbol *const *s2 = s2p;
199
200   return strcmp_iw_ordered (SYMBOL_SEARCH_NAME (*s1),
201                             SYMBOL_SEARCH_NAME (*s2));
202 }
203
204 void
205 sort_pst_symbols (struct partial_symtab *pst)
206 {
207   /* Sort the global list; don't sort the static list */
208
209   qsort (pst->objfile->global_psymbols.list + pst->globals_offset,
210          pst->n_global_syms, sizeof (struct partial_symbol *),
211          compare_psymbols);
212 }
213
214 /* Make a null terminated copy of the string at PTR with SIZE characters in
215    the obstack pointed to by OBSTACKP .  Returns the address of the copy.
216    Note that the string at PTR does not have to be null terminated, I.E. it
217    may be part of a larger string and we are only saving a substring. */
218
219 char *
220 obsavestring (const char *ptr, int size, struct obstack *obstackp)
221 {
222   char *p = (char *) obstack_alloc (obstackp, size + 1);
223   /* Open-coded memcpy--saves function call time.  These strings are usually
224      short.  FIXME: Is this really still true with a compiler that can
225      inline memcpy? */
226   {
227     const char *p1 = ptr;
228     char *p2 = p;
229     const char *end = ptr + size;
230     while (p1 != end)
231       *p2++ = *p1++;
232   }
233   p[size] = 0;
234   return p;
235 }
236
237 /* Concatenate strings S1, S2 and S3; return the new string.  Space is found
238    in the obstack pointed to by OBSTACKP.  */
239
240 char *
241 obconcat (struct obstack *obstackp, const char *s1, const char *s2,
242           const char *s3)
243 {
244   int len = strlen (s1) + strlen (s2) + strlen (s3) + 1;
245   char *val = (char *) obstack_alloc (obstackp, len);
246   strcpy (val, s1);
247   strcat (val, s2);
248   strcat (val, s3);
249   return val;
250 }
251
252 /* True if we are nested inside psymtab_to_symtab. */
253
254 int currently_reading_symtab = 0;
255
256 static void
257 decrement_reading_symtab (void *dummy)
258 {
259   currently_reading_symtab--;
260 }
261
262 /* Get the symbol table that corresponds to a partial_symtab.
263    This is fast after the first time you do it.  In fact, there
264    is an even faster macro PSYMTAB_TO_SYMTAB that does the fast
265    case inline.  */
266
267 struct symtab *
268 psymtab_to_symtab (struct partial_symtab *pst)
269 {
270   /* If it's been looked up before, return it. */
271   if (pst->symtab)
272     return pst->symtab;
273
274   /* If it has not yet been read in, read it.  */
275   if (!pst->readin)
276     {
277       struct cleanup *back_to = make_cleanup (decrement_reading_symtab, NULL);
278       currently_reading_symtab++;
279       (*pst->read_symtab) (pst);
280       do_cleanups (back_to);
281     }
282
283   return pst->symtab;
284 }
285
286 /* Remember the lowest-addressed loadable section we've seen.
287    This function is called via bfd_map_over_sections.
288
289    In case of equal vmas, the section with the largest size becomes the
290    lowest-addressed loadable section.
291
292    If the vmas and sizes are equal, the last section is considered the
293    lowest-addressed loadable section.  */
294
295 void
296 find_lowest_section (bfd *abfd, asection *sect, void *obj)
297 {
298   asection **lowest = (asection **) obj;
299
300   if (0 == (bfd_get_section_flags (abfd, sect) & SEC_LOAD))
301     return;
302   if (!*lowest)
303     *lowest = sect;             /* First loadable section */
304   else if (bfd_section_vma (abfd, *lowest) > bfd_section_vma (abfd, sect))
305     *lowest = sect;             /* A lower loadable section */
306   else if (bfd_section_vma (abfd, *lowest) == bfd_section_vma (abfd, sect)
307            && (bfd_section_size (abfd, (*lowest))
308                <= bfd_section_size (abfd, sect)))
309     *lowest = sect;
310 }
311
312 /* Create a new section_addr_info, with room for NUM_SECTIONS.  */
313
314 struct section_addr_info *
315 alloc_section_addr_info (size_t num_sections)
316 {
317   struct section_addr_info *sap;
318   size_t size;
319
320   size = (sizeof (struct section_addr_info)
321           +  sizeof (struct other_sections) * (num_sections - 1));
322   sap = (struct section_addr_info *) xmalloc (size);
323   memset (sap, 0, size);
324   sap->num_sections = num_sections;
325
326   return sap;
327 }
328
329 /* Build (allocate and populate) a section_addr_info struct from
330    an existing section table. */
331
332 extern struct section_addr_info *
333 build_section_addr_info_from_section_table (const struct target_section *start,
334                                             const struct target_section *end)
335 {
336   struct section_addr_info *sap;
337   const struct target_section *stp;
338   int oidx;
339
340   sap = alloc_section_addr_info (end - start);
341
342   for (stp = start, oidx = 0; stp != end; stp++)
343     {
344       if (bfd_get_section_flags (stp->bfd,
345                                  stp->the_bfd_section) & (SEC_ALLOC | SEC_LOAD)
346           && oidx < end - start)
347         {
348           sap->other[oidx].addr = stp->addr;
349           sap->other[oidx].name
350             = xstrdup (bfd_section_name (stp->bfd, stp->the_bfd_section));
351           sap->other[oidx].sectindex = stp->the_bfd_section->index;
352           oidx++;
353         }
354     }
355
356   return sap;
357 }
358
359 /* Create a section_addr_info from section offsets in OBJFILE.  */
360
361 struct section_addr_info *
362 build_section_addr_info_from_objfile (const struct objfile *objfile)
363 {
364   struct section_addr_info *sap;
365   int i;
366   struct bfd_section *sec;
367   int addr_bit = gdbarch_addr_bit (objfile->gdbarch);
368   CORE_ADDR mask = CORE_ADDR_MAX;
369
370   if (addr_bit < (sizeof (CORE_ADDR) * HOST_CHAR_BIT))
371     mask = ((CORE_ADDR) 1 << addr_bit) - 1;
372
373   sap = alloc_section_addr_info (objfile->num_sections);
374   for (i = 0, sec = objfile->obfd->sections;
375        i < objfile->num_sections;
376        i++, sec = sec->next)
377     {
378       gdb_assert (sec != NULL);
379       sap->other[i].addr = (bfd_get_section_vma (objfile->obfd, sec)
380                             + objfile->section_offsets->offsets[i]) & mask;
381       sap->other[i].name = xstrdup (bfd_get_section_name (objfile->obfd, sec));
382       sap->other[i].sectindex = sec->index;
383     }
384   return sap;
385 }
386
387
388 /* Free all memory allocated by build_section_addr_info_from_section_table. */
389
390 extern void
391 free_section_addr_info (struct section_addr_info *sap)
392 {
393   int idx;
394
395   for (idx = 0; idx < sap->num_sections; idx++)
396     if (sap->other[idx].name)
397       xfree (sap->other[idx].name);
398   xfree (sap);
399 }
400
401
402 /* Initialize OBJFILE's sect_index_* members.  */
403 static void
404 init_objfile_sect_indices (struct objfile *objfile)
405 {
406   asection *sect;
407   int i;
408
409   sect = bfd_get_section_by_name (objfile->obfd, ".text");
410   if (sect)
411     objfile->sect_index_text = sect->index;
412
413   sect = bfd_get_section_by_name (objfile->obfd, ".data");
414   if (sect)
415     objfile->sect_index_data = sect->index;
416
417   sect = bfd_get_section_by_name (objfile->obfd, ".bss");
418   if (sect)
419     objfile->sect_index_bss = sect->index;
420
421   sect = bfd_get_section_by_name (objfile->obfd, ".rodata");
422   if (sect)
423     objfile->sect_index_rodata = sect->index;
424
425   /* This is where things get really weird...  We MUST have valid
426      indices for the various sect_index_* members or gdb will abort.
427      So if for example, there is no ".text" section, we have to
428      accomodate that.  First, check for a file with the standard
429      one or two segments.  */
430
431   symfile_find_segment_sections (objfile);
432
433   /* Except when explicitly adding symbol files at some address,
434      section_offsets contains nothing but zeros, so it doesn't matter
435      which slot in section_offsets the individual sect_index_* members
436      index into.  So if they are all zero, it is safe to just point
437      all the currently uninitialized indices to the first slot.  But
438      beware: if this is the main executable, it may be relocated
439      later, e.g. by the remote qOffsets packet, and then this will
440      be wrong!  That's why we try segments first.  */
441
442   for (i = 0; i < objfile->num_sections; i++)
443     {
444       if (ANOFFSET (objfile->section_offsets, i) != 0)
445         {
446           break;
447         }
448     }
449   if (i == objfile->num_sections)
450     {
451       if (objfile->sect_index_text == -1)
452         objfile->sect_index_text = 0;
453       if (objfile->sect_index_data == -1)
454         objfile->sect_index_data = 0;
455       if (objfile->sect_index_bss == -1)
456         objfile->sect_index_bss = 0;
457       if (objfile->sect_index_rodata == -1)
458         objfile->sect_index_rodata = 0;
459     }
460 }
461
462 /* The arguments to place_section.  */
463
464 struct place_section_arg
465 {
466   struct section_offsets *offsets;
467   CORE_ADDR lowest;
468 };
469
470 /* Find a unique offset to use for loadable section SECT if
471    the user did not provide an offset.  */
472
473 static void
474 place_section (bfd *abfd, asection *sect, void *obj)
475 {
476   struct place_section_arg *arg = obj;
477   CORE_ADDR *offsets = arg->offsets->offsets, start_addr;
478   int done;
479   ULONGEST align = ((ULONGEST) 1) << bfd_get_section_alignment (abfd, sect);
480
481   /* We are only interested in allocated sections.  */
482   if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
483     return;
484
485   /* If the user specified an offset, honor it.  */
486   if (offsets[sect->index] != 0)
487     return;
488
489   /* Otherwise, let's try to find a place for the section.  */
490   start_addr = (arg->lowest + align - 1) & -align;
491
492   do {
493     asection *cur_sec;
494
495     done = 1;
496
497     for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next)
498       {
499         int indx = cur_sec->index;
500         CORE_ADDR cur_offset;
501
502         /* We don't need to compare against ourself.  */
503         if (cur_sec == sect)
504           continue;
505
506         /* We can only conflict with allocated sections.  */
507         if ((bfd_get_section_flags (abfd, cur_sec) & SEC_ALLOC) == 0)
508           continue;
509
510         /* If the section offset is 0, either the section has not been placed
511            yet, or it was the lowest section placed (in which case LOWEST
512            will be past its end).  */
513         if (offsets[indx] == 0)
514           continue;
515
516         /* If this section would overlap us, then we must move up.  */
517         if (start_addr + bfd_get_section_size (sect) > offsets[indx]
518             && start_addr < offsets[indx] + bfd_get_section_size (cur_sec))
519           {
520             start_addr = offsets[indx] + bfd_get_section_size (cur_sec);
521             start_addr = (start_addr + align - 1) & -align;
522             done = 0;
523             break;
524           }
525
526         /* Otherwise, we appear to be OK.  So far.  */
527       }
528     }
529   while (!done);
530
531   offsets[sect->index] = start_addr;
532   arg->lowest = start_addr + bfd_get_section_size (sect);
533 }
534
535 /* Store struct section_addr_info as prepared (made relative and with SECTINDEX
536    filled-in) by addr_info_make_relative into SECTION_OFFSETS of NUM_SECTIONS
537    entries.  */
538
539 void
540 relative_addr_info_to_section_offsets (struct section_offsets *section_offsets,
541                                        int num_sections,
542                                        struct section_addr_info *addrs)
543 {
544   int i;
545
546   memset (section_offsets, 0, SIZEOF_N_SECTION_OFFSETS (num_sections));
547
548   /* Now calculate offsets for section that were specified by the caller. */
549   for (i = 0; i < addrs->num_sections && addrs->other[i].name; i++)
550     {
551       struct other_sections *osp;
552
553       osp = &addrs->other[i];
554       if (osp->addr == 0)
555         continue;
556
557       /* Record all sections in offsets */
558       /* The section_offsets in the objfile are here filled in using
559          the BFD index. */
560       section_offsets->offsets[osp->sectindex] = osp->addr;
561     }
562 }
563
564 /* Relativize absolute addresses in ADDRS into offsets based on ABFD.  Fill-in
565    also SECTINDEXes there.  */
566
567 void
568 addr_info_make_relative (struct section_addr_info *addrs, bfd *abfd)
569 {
570   asection *lower_sect;
571   asection *sect;
572   CORE_ADDR lower_offset;
573   int i;
574
575   /* Find lowest loadable section to be used as starting point for
576      continguous sections. FIXME!! won't work without call to find
577      .text first, but this assumes text is lowest section. */
578   lower_sect = bfd_get_section_by_name (abfd, ".text");
579   if (lower_sect == NULL)
580     bfd_map_over_sections (abfd, find_lowest_section, &lower_sect);
581   if (lower_sect == NULL)
582     {
583       warning (_("no loadable sections found in added symbol-file %s"),
584                bfd_get_filename (abfd));
585       lower_offset = 0;
586     }
587   else
588     lower_offset = bfd_section_vma (bfd_get_filename (abfd), lower_sect);
589
590   /* Calculate offsets for the loadable sections.
591      FIXME! Sections must be in order of increasing loadable section
592      so that contiguous sections can use the lower-offset!!!
593
594      Adjust offsets if the segments are not contiguous.
595      If the section is contiguous, its offset should be set to
596      the offset of the highest loadable section lower than it
597      (the loadable section directly below it in memory).
598      this_offset = lower_offset = lower_addr - lower_orig_addr */
599
600   for (i = 0; i < addrs->num_sections && addrs->other[i].name; i++)
601     {
602       if (addrs->other[i].addr != 0)
603         {
604           sect = bfd_get_section_by_name (abfd, addrs->other[i].name);
605           if (sect)
606             {
607               addrs->other[i].addr -= bfd_section_vma (abfd, sect);
608               lower_offset = addrs->other[i].addr;
609               /* This is the index used by BFD. */
610               addrs->other[i].sectindex = sect->index;
611             }
612           else
613             {
614               warning (_("section %s not found in %s"), addrs->other[i].name,
615                        bfd_get_filename (abfd));
616               addrs->other[i].addr = 0;
617             }
618         }
619       else
620         addrs->other[i].addr = lower_offset;
621     }
622 }
623
624 /* Parse the user's idea of an offset for dynamic linking, into our idea
625    of how to represent it for fast symbol reading.  This is the default
626    version of the sym_fns.sym_offsets function for symbol readers that
627    don't need to do anything special.  It allocates a section_offsets table
628    for the objectfile OBJFILE and stuffs ADDR into all of the offsets.  */
629
630 void
631 default_symfile_offsets (struct objfile *objfile,
632                          struct section_addr_info *addrs)
633 {
634   objfile->num_sections = bfd_count_sections (objfile->obfd);
635   objfile->section_offsets = (struct section_offsets *)
636     obstack_alloc (&objfile->objfile_obstack,
637                    SIZEOF_N_SECTION_OFFSETS (objfile->num_sections));
638   relative_addr_info_to_section_offsets (objfile->section_offsets,
639                                          objfile->num_sections, addrs);
640
641   /* For relocatable files, all loadable sections will start at zero.
642      The zero is meaningless, so try to pick arbitrary addresses such
643      that no loadable sections overlap.  This algorithm is quadratic,
644      but the number of sections in a single object file is generally
645      small.  */
646   if ((bfd_get_file_flags (objfile->obfd) & (EXEC_P | DYNAMIC)) == 0)
647     {
648       struct place_section_arg arg;
649       bfd *abfd = objfile->obfd;
650       asection *cur_sec;
651       CORE_ADDR lowest = 0;
652
653       for (cur_sec = abfd->sections; cur_sec != NULL; cur_sec = cur_sec->next)
654         /* We do not expect this to happen; just skip this step if the
655            relocatable file has a section with an assigned VMA.  */
656         if (bfd_section_vma (abfd, cur_sec) != 0)
657           break;
658
659       if (cur_sec == NULL)
660         {
661           CORE_ADDR *offsets = objfile->section_offsets->offsets;
662
663           /* Pick non-overlapping offsets for sections the user did not
664              place explicitly.  */
665           arg.offsets = objfile->section_offsets;
666           arg.lowest = 0;
667           bfd_map_over_sections (objfile->obfd, place_section, &arg);
668
669           /* Correctly filling in the section offsets is not quite
670              enough.  Relocatable files have two properties that
671              (most) shared objects do not:
672
673              - Their debug information will contain relocations.  Some
674              shared libraries do also, but many do not, so this can not
675              be assumed.
676
677              - If there are multiple code sections they will be loaded
678              at different relative addresses in memory than they are
679              in the objfile, since all sections in the file will start
680              at address zero.
681
682              Because GDB has very limited ability to map from an
683              address in debug info to the correct code section,
684              it relies on adding SECT_OFF_TEXT to things which might be
685              code.  If we clear all the section offsets, and set the
686              section VMAs instead, then symfile_relocate_debug_section
687              will return meaningful debug information pointing at the
688              correct sections.
689
690              GDB has too many different data structures for section
691              addresses - a bfd, objfile, and so_list all have section
692              tables, as does exec_ops.  Some of these could probably
693              be eliminated.  */
694
695           for (cur_sec = abfd->sections; cur_sec != NULL;
696                cur_sec = cur_sec->next)
697             {
698               if ((bfd_get_section_flags (abfd, cur_sec) & SEC_ALLOC) == 0)
699                 continue;
700
701               bfd_set_section_vma (abfd, cur_sec, offsets[cur_sec->index]);
702               exec_set_section_address (bfd_get_filename (abfd), cur_sec->index,
703                                         offsets[cur_sec->index]);
704               offsets[cur_sec->index] = 0;
705             }
706         }
707     }
708
709   /* Remember the bfd indexes for the .text, .data, .bss and
710      .rodata sections. */
711   init_objfile_sect_indices (objfile);
712 }
713
714
715 /* Divide the file into segments, which are individual relocatable units.
716    This is the default version of the sym_fns.sym_segments function for
717    symbol readers that do not have an explicit representation of segments.
718    It assumes that object files do not have segments, and fully linked
719    files have a single segment.  */
720
721 struct symfile_segment_data *
722 default_symfile_segments (bfd *abfd)
723 {
724   int num_sections, i;
725   asection *sect;
726   struct symfile_segment_data *data;
727   CORE_ADDR low, high;
728
729   /* Relocatable files contain enough information to position each
730      loadable section independently; they should not be relocated
731      in segments.  */
732   if ((bfd_get_file_flags (abfd) & (EXEC_P | DYNAMIC)) == 0)
733     return NULL;
734
735   /* Make sure there is at least one loadable section in the file.  */
736   for (sect = abfd->sections; sect != NULL; sect = sect->next)
737     {
738       if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
739         continue;
740
741       break;
742     }
743   if (sect == NULL)
744     return NULL;
745
746   low = bfd_get_section_vma (abfd, sect);
747   high = low + bfd_get_section_size (sect);
748
749   data = XZALLOC (struct symfile_segment_data);
750   data->num_segments = 1;
751   data->segment_bases = XCALLOC (1, CORE_ADDR);
752   data->segment_sizes = XCALLOC (1, CORE_ADDR);
753
754   num_sections = bfd_count_sections (abfd);
755   data->segment_info = XCALLOC (num_sections, int);
756
757   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
758     {
759       CORE_ADDR vma;
760
761       if ((bfd_get_section_flags (abfd, sect) & SEC_ALLOC) == 0)
762         continue;
763
764       vma = bfd_get_section_vma (abfd, sect);
765       if (vma < low)
766         low = vma;
767       if (vma + bfd_get_section_size (sect) > high)
768         high = vma + bfd_get_section_size (sect);
769
770       data->segment_info[i] = 1;
771     }
772
773   data->segment_bases[0] = low;
774   data->segment_sizes[0] = high - low;
775
776   return data;
777 }
778
779 /* Process a symbol file, as either the main file or as a dynamically
780    loaded file.
781
782    OBJFILE is where the symbols are to be read from.
783
784    ADDRS is the list of section load addresses.  If the user has given
785    an 'add-symbol-file' command, then this is the list of offsets and
786    addresses he or she provided as arguments to the command; or, if
787    we're handling a shared library, these are the actual addresses the
788    sections are loaded at, according to the inferior's dynamic linker
789    (as gleaned by GDB's shared library code).  We convert each address
790    into an offset from the section VMA's as it appears in the object
791    file, and then call the file's sym_offsets function to convert this
792    into a format-specific offset table --- a `struct section_offsets'.
793    If ADDRS is non-zero, OFFSETS must be zero.
794
795    OFFSETS is a table of section offsets already in the right
796    format-specific representation.  NUM_OFFSETS is the number of
797    elements present in OFFSETS->offsets.  If OFFSETS is non-zero, we
798    assume this is the proper table the call to sym_offsets described
799    above would produce.  Instead of calling sym_offsets, we just dump
800    it right into objfile->section_offsets.  (When we're re-reading
801    symbols from an objfile, we don't have the original load address
802    list any more; all we have is the section offset table.)  If
803    OFFSETS is non-zero, ADDRS must be zero.
804
805    ADD_FLAGS encodes verbosity level, whether this is main symbol or
806    an extra symbol file such as dynamically loaded code, and wether
807    breakpoint reset should be deferred.  */
808
809 void
810 syms_from_objfile (struct objfile *objfile,
811                    struct section_addr_info *addrs,
812                    struct section_offsets *offsets,
813                    int num_offsets,
814                    int add_flags)
815 {
816   struct section_addr_info *local_addr = NULL;
817   struct cleanup *old_chain;
818   const int mainline = add_flags & SYMFILE_MAINLINE;
819
820   gdb_assert (! (addrs && offsets));
821
822   init_entry_point_info (objfile);
823   objfile->sf = find_sym_fns (objfile->obfd);
824
825   if (objfile->sf == NULL)
826     return;     /* No symbols. */
827
828   /* Make sure that partially constructed symbol tables will be cleaned up
829      if an error occurs during symbol reading.  */
830   old_chain = make_cleanup_free_objfile (objfile);
831
832   /* If ADDRS and OFFSETS are both NULL, put together a dummy address
833      list.  We now establish the convention that an addr of zero means
834      no load address was specified. */
835   if (! addrs && ! offsets)
836     {
837       local_addr
838         = alloc_section_addr_info (bfd_count_sections (objfile->obfd));
839       make_cleanup (xfree, local_addr);
840       addrs = local_addr;
841     }
842
843   /* Now either addrs or offsets is non-zero.  */
844
845   if (mainline)
846     {
847       /* We will modify the main symbol table, make sure that all its users
848          will be cleaned up if an error occurs during symbol reading.  */
849       make_cleanup (clear_symtab_users_cleanup, 0 /*ignore*/);
850
851       /* Since no error yet, throw away the old symbol table.  */
852
853       if (symfile_objfile != NULL)
854         {
855           free_objfile (symfile_objfile);
856           gdb_assert (symfile_objfile == NULL);
857         }
858
859       /* Currently we keep symbols from the add-symbol-file command.
860          If the user wants to get rid of them, they should do "symbol-file"
861          without arguments first.  Not sure this is the best behavior
862          (PR 2207).  */
863
864       (*objfile->sf->sym_new_init) (objfile);
865     }
866
867   /* Convert addr into an offset rather than an absolute address.
868      We find the lowest address of a loaded segment in the objfile,
869      and assume that <addr> is where that got loaded.
870
871      We no longer warn if the lowest section is not a text segment (as
872      happens for the PA64 port.  */
873   if (addrs && addrs->other[0].name)
874     addr_info_make_relative (addrs, objfile->obfd);
875
876   /* Initialize symbol reading routines for this objfile, allow complaints to
877      appear for this new file, and record how verbose to be, then do the
878      initial symbol reading for this file. */
879
880   (*objfile->sf->sym_init) (objfile);
881   clear_complaints (&symfile_complaints, 1, add_flags & SYMFILE_VERBOSE);
882
883   if (addrs)
884     (*objfile->sf->sym_offsets) (objfile, addrs);
885   else
886     {
887       size_t size = SIZEOF_N_SECTION_OFFSETS (num_offsets);
888
889       /* Just copy in the offset table directly as given to us.  */
890       objfile->num_sections = num_offsets;
891       objfile->section_offsets
892         = ((struct section_offsets *)
893            obstack_alloc (&objfile->objfile_obstack, size));
894       memcpy (objfile->section_offsets, offsets, size);
895
896       init_objfile_sect_indices (objfile);
897     }
898
899   (*objfile->sf->sym_read) (objfile, add_flags);
900
901   /* Discard cleanups as symbol reading was successful.  */
902
903   discard_cleanups (old_chain);
904   xfree (local_addr);
905 }
906
907 /* Perform required actions after either reading in the initial
908    symbols for a new objfile, or mapping in the symbols from a reusable
909    objfile. */
910
911 void
912 new_symfile_objfile (struct objfile *objfile, int add_flags)
913 {
914
915   /* If this is the main symbol file we have to clean up all users of the
916      old main symbol file. Otherwise it is sufficient to fixup all the
917      breakpoints that may have been redefined by this symbol file.  */
918   if (add_flags & SYMFILE_MAINLINE)
919     {
920       /* OK, make it the "real" symbol file.  */
921       symfile_objfile = objfile;
922
923       clear_symtab_users ();
924     }
925   else if ((add_flags & SYMFILE_DEFER_BP_RESET) == 0)
926     {
927       breakpoint_re_set ();
928     }
929
930   /* We're done reading the symbol file; finish off complaints.  */
931   clear_complaints (&symfile_complaints, 0, add_flags & SYMFILE_VERBOSE);
932 }
933
934 /* Process a symbol file, as either the main file or as a dynamically
935    loaded file.
936
937    ABFD is a BFD already open on the file, as from symfile_bfd_open.
938    This BFD will be closed on error, and is always consumed by this function.
939
940    ADD_FLAGS encodes verbosity, whether this is main symbol file or
941    extra, such as dynamically loaded code, and what to do with breakpoins.
942
943    ADDRS, OFFSETS, and NUM_OFFSETS are as described for
944    syms_from_objfile, above.
945    ADDRS is ignored when SYMFILE_MAINLINE bit is set in ADD_FLAGS.
946
947    Upon success, returns a pointer to the objfile that was added.
948    Upon failure, jumps back to command level (never returns). */
949
950 static struct objfile *
951 symbol_file_add_with_addrs_or_offsets (bfd *abfd,
952                                        int add_flags,
953                                        struct section_addr_info *addrs,
954                                        struct section_offsets *offsets,
955                                        int num_offsets,
956                                        int flags)
957 {
958   struct objfile *objfile;
959   struct partial_symtab *psymtab;
960   struct cleanup *my_cleanups;
961   const char *name = bfd_get_filename (abfd);
962   const int from_tty = add_flags & SYMFILE_VERBOSE;
963
964   my_cleanups = make_cleanup_bfd_close (abfd);
965
966   /* Give user a chance to burp if we'd be
967      interactively wiping out any existing symbols.  */
968
969   if ((have_full_symbols () || have_partial_symbols ())
970       && (add_flags & SYMFILE_MAINLINE)
971       && from_tty
972       && !query (_("Load new symbol table from \"%s\"? "), name))
973     error (_("Not confirmed."));
974
975   objfile = allocate_objfile (abfd, flags);
976   discard_cleanups (my_cleanups);
977
978   /* We either created a new mapped symbol table, mapped an existing
979      symbol table file which has not had initial symbol reading
980      performed, or need to read an unmapped symbol table. */
981   if (from_tty || info_verbose)
982     {
983       if (deprecated_pre_add_symbol_hook)
984         deprecated_pre_add_symbol_hook (name);
985       else
986         {
987           printf_unfiltered (_("Reading symbols from %s..."), name);
988           wrap_here ("");
989           gdb_flush (gdb_stdout);
990         }
991     }
992   syms_from_objfile (objfile, addrs, offsets, num_offsets,
993                      add_flags);
994
995   /* We now have at least a partial symbol table.  Check to see if the
996      user requested that all symbols be read on initial access via either
997      the gdb startup command line or on a per symbol file basis.  Expand
998      all partial symbol tables for this objfile if so. */
999
1000   if ((flags & OBJF_READNOW) || readnow_symbol_files)
1001     {
1002       if (from_tty || info_verbose)
1003         {
1004           printf_unfiltered (_("expanding to full symbols..."));
1005           wrap_here ("");
1006           gdb_flush (gdb_stdout);
1007         }
1008
1009       for (psymtab = objfile->psymtabs;
1010            psymtab != NULL;
1011            psymtab = psymtab->next)
1012         {
1013           psymtab_to_symtab (psymtab);
1014         }
1015     }
1016
1017   if ((from_tty || info_verbose)
1018       && !objfile_has_symbols (objfile))
1019     {
1020       wrap_here ("");
1021       printf_unfiltered (_("(no debugging symbols found)..."));
1022       wrap_here ("");
1023     }
1024
1025   if (from_tty || info_verbose)
1026     {
1027       if (deprecated_post_add_symbol_hook)
1028         deprecated_post_add_symbol_hook ();
1029       else
1030         printf_unfiltered (_("done.\n"));
1031     }
1032
1033   /* We print some messages regardless of whether 'from_tty ||
1034      info_verbose' is true, so make sure they go out at the right
1035      time.  */
1036   gdb_flush (gdb_stdout);
1037
1038   do_cleanups (my_cleanups);
1039
1040   if (objfile->sf == NULL)
1041     {
1042       observer_notify_new_objfile (objfile);
1043       return objfile;   /* No symbols. */
1044     }
1045
1046   new_symfile_objfile (objfile, add_flags);
1047
1048   observer_notify_new_objfile (objfile);
1049
1050   bfd_cache_close_all ();
1051   return (objfile);
1052 }
1053
1054 /* Add BFD as a separate debug file for OBJFILE.  */
1055
1056 void
1057 symbol_file_add_separate (bfd *bfd, int symfile_flags, struct objfile *objfile)
1058 {
1059   struct objfile *new_objfile;
1060   struct section_addr_info *sap;
1061   struct cleanup *my_cleanup;
1062
1063   /* Create section_addr_info.  We can't directly use offsets from OBJFILE
1064      because sections of BFD may not match sections of OBJFILE and because
1065      vma may have been modified by tools such as prelink.  */
1066   sap = build_section_addr_info_from_objfile (objfile);
1067   my_cleanup = make_cleanup_free_section_addr_info (sap);
1068
1069   new_objfile = symbol_file_add_with_addrs_or_offsets
1070     (bfd, symfile_flags,
1071      sap, NULL, 0,
1072      objfile->flags & (OBJF_REORDERED | OBJF_SHARED | OBJF_READNOW
1073                        | OBJF_USERLOADED));
1074
1075   do_cleanups (my_cleanup);
1076
1077   add_separate_debug_objfile (new_objfile, objfile);
1078 }
1079
1080 /* Process the symbol file ABFD, as either the main file or as a
1081    dynamically loaded file.
1082
1083    See symbol_file_add_with_addrs_or_offsets's comments for
1084    details.  */
1085 struct objfile *
1086 symbol_file_add_from_bfd (bfd *abfd, int add_flags,
1087                           struct section_addr_info *addrs,
1088                           int flags)
1089 {
1090   return symbol_file_add_with_addrs_or_offsets (abfd, add_flags, addrs, 0, 0,
1091                                                 flags);
1092 }
1093
1094
1095 /* Process a symbol file, as either the main file or as a dynamically
1096    loaded file.  See symbol_file_add_with_addrs_or_offsets's comments
1097    for details.  */
1098 struct objfile *
1099 symbol_file_add (char *name, int add_flags, struct section_addr_info *addrs,
1100                  int flags)
1101 {
1102   return symbol_file_add_from_bfd (symfile_bfd_open (name), add_flags, addrs,
1103                                    flags);
1104 }
1105
1106
1107 /* Call symbol_file_add() with default values and update whatever is
1108    affected by the loading of a new main().
1109    Used when the file is supplied in the gdb command line
1110    and by some targets with special loading requirements.
1111    The auxiliary function, symbol_file_add_main_1(), has the flags
1112    argument for the switches that can only be specified in the symbol_file
1113    command itself.  */
1114
1115 void
1116 symbol_file_add_main (char *args, int from_tty)
1117 {
1118   symbol_file_add_main_1 (args, from_tty, 0);
1119 }
1120
1121 static void
1122 symbol_file_add_main_1 (char *args, int from_tty, int flags)
1123 {
1124   const int add_flags = SYMFILE_MAINLINE | (from_tty ? SYMFILE_VERBOSE : 0);
1125   symbol_file_add (args, add_flags, NULL, flags);
1126
1127   /* Getting new symbols may change our opinion about
1128      what is frameless.  */
1129   reinit_frame_cache ();
1130
1131   set_initial_language ();
1132 }
1133
1134 void
1135 symbol_file_clear (int from_tty)
1136 {
1137   if ((have_full_symbols () || have_partial_symbols ())
1138       && from_tty
1139       && (symfile_objfile
1140           ? !query (_("Discard symbol table from `%s'? "),
1141                     symfile_objfile->name)
1142           : !query (_("Discard symbol table? "))))
1143     error (_("Not confirmed."));
1144
1145   free_all_objfiles ();
1146
1147   /* solib descriptors may have handles to objfiles.  Since their
1148      storage has just been released, we'd better wipe the solib
1149      descriptors as well.  */
1150   no_shared_libraries (NULL, from_tty);
1151
1152   gdb_assert (symfile_objfile == NULL);
1153   if (from_tty)
1154     printf_unfiltered (_("No symbol file now.\n"));
1155 }
1156
1157 static char *
1158 get_debug_link_info (struct objfile *objfile, unsigned long *crc32_out)
1159 {
1160   asection *sect;
1161   bfd_size_type debuglink_size;
1162   unsigned long crc32;
1163   char *contents;
1164   int crc_offset;
1165   unsigned char *p;
1166
1167   sect = bfd_get_section_by_name (objfile->obfd, ".gnu_debuglink");
1168
1169   if (sect == NULL)
1170     return NULL;
1171
1172   debuglink_size = bfd_section_size (objfile->obfd, sect);
1173
1174   contents = xmalloc (debuglink_size);
1175   bfd_get_section_contents (objfile->obfd, sect, contents,
1176                             (file_ptr)0, (bfd_size_type)debuglink_size);
1177
1178   /* Crc value is stored after the filename, aligned up to 4 bytes. */
1179   crc_offset = strlen (contents) + 1;
1180   crc_offset = (crc_offset + 3) & ~3;
1181
1182   crc32 = bfd_get_32 (objfile->obfd, (bfd_byte *) (contents + crc_offset));
1183
1184   *crc32_out = crc32;
1185   return contents;
1186 }
1187
1188 static int
1189 separate_debug_file_exists (const char *name, unsigned long crc,
1190                             struct objfile *parent_objfile)
1191 {
1192   unsigned long file_crc = 0;
1193   bfd *abfd;
1194   gdb_byte buffer[8*1024];
1195   int count;
1196   struct stat parent_stat, abfd_stat;
1197
1198   /* Find a separate debug info file as if symbols would be present in
1199      PARENT_OBJFILE itself this function would not be called.  .gnu_debuglink
1200      section can contain just the basename of PARENT_OBJFILE without any
1201      ".debug" suffix as "/usr/lib/debug/path/to/file" is a separate tree where
1202      the separate debug infos with the same basename can exist. */
1203
1204   if (strcmp (name, parent_objfile->name) == 0)
1205     return 0;
1206
1207   abfd = bfd_open_maybe_remote (name);
1208
1209   if (!abfd)
1210     return 0;
1211
1212   /* Verify symlinks were not the cause of strcmp name difference above.
1213
1214      Some operating systems, e.g. Windows, do not provide a meaningful
1215      st_ino; they always set it to zero.  (Windows does provide a
1216      meaningful st_dev.)  Do not indicate a duplicate library in that
1217      case.  While there is no guarantee that a system that provides
1218      meaningful inode numbers will never set st_ino to zero, this is
1219      merely an optimization, so we do not need to worry about false
1220      negatives.  */
1221
1222   if (bfd_stat (abfd, &abfd_stat) == 0
1223       && bfd_stat (parent_objfile->obfd, &parent_stat) == 0
1224       && abfd_stat.st_dev == parent_stat.st_dev
1225       && abfd_stat.st_ino == parent_stat.st_ino
1226       && abfd_stat.st_ino != 0)
1227     {
1228       bfd_close (abfd);
1229       return 0;
1230     }
1231
1232   while ((count = bfd_bread (buffer, sizeof (buffer), abfd)) > 0)
1233     file_crc = gnu_debuglink_crc32 (file_crc, buffer, count);
1234
1235   bfd_close (abfd);
1236
1237   if (crc != file_crc)
1238     {
1239       warning (_("the debug information found in \"%s\""
1240                  " does not match \"%s\" (CRC mismatch).\n"),
1241                name, parent_objfile->name);
1242       return 0;
1243     }
1244
1245   return 1;
1246 }
1247
1248 char *debug_file_directory = NULL;
1249 static void
1250 show_debug_file_directory (struct ui_file *file, int from_tty,
1251                            struct cmd_list_element *c, const char *value)
1252 {
1253   fprintf_filtered (file, _("\
1254 The directory where separate debug symbols are searched for is \"%s\".\n"),
1255                     value);
1256 }
1257
1258 #if ! defined (DEBUG_SUBDIRECTORY)
1259 #define DEBUG_SUBDIRECTORY ".debug"
1260 #endif
1261
1262 char *
1263 find_separate_debug_file_by_debuglink (struct objfile *objfile)
1264 {
1265   asection *sect;
1266   char *basename, *name_copy, *debugdir;
1267   char *dir = NULL;
1268   char *debugfile = NULL;
1269   char *canon_name = NULL;
1270   bfd_size_type debuglink_size;
1271   unsigned long crc32;
1272   int i;
1273
1274   basename = get_debug_link_info (objfile, &crc32);
1275
1276   if (basename == NULL)
1277     /* There's no separate debug info, hence there's no way we could
1278        load it => no warning.  */
1279     goto cleanup_return_debugfile;
1280
1281   dir = xstrdup (objfile->name);
1282
1283   /* Strip off the final filename part, leaving the directory name,
1284      followed by a slash.  Objfile names should always be absolute and
1285      tilde-expanded, so there should always be a slash in there
1286      somewhere.  */
1287   for (i = strlen(dir) - 1; i >= 0; i--)
1288     {
1289       if (IS_DIR_SEPARATOR (dir[i]))
1290         break;
1291     }
1292   gdb_assert (i >= 0 && IS_DIR_SEPARATOR (dir[i]));
1293   dir[i+1] = '\0';
1294
1295   /* Set I to max (strlen (canon_name), strlen (dir)). */
1296   canon_name = lrealpath (dir);
1297   i = strlen (dir);
1298   if (canon_name && strlen (canon_name) > i)
1299     i = strlen (canon_name);
1300
1301   debugfile = xmalloc (strlen (debug_file_directory) + 1
1302                        + i
1303                        + strlen (DEBUG_SUBDIRECTORY)
1304                        + strlen ("/")
1305                        + strlen (basename)
1306                        + 1);
1307
1308   /* First try in the same directory as the original file.  */
1309   strcpy (debugfile, dir);
1310   strcat (debugfile, basename);
1311
1312   if (separate_debug_file_exists (debugfile, crc32, objfile))
1313     goto cleanup_return_debugfile;
1314
1315   /* Then try in the subdirectory named DEBUG_SUBDIRECTORY.  */
1316   strcpy (debugfile, dir);
1317   strcat (debugfile, DEBUG_SUBDIRECTORY);
1318   strcat (debugfile, "/");
1319   strcat (debugfile, basename);
1320
1321   if (separate_debug_file_exists (debugfile, crc32, objfile))
1322     goto cleanup_return_debugfile;
1323
1324   /* Then try in the global debugfile directories.
1325  
1326      Keep backward compatibility so that DEBUG_FILE_DIRECTORY being "" will
1327      cause "/..." lookups.  */
1328
1329   debugdir = debug_file_directory;
1330   do
1331     {
1332       char *debugdir_end;
1333
1334       while (*debugdir == DIRNAME_SEPARATOR)
1335         debugdir++;
1336
1337       debugdir_end = strchr (debugdir, DIRNAME_SEPARATOR);
1338       if (debugdir_end == NULL)
1339         debugdir_end = &debugdir[strlen (debugdir)];
1340
1341       memcpy (debugfile, debugdir, debugdir_end - debugdir);
1342       debugfile[debugdir_end - debugdir] = 0;
1343       strcat (debugfile, "/");
1344       strcat (debugfile, dir);
1345       strcat (debugfile, basename);
1346
1347       if (separate_debug_file_exists (debugfile, crc32, objfile))
1348         goto cleanup_return_debugfile;
1349
1350       /* If the file is in the sysroot, try using its base path in the
1351          global debugfile directory.  */
1352       if (canon_name
1353           && strncmp (canon_name, gdb_sysroot, strlen (gdb_sysroot)) == 0
1354           && IS_DIR_SEPARATOR (canon_name[strlen (gdb_sysroot)]))
1355         {
1356           memcpy (debugfile, debugdir, debugdir_end - debugdir);
1357           debugfile[debugdir_end - debugdir] = 0;
1358           strcat (debugfile, canon_name + strlen (gdb_sysroot));
1359           strcat (debugfile, "/");
1360           strcat (debugfile, basename);
1361
1362           if (separate_debug_file_exists (debugfile, crc32, objfile))
1363             goto cleanup_return_debugfile;
1364         }
1365
1366       debugdir = debugdir_end;
1367     }
1368   while (*debugdir != 0);
1369   
1370   xfree (debugfile);
1371   debugfile = NULL;
1372
1373 cleanup_return_debugfile:
1374   xfree (canon_name);
1375   xfree (basename);
1376   xfree (dir);
1377   return debugfile;
1378 }
1379
1380
1381 /* This is the symbol-file command.  Read the file, analyze its
1382    symbols, and add a struct symtab to a symtab list.  The syntax of
1383    the command is rather bizarre:
1384
1385    1. The function buildargv implements various quoting conventions
1386    which are undocumented and have little or nothing in common with
1387    the way things are quoted (or not quoted) elsewhere in GDB.
1388
1389    2. Options are used, which are not generally used in GDB (perhaps
1390    "set mapped on", "set readnow on" would be better)
1391
1392    3. The order of options matters, which is contrary to GNU
1393    conventions (because it is confusing and inconvenient).  */
1394
1395 void
1396 symbol_file_command (char *args, int from_tty)
1397 {
1398   dont_repeat ();
1399
1400   if (args == NULL)
1401     {
1402       symbol_file_clear (from_tty);
1403     }
1404   else
1405     {
1406       char **argv = gdb_buildargv (args);
1407       int flags = OBJF_USERLOADED;
1408       struct cleanup *cleanups;
1409       char *name = NULL;
1410
1411       cleanups = make_cleanup_freeargv (argv);
1412       while (*argv != NULL)
1413         {
1414           if (strcmp (*argv, "-readnow") == 0)
1415             flags |= OBJF_READNOW;
1416           else if (**argv == '-')
1417             error (_("unknown option `%s'"), *argv);
1418           else
1419             {
1420               symbol_file_add_main_1 (*argv, from_tty, flags);
1421               name = *argv;
1422             }
1423
1424           argv++;
1425         }
1426
1427       if (name == NULL)
1428         error (_("no symbol file name was specified"));
1429
1430       do_cleanups (cleanups);
1431     }
1432 }
1433
1434 /* Set the initial language.
1435
1436    FIXME: A better solution would be to record the language in the
1437    psymtab when reading partial symbols, and then use it (if known) to
1438    set the language.  This would be a win for formats that encode the
1439    language in an easily discoverable place, such as DWARF.  For
1440    stabs, we can jump through hoops looking for specially named
1441    symbols or try to intuit the language from the specific type of
1442    stabs we find, but we can't do that until later when we read in
1443    full symbols.  */
1444
1445 void
1446 set_initial_language (void)
1447 {
1448   struct partial_symtab *pst;
1449   enum language lang = language_unknown;
1450
1451   pst = find_main_psymtab ();
1452   if (pst != NULL)
1453     {
1454       if (pst->filename != NULL)
1455         lang = deduce_language_from_filename (pst->filename);
1456
1457       if (lang == language_unknown)
1458         {
1459           /* Make C the default language */
1460           lang = language_c;
1461         }
1462
1463       set_language (lang);
1464       expected_language = current_language; /* Don't warn the user.  */
1465     }
1466 }
1467
1468 /* If NAME is a remote name open the file using remote protocol, otherwise
1469    open it normally.  */
1470
1471 bfd *
1472 bfd_open_maybe_remote (const char *name)
1473 {
1474   if (remote_filename_p (name))
1475     return remote_bfd_open (name, gnutarget);
1476   else
1477     return bfd_openr (name, gnutarget);
1478 }
1479
1480
1481 /* Open the file specified by NAME and hand it off to BFD for
1482    preliminary analysis.  Return a newly initialized bfd *, which
1483    includes a newly malloc'd` copy of NAME (tilde-expanded and made
1484    absolute).  In case of trouble, error() is called.  */
1485
1486 bfd *
1487 symfile_bfd_open (char *name)
1488 {
1489   bfd *sym_bfd;
1490   int desc;
1491   char *absolute_name;
1492
1493   if (remote_filename_p (name))
1494     {
1495       name = xstrdup (name);
1496       sym_bfd = remote_bfd_open (name, gnutarget);
1497       if (!sym_bfd)
1498         {
1499           make_cleanup (xfree, name);
1500           error (_("`%s': can't open to read symbols: %s."), name,
1501                  bfd_errmsg (bfd_get_error ()));
1502         }
1503
1504       if (!bfd_check_format (sym_bfd, bfd_object))
1505         {
1506           bfd_close (sym_bfd);
1507           make_cleanup (xfree, name);
1508           error (_("`%s': can't read symbols: %s."), name,
1509                  bfd_errmsg (bfd_get_error ()));
1510         }
1511
1512       return sym_bfd;
1513     }
1514
1515   name = tilde_expand (name);   /* Returns 1st new malloc'd copy.  */
1516
1517   /* Look down path for it, allocate 2nd new malloc'd copy.  */
1518   desc = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST, name,
1519                 O_RDONLY | O_BINARY, &absolute_name);
1520 #if defined(__GO32__) || defined(_WIN32) || defined (__CYGWIN__)
1521   if (desc < 0)
1522     {
1523       char *exename = alloca (strlen (name) + 5);
1524       strcat (strcpy (exename, name), ".exe");
1525       desc = openp (getenv ("PATH"), OPF_TRY_CWD_FIRST, exename,
1526                     O_RDONLY | O_BINARY, &absolute_name);
1527     }
1528 #endif
1529   if (desc < 0)
1530     {
1531       make_cleanup (xfree, name);
1532       perror_with_name (name);
1533     }
1534
1535   /* Free 1st new malloc'd copy, but keep the 2nd malloc'd copy in
1536      bfd.  It'll be freed in free_objfile(). */
1537   xfree (name);
1538   name = absolute_name;
1539
1540   sym_bfd = bfd_fopen (name, gnutarget, FOPEN_RB, desc);
1541   if (!sym_bfd)
1542     {
1543       close (desc);
1544       make_cleanup (xfree, name);
1545       error (_("`%s': can't open to read symbols: %s."), name,
1546              bfd_errmsg (bfd_get_error ()));
1547     }
1548   bfd_set_cacheable (sym_bfd, 1);
1549
1550   if (!bfd_check_format (sym_bfd, bfd_object))
1551     {
1552       /* FIXME: should be checking for errors from bfd_close (for one
1553          thing, on error it does not free all the storage associated
1554          with the bfd).  */
1555       bfd_close (sym_bfd);      /* This also closes desc.  */
1556       make_cleanup (xfree, name);
1557       error (_("`%s': can't read symbols: %s."), name,
1558              bfd_errmsg (bfd_get_error ()));
1559     }
1560
1561   /* bfd_usrdata exists for applications and libbfd must not touch it.  */
1562   gdb_assert (bfd_usrdata (sym_bfd) == NULL);
1563
1564   return sym_bfd;
1565 }
1566
1567 /* Return the section index for SECTION_NAME on OBJFILE.  Return -1 if
1568    the section was not found.  */
1569
1570 int
1571 get_section_index (struct objfile *objfile, char *section_name)
1572 {
1573   asection *sect = bfd_get_section_by_name (objfile->obfd, section_name);
1574
1575   if (sect)
1576     return sect->index;
1577   else
1578     return -1;
1579 }
1580
1581 /* Link SF into the global symtab_fns list.  Called on startup by the
1582    _initialize routine in each object file format reader, to register
1583    information about each format the the reader is prepared to
1584    handle. */
1585
1586 void
1587 add_symtab_fns (struct sym_fns *sf)
1588 {
1589   sf->next = symtab_fns;
1590   symtab_fns = sf;
1591 }
1592
1593 /* Initialize OBJFILE to read symbols from its associated BFD.  It
1594    either returns or calls error().  The result is an initialized
1595    struct sym_fns in the objfile structure, that contains cached
1596    information about the symbol file.  */
1597
1598 static struct sym_fns *
1599 find_sym_fns (bfd *abfd)
1600 {
1601   struct sym_fns *sf;
1602   enum bfd_flavour our_flavour = bfd_get_flavour (abfd);
1603
1604   if (our_flavour == bfd_target_srec_flavour
1605       || our_flavour == bfd_target_ihex_flavour
1606       || our_flavour == bfd_target_tekhex_flavour)
1607     return NULL;        /* No symbols.  */
1608
1609   for (sf = symtab_fns; sf != NULL; sf = sf->next)
1610     if (our_flavour == sf->sym_flavour)
1611       return sf;
1612
1613   error (_("I'm sorry, Dave, I can't do that.  Symbol format `%s' unknown."),
1614          bfd_get_target (abfd));
1615 }
1616 \f
1617
1618 /* This function runs the load command of our current target.  */
1619
1620 static void
1621 load_command (char *arg, int from_tty)
1622 {
1623   /* The user might be reloading because the binary has changed.  Take
1624      this opportunity to check.  */
1625   reopen_exec_file ();
1626   reread_symbols ();
1627
1628   if (arg == NULL)
1629     {
1630       char *parg;
1631       int count = 0;
1632
1633       parg = arg = get_exec_file (1);
1634
1635       /* Count how many \ " ' tab space there are in the name.  */
1636       while ((parg = strpbrk (parg, "\\\"'\t ")))
1637         {
1638           parg++;
1639           count++;
1640         }
1641
1642       if (count)
1643         {
1644           /* We need to quote this string so buildargv can pull it apart.  */
1645           char *temp = xmalloc (strlen (arg) + count + 1 );
1646           char *ptemp = temp;
1647           char *prev;
1648
1649           make_cleanup (xfree, temp);
1650
1651           prev = parg = arg;
1652           while ((parg = strpbrk (parg, "\\\"'\t ")))
1653             {
1654               strncpy (ptemp, prev, parg - prev);
1655               ptemp += parg - prev;
1656               prev = parg++;
1657               *ptemp++ = '\\';
1658             }
1659           strcpy (ptemp, prev);
1660
1661           arg = temp;
1662         }
1663     }
1664
1665   target_load (arg, from_tty);
1666
1667   /* After re-loading the executable, we don't really know which
1668      overlays are mapped any more.  */
1669   overlay_cache_invalid = 1;
1670 }
1671
1672 /* This version of "load" should be usable for any target.  Currently
1673    it is just used for remote targets, not inftarg.c or core files,
1674    on the theory that only in that case is it useful.
1675
1676    Avoiding xmodem and the like seems like a win (a) because we don't have
1677    to worry about finding it, and (b) On VMS, fork() is very slow and so
1678    we don't want to run a subprocess.  On the other hand, I'm not sure how
1679    performance compares.  */
1680
1681 static int validate_download = 0;
1682
1683 /* Callback service function for generic_load (bfd_map_over_sections).  */
1684
1685 static void
1686 add_section_size_callback (bfd *abfd, asection *asec, void *data)
1687 {
1688   bfd_size_type *sum = data;
1689
1690   *sum += bfd_get_section_size (asec);
1691 }
1692
1693 /* Opaque data for load_section_callback.  */
1694 struct load_section_data {
1695   unsigned long load_offset;
1696   struct load_progress_data *progress_data;
1697   VEC(memory_write_request_s) *requests;
1698 };
1699
1700 /* Opaque data for load_progress.  */
1701 struct load_progress_data {
1702   /* Cumulative data.  */
1703   unsigned long write_count;
1704   unsigned long data_count;
1705   bfd_size_type total_size;
1706 };
1707
1708 /* Opaque data for load_progress for a single section.  */
1709 struct load_progress_section_data {
1710   struct load_progress_data *cumulative;
1711
1712   /* Per-section data.  */
1713   const char *section_name;
1714   ULONGEST section_sent;
1715   ULONGEST section_size;
1716   CORE_ADDR lma;
1717   gdb_byte *buffer;
1718 };
1719
1720 /* Target write callback routine for progress reporting.  */
1721
1722 static void
1723 load_progress (ULONGEST bytes, void *untyped_arg)
1724 {
1725   struct load_progress_section_data *args = untyped_arg;
1726   struct load_progress_data *totals;
1727
1728   if (args == NULL)
1729     /* Writing padding data.  No easy way to get at the cumulative
1730        stats, so just ignore this.  */
1731     return;
1732
1733   totals = args->cumulative;
1734
1735   if (bytes == 0 && args->section_sent == 0)
1736     {
1737       /* The write is just starting.  Let the user know we've started
1738          this section.  */
1739       ui_out_message (uiout, 0, "Loading section %s, size %s lma %s\n",
1740                       args->section_name, hex_string (args->section_size),
1741                       paddress (target_gdbarch, args->lma));
1742       return;
1743     }
1744
1745   if (validate_download)
1746     {
1747       /* Broken memories and broken monitors manifest themselves here
1748          when bring new computers to life.  This doubles already slow
1749          downloads.  */
1750       /* NOTE: cagney/1999-10-18: A more efficient implementation
1751          might add a verify_memory() method to the target vector and
1752          then use that.  remote.c could implement that method using
1753          the ``qCRC'' packet.  */
1754       gdb_byte *check = xmalloc (bytes);
1755       struct cleanup *verify_cleanups = make_cleanup (xfree, check);
1756
1757       if (target_read_memory (args->lma, check, bytes) != 0)
1758         error (_("Download verify read failed at %s"),
1759                paddress (target_gdbarch, args->lma));
1760       if (memcmp (args->buffer, check, bytes) != 0)
1761         error (_("Download verify compare failed at %s"),
1762                paddress (target_gdbarch, args->lma));
1763       do_cleanups (verify_cleanups);
1764     }
1765   totals->data_count += bytes;
1766   args->lma += bytes;
1767   args->buffer += bytes;
1768   totals->write_count += 1;
1769   args->section_sent += bytes;
1770   if (quit_flag
1771       || (deprecated_ui_load_progress_hook != NULL
1772           && deprecated_ui_load_progress_hook (args->section_name,
1773                                                args->section_sent)))
1774     error (_("Canceled the download"));
1775
1776   if (deprecated_show_load_progress != NULL)
1777     deprecated_show_load_progress (args->section_name,
1778                                    args->section_sent,
1779                                    args->section_size,
1780                                    totals->data_count,
1781                                    totals->total_size);
1782 }
1783
1784 /* Callback service function for generic_load (bfd_map_over_sections).  */
1785
1786 static void
1787 load_section_callback (bfd *abfd, asection *asec, void *data)
1788 {
1789   struct memory_write_request *new_request;
1790   struct load_section_data *args = data;
1791   struct load_progress_section_data *section_data;
1792   bfd_size_type size = bfd_get_section_size (asec);
1793   gdb_byte *buffer;
1794   const char *sect_name = bfd_get_section_name (abfd, asec);
1795
1796   if ((bfd_get_section_flags (abfd, asec) & SEC_LOAD) == 0)
1797     return;
1798
1799   if (size == 0)
1800     return;
1801
1802   new_request = VEC_safe_push (memory_write_request_s,
1803                                args->requests, NULL);
1804   memset (new_request, 0, sizeof (struct memory_write_request));
1805   section_data = xcalloc (1, sizeof (struct load_progress_section_data));
1806   new_request->begin = bfd_section_lma (abfd, asec) + args->load_offset;
1807   new_request->end = new_request->begin + size; /* FIXME Should size be in instead?  */
1808   new_request->data = xmalloc (size);
1809   new_request->baton = section_data;
1810
1811   buffer = new_request->data;
1812
1813   section_data->cumulative = args->progress_data;
1814   section_data->section_name = sect_name;
1815   section_data->section_size = size;
1816   section_data->lma = new_request->begin;
1817   section_data->buffer = buffer;
1818
1819   bfd_get_section_contents (abfd, asec, buffer, 0, size);
1820 }
1821
1822 /* Clean up an entire memory request vector, including load
1823    data and progress records.  */
1824
1825 static void
1826 clear_memory_write_data (void *arg)
1827 {
1828   VEC(memory_write_request_s) **vec_p = arg;
1829   VEC(memory_write_request_s) *vec = *vec_p;
1830   int i;
1831   struct memory_write_request *mr;
1832
1833   for (i = 0; VEC_iterate (memory_write_request_s, vec, i, mr); ++i)
1834     {
1835       xfree (mr->data);
1836       xfree (mr->baton);
1837     }
1838   VEC_free (memory_write_request_s, vec);
1839 }
1840
1841 void
1842 generic_load (char *args, int from_tty)
1843 {
1844   bfd *loadfile_bfd;
1845   struct timeval start_time, end_time;
1846   char *filename;
1847   struct cleanup *old_cleanups = make_cleanup (null_cleanup, 0);
1848   struct load_section_data cbdata;
1849   struct load_progress_data total_progress;
1850
1851   CORE_ADDR entry;
1852   char **argv;
1853
1854   memset (&cbdata, 0, sizeof (cbdata));
1855   memset (&total_progress, 0, sizeof (total_progress));
1856   cbdata.progress_data = &total_progress;
1857
1858   make_cleanup (clear_memory_write_data, &cbdata.requests);
1859
1860   if (args == NULL)
1861     error_no_arg (_("file to load"));
1862
1863   argv = gdb_buildargv (args);
1864   make_cleanup_freeargv (argv);
1865
1866   filename = tilde_expand (argv[0]);
1867   make_cleanup (xfree, filename);
1868
1869   if (argv[1] != NULL)
1870     {
1871       char *endptr;
1872
1873       cbdata.load_offset = strtoul (argv[1], &endptr, 0);
1874
1875       /* If the last word was not a valid number then
1876          treat it as a file name with spaces in.  */
1877       if (argv[1] == endptr)
1878         error (_("Invalid download offset:%s."), argv[1]);
1879
1880       if (argv[2] != NULL)
1881         error (_("Too many parameters."));
1882     }
1883
1884   /* Open the file for loading. */
1885   loadfile_bfd = bfd_openr (filename, gnutarget);
1886   if (loadfile_bfd == NULL)
1887     {
1888       perror_with_name (filename);
1889       return;
1890     }
1891
1892   /* FIXME: should be checking for errors from bfd_close (for one thing,
1893      on error it does not free all the storage associated with the
1894      bfd).  */
1895   make_cleanup_bfd_close (loadfile_bfd);
1896
1897   if (!bfd_check_format (loadfile_bfd, bfd_object))
1898     {
1899       error (_("\"%s\" is not an object file: %s"), filename,
1900              bfd_errmsg (bfd_get_error ()));
1901     }
1902
1903   bfd_map_over_sections (loadfile_bfd, add_section_size_callback,
1904                          (void *) &total_progress.total_size);
1905
1906   bfd_map_over_sections (loadfile_bfd, load_section_callback, &cbdata);
1907
1908   gettimeofday (&start_time, NULL);
1909
1910   if (target_write_memory_blocks (cbdata.requests, flash_discard,
1911                                   load_progress) != 0)
1912     error (_("Load failed"));
1913
1914   gettimeofday (&end_time, NULL);
1915
1916   entry = bfd_get_start_address (loadfile_bfd);
1917   ui_out_text (uiout, "Start address ");
1918   ui_out_field_fmt (uiout, "address", "%s", paddress (target_gdbarch, entry));
1919   ui_out_text (uiout, ", load size ");
1920   ui_out_field_fmt (uiout, "load-size", "%lu", total_progress.data_count);
1921   ui_out_text (uiout, "\n");
1922   /* We were doing this in remote-mips.c, I suspect it is right
1923      for other targets too.  */
1924   regcache_write_pc (get_current_regcache (), entry);
1925
1926   /* FIXME: are we supposed to call symbol_file_add or not?  According
1927      to a comment from remote-mips.c (where a call to symbol_file_add
1928      was commented out), making the call confuses GDB if more than one
1929      file is loaded in.  Some targets do (e.g., remote-vx.c) but
1930      others don't (or didn't - perhaps they have all been deleted).  */
1931
1932   print_transfer_performance (gdb_stdout, total_progress.data_count,
1933                               total_progress.write_count,
1934                               &start_time, &end_time);
1935
1936   do_cleanups (old_cleanups);
1937 }
1938
1939 /* Report how fast the transfer went. */
1940
1941 /* DEPRECATED: cagney/1999-10-18: report_transfer_performance is being
1942    replaced by print_transfer_performance (with a very different
1943    function signature). */
1944
1945 void
1946 report_transfer_performance (unsigned long data_count, time_t start_time,
1947                              time_t end_time)
1948 {
1949   struct timeval start, end;
1950
1951   start.tv_sec = start_time;
1952   start.tv_usec = 0;
1953   end.tv_sec = end_time;
1954   end.tv_usec = 0;
1955
1956   print_transfer_performance (gdb_stdout, data_count, 0, &start, &end);
1957 }
1958
1959 void
1960 print_transfer_performance (struct ui_file *stream,
1961                             unsigned long data_count,
1962                             unsigned long write_count,
1963                             const struct timeval *start_time,
1964                             const struct timeval *end_time)
1965 {
1966   ULONGEST time_count;
1967
1968   /* Compute the elapsed time in milliseconds, as a tradeoff between
1969      accuracy and overflow.  */
1970   time_count = (end_time->tv_sec - start_time->tv_sec) * 1000;
1971   time_count += (end_time->tv_usec - start_time->tv_usec) / 1000;
1972
1973   ui_out_text (uiout, "Transfer rate: ");
1974   if (time_count > 0)
1975     {
1976       unsigned long rate = ((ULONGEST) data_count * 1000) / time_count;
1977
1978       if (ui_out_is_mi_like_p (uiout))
1979         {
1980           ui_out_field_fmt (uiout, "transfer-rate", "%lu", rate * 8);
1981           ui_out_text (uiout, " bits/sec");
1982         }
1983       else if (rate < 1024)
1984         {
1985           ui_out_field_fmt (uiout, "transfer-rate", "%lu", rate);
1986           ui_out_text (uiout, " bytes/sec");
1987         }
1988       else
1989         {
1990           ui_out_field_fmt (uiout, "transfer-rate", "%lu", rate / 1024);
1991           ui_out_text (uiout, " KB/sec");
1992         }
1993     }
1994   else
1995     {
1996       ui_out_field_fmt (uiout, "transferred-bits", "%lu", (data_count * 8));
1997       ui_out_text (uiout, " bits in <1 sec");
1998     }
1999   if (write_count > 0)
2000     {
2001       ui_out_text (uiout, ", ");
2002       ui_out_field_fmt (uiout, "write-rate", "%lu", data_count / write_count);
2003       ui_out_text (uiout, " bytes/write");
2004     }
2005   ui_out_text (uiout, ".\n");
2006 }
2007
2008 /* This function allows the addition of incrementally linked object files.
2009    It does not modify any state in the target, only in the debugger.  */
2010 /* Note: ezannoni 2000-04-13 This function/command used to have a
2011    special case syntax for the rombug target (Rombug is the boot
2012    monitor for Microware's OS-9 / OS-9000, see remote-os9k.c). In the
2013    rombug case, the user doesn't need to supply a text address,
2014    instead a call to target_link() (in target.c) would supply the
2015    value to use. We are now discontinuing this type of ad hoc syntax. */
2016
2017 static void
2018 add_symbol_file_command (char *args, int from_tty)
2019 {
2020   struct gdbarch *gdbarch = get_current_arch ();
2021   char *filename = NULL;
2022   int flags = OBJF_USERLOADED;
2023   char *arg;
2024   int expecting_option = 0;
2025   int section_index = 0;
2026   int argcnt = 0;
2027   int sec_num = 0;
2028   int i;
2029   int expecting_sec_name = 0;
2030   int expecting_sec_addr = 0;
2031   char **argv;
2032
2033   struct sect_opt
2034   {
2035     char *name;
2036     char *value;
2037   };
2038
2039   struct section_addr_info *section_addrs;
2040   struct sect_opt *sect_opts = NULL;
2041   size_t num_sect_opts = 0;
2042   struct cleanup *my_cleanups = make_cleanup (null_cleanup, NULL);
2043
2044   num_sect_opts = 16;
2045   sect_opts = (struct sect_opt *) xmalloc (num_sect_opts
2046                                            * sizeof (struct sect_opt));
2047
2048   dont_repeat ();
2049
2050   if (args == NULL)
2051     error (_("add-symbol-file takes a file name and an address"));
2052
2053   argv = gdb_buildargv (args);
2054   make_cleanup_freeargv (argv);
2055
2056   for (arg = argv[0], argcnt = 0; arg != NULL; arg = argv[++argcnt])
2057     {
2058       /* Process the argument. */
2059       if (argcnt == 0)
2060         {
2061           /* The first argument is the file name. */
2062           filename = tilde_expand (arg);
2063           make_cleanup (xfree, filename);
2064         }
2065       else
2066         if (argcnt == 1)
2067           {
2068             /* The second argument is always the text address at which
2069                to load the program. */
2070             sect_opts[section_index].name = ".text";
2071             sect_opts[section_index].value = arg;
2072             if (++section_index >= num_sect_opts)
2073               {
2074                 num_sect_opts *= 2;
2075                 sect_opts = ((struct sect_opt *)
2076                              xrealloc (sect_opts,
2077                                        num_sect_opts
2078                                        * sizeof (struct sect_opt)));
2079               }
2080           }
2081         else
2082           {
2083             /* It's an option (starting with '-') or it's an argument
2084                to an option */
2085
2086             if (*arg == '-')
2087               {
2088                 if (strcmp (arg, "-readnow") == 0)
2089                   flags |= OBJF_READNOW;
2090                 else if (strcmp (arg, "-s") == 0)
2091                   {
2092                     expecting_sec_name = 1;
2093                     expecting_sec_addr = 1;
2094                   }
2095               }
2096             else
2097               {
2098                 if (expecting_sec_name)
2099                   {
2100                     sect_opts[section_index].name = arg;
2101                     expecting_sec_name = 0;
2102                   }
2103                 else
2104                   if (expecting_sec_addr)
2105                     {
2106                       sect_opts[section_index].value = arg;
2107                       expecting_sec_addr = 0;
2108                       if (++section_index >= num_sect_opts)
2109                         {
2110                           num_sect_opts *= 2;
2111                           sect_opts = ((struct sect_opt *)
2112                                        xrealloc (sect_opts,
2113                                                  num_sect_opts
2114                                                  * sizeof (struct sect_opt)));
2115                         }
2116                     }
2117                   else
2118                     error (_("USAGE: add-symbol-file <filename> <textaddress> [-mapped] [-readnow] [-s <secname> <addr>]*"));
2119               }
2120           }
2121     }
2122
2123   /* This command takes at least two arguments.  The first one is a
2124      filename, and the second is the address where this file has been
2125      loaded.  Abort now if this address hasn't been provided by the
2126      user.  */
2127   if (section_index < 1)
2128     error (_("The address where %s has been loaded is missing"), filename);
2129
2130   /* Print the prompt for the query below. And save the arguments into
2131      a sect_addr_info structure to be passed around to other
2132      functions.  We have to split this up into separate print
2133      statements because hex_string returns a local static
2134      string. */
2135
2136   printf_unfiltered (_("add symbol table from file \"%s\" at\n"), filename);
2137   section_addrs = alloc_section_addr_info (section_index);
2138   make_cleanup (xfree, section_addrs);
2139   for (i = 0; i < section_index; i++)
2140     {
2141       CORE_ADDR addr;
2142       char *val = sect_opts[i].value;
2143       char *sec = sect_opts[i].name;
2144
2145       addr = parse_and_eval_address (val);
2146
2147       /* Here we store the section offsets in the order they were
2148          entered on the command line. */
2149       section_addrs->other[sec_num].name = sec;
2150       section_addrs->other[sec_num].addr = addr;
2151       printf_unfiltered ("\t%s_addr = %s\n", sec,
2152                          paddress (gdbarch, addr));
2153       sec_num++;
2154
2155       /* The object's sections are initialized when a
2156          call is made to build_objfile_section_table (objfile).
2157          This happens in reread_symbols.
2158          At this point, we don't know what file type this is,
2159          so we can't determine what section names are valid.  */
2160     }
2161
2162   if (from_tty && (!query ("%s", "")))
2163     error (_("Not confirmed."));
2164
2165   symbol_file_add (filename, from_tty ? SYMFILE_VERBOSE : 0,
2166                    section_addrs, flags);
2167
2168   /* Getting new symbols may change our opinion about what is
2169      frameless.  */
2170   reinit_frame_cache ();
2171   do_cleanups (my_cleanups);
2172 }
2173 \f
2174
2175 /* Re-read symbols if a symbol-file has changed.  */
2176 void
2177 reread_symbols (void)
2178 {
2179   struct objfile *objfile;
2180   long new_modtime;
2181   int reread_one = 0;
2182   struct stat new_statbuf;
2183   int res;
2184
2185   /* With the addition of shared libraries, this should be modified,
2186      the load time should be saved in the partial symbol tables, since
2187      different tables may come from different source files.  FIXME.
2188      This routine should then walk down each partial symbol table
2189      and see if the symbol table that it originates from has been changed */
2190
2191   for (objfile = object_files; objfile; objfile = objfile->next)
2192     {
2193       /* solib-sunos.c creates one objfile with obfd.  */
2194       if (objfile->obfd == NULL)
2195         continue;
2196
2197       /* Separate debug objfiles are handled in the main objfile.  */
2198       if (objfile->separate_debug_objfile_backlink)
2199         continue;
2200
2201 #ifdef DEPRECATED_IBM6000_TARGET
2202       /* If this object is from a shared library, then you should
2203          stat on the library name, not member name. */
2204
2205       if (objfile->obfd->my_archive)
2206         res = stat (objfile->obfd->my_archive->filename, &new_statbuf);
2207       else
2208 #endif
2209         res = stat (objfile->name, &new_statbuf);
2210       if (res != 0)
2211         {
2212           /* FIXME, should use print_sys_errmsg but it's not filtered. */
2213           printf_unfiltered (_("`%s' has disappeared; keeping its symbols.\n"),
2214                              objfile->name);
2215           continue;
2216         }
2217       new_modtime = new_statbuf.st_mtime;
2218       if (new_modtime != objfile->mtime)
2219         {
2220           struct cleanup *old_cleanups;
2221           struct section_offsets *offsets;
2222           int num_offsets;
2223           char *obfd_filename;
2224
2225           printf_unfiltered (_("`%s' has changed; re-reading symbols.\n"),
2226                              objfile->name);
2227
2228           /* There are various functions like symbol_file_add,
2229              symfile_bfd_open, syms_from_objfile, etc., which might
2230              appear to do what we want.  But they have various other
2231              effects which we *don't* want.  So we just do stuff
2232              ourselves.  We don't worry about mapped files (for one thing,
2233              any mapped file will be out of date).  */
2234
2235           /* If we get an error, blow away this objfile (not sure if
2236              that is the correct response for things like shared
2237              libraries).  */
2238           old_cleanups = make_cleanup_free_objfile (objfile);
2239           /* We need to do this whenever any symbols go away.  */
2240           make_cleanup (clear_symtab_users_cleanup, 0 /*ignore*/);
2241
2242           if (exec_bfd != NULL && strcmp (bfd_get_filename (objfile->obfd),
2243                                           bfd_get_filename (exec_bfd)) == 0)
2244             {
2245               /* Reload EXEC_BFD without asking anything.  */
2246
2247               exec_file_attach (bfd_get_filename (objfile->obfd), 0);
2248             }
2249
2250           /* Clean up any state BFD has sitting around.  We don't need
2251              to close the descriptor but BFD lacks a way of closing the
2252              BFD without closing the descriptor.  */
2253           obfd_filename = bfd_get_filename (objfile->obfd);
2254           if (!bfd_close (objfile->obfd))
2255             error (_("Can't close BFD for %s: %s"), objfile->name,
2256                    bfd_errmsg (bfd_get_error ()));
2257           objfile->obfd = bfd_open_maybe_remote (obfd_filename);
2258           if (objfile->obfd == NULL)
2259             error (_("Can't open %s to read symbols."), objfile->name);
2260           else
2261             objfile->obfd = gdb_bfd_ref (objfile->obfd);
2262           /* bfd_openr sets cacheable to true, which is what we want.  */
2263           if (!bfd_check_format (objfile->obfd, bfd_object))
2264             error (_("Can't read symbols from %s: %s."), objfile->name,
2265                    bfd_errmsg (bfd_get_error ()));
2266
2267           /* Save the offsets, we will nuke them with the rest of the
2268              objfile_obstack.  */
2269           num_offsets = objfile->num_sections;
2270           offsets = ((struct section_offsets *)
2271                      alloca (SIZEOF_N_SECTION_OFFSETS (num_offsets)));
2272           memcpy (offsets, objfile->section_offsets,
2273                   SIZEOF_N_SECTION_OFFSETS (num_offsets));
2274
2275           /* Remove any references to this objfile in the global
2276              value lists.  */
2277           preserve_values (objfile);
2278
2279           /* Nuke all the state that we will re-read.  Much of the following
2280              code which sets things to NULL really is necessary to tell
2281              other parts of GDB that there is nothing currently there.
2282
2283              Try to keep the freeing order compatible with free_objfile.  */
2284
2285           if (objfile->sf != NULL)
2286             {
2287               (*objfile->sf->sym_finish) (objfile);
2288             }
2289
2290           clear_objfile_data (objfile);
2291
2292           /* Free the separate debug objfiles.  It will be
2293              automatically recreated by sym_read.  */
2294           free_objfile_separate_debug (objfile);
2295
2296           /* FIXME: Do we have to free a whole linked list, or is this
2297              enough?  */
2298           if (objfile->global_psymbols.list)
2299             xfree (objfile->global_psymbols.list);
2300           memset (&objfile->global_psymbols, 0,
2301                   sizeof (objfile->global_psymbols));
2302           if (objfile->static_psymbols.list)
2303             xfree (objfile->static_psymbols.list);
2304           memset (&objfile->static_psymbols, 0,
2305                   sizeof (objfile->static_psymbols));
2306
2307           /* Free the obstacks for non-reusable objfiles */
2308           bcache_xfree (objfile->psymbol_cache);
2309           objfile->psymbol_cache = bcache_xmalloc ();
2310           bcache_xfree (objfile->macro_cache);
2311           objfile->macro_cache = bcache_xmalloc ();
2312           bcache_xfree (objfile->filename_cache);
2313           objfile->filename_cache = bcache_xmalloc ();
2314           if (objfile->demangled_names_hash != NULL)
2315             {
2316               htab_delete (objfile->demangled_names_hash);
2317               objfile->demangled_names_hash = NULL;
2318             }
2319           obstack_free (&objfile->objfile_obstack, 0);
2320           objfile->sections = NULL;
2321           objfile->symtabs = NULL;
2322           objfile->psymtabs = NULL;
2323           objfile->psymtabs_addrmap = NULL;
2324           objfile->free_psymtabs = NULL;
2325           objfile->cp_namespace_symtab = NULL;
2326           objfile->msymbols = NULL;
2327           objfile->deprecated_sym_private = NULL;
2328           objfile->minimal_symbol_count = 0;
2329           memset (&objfile->msymbol_hash, 0,
2330                   sizeof (objfile->msymbol_hash));
2331           memset (&objfile->msymbol_demangled_hash, 0,
2332                   sizeof (objfile->msymbol_demangled_hash));
2333
2334           objfile->psymbol_cache = bcache_xmalloc ();
2335           objfile->macro_cache = bcache_xmalloc ();
2336           objfile->filename_cache = bcache_xmalloc ();
2337           /* obstack_init also initializes the obstack so it is
2338              empty.  We could use obstack_specify_allocation but
2339              gdb_obstack.h specifies the alloc/dealloc
2340              functions.  */
2341           obstack_init (&objfile->objfile_obstack);
2342           if (build_objfile_section_table (objfile))
2343             {
2344               error (_("Can't find the file sections in `%s': %s"),
2345                      objfile->name, bfd_errmsg (bfd_get_error ()));
2346             }
2347           terminate_minimal_symbol_table (objfile);
2348
2349           /* We use the same section offsets as from last time.  I'm not
2350              sure whether that is always correct for shared libraries.  */
2351           objfile->section_offsets = (struct section_offsets *)
2352             obstack_alloc (&objfile->objfile_obstack,
2353                            SIZEOF_N_SECTION_OFFSETS (num_offsets));
2354           memcpy (objfile->section_offsets, offsets,
2355                   SIZEOF_N_SECTION_OFFSETS (num_offsets));
2356           objfile->num_sections = num_offsets;
2357
2358           /* What the hell is sym_new_init for, anyway?  The concept of
2359              distinguishing between the main file and additional files
2360              in this way seems rather dubious.  */
2361           if (objfile == symfile_objfile)
2362             {
2363               (*objfile->sf->sym_new_init) (objfile);
2364             }
2365
2366           (*objfile->sf->sym_init) (objfile);
2367           clear_complaints (&symfile_complaints, 1, 1);
2368           /* Do not set flags as this is safe and we don't want to be
2369              verbose.  */
2370           (*objfile->sf->sym_read) (objfile, 0);
2371           if (!objfile_has_symbols (objfile))
2372             {
2373               wrap_here ("");
2374               printf_unfiltered (_("(no debugging symbols found)\n"));
2375               wrap_here ("");
2376             }
2377
2378           /* We're done reading the symbol file; finish off complaints.  */
2379           clear_complaints (&symfile_complaints, 0, 1);
2380
2381           /* Getting new symbols may change our opinion about what is
2382              frameless.  */
2383
2384           reinit_frame_cache ();
2385
2386           /* Discard cleanups as symbol reading was successful.  */
2387           discard_cleanups (old_cleanups);
2388
2389           /* If the mtime has changed between the time we set new_modtime
2390              and now, we *want* this to be out of date, so don't call stat
2391              again now.  */
2392           objfile->mtime = new_modtime;
2393           reread_one = 1;
2394           init_entry_point_info (objfile);
2395         }
2396     }
2397
2398   if (reread_one)
2399     {
2400       /* Notify objfiles that we've modified objfile sections.  */
2401       objfiles_changed ();
2402
2403       clear_symtab_users ();
2404       /* At least one objfile has changed, so we can consider that
2405          the executable we're debugging has changed too.  */
2406       observer_notify_executable_changed ();
2407     }
2408 }
2409 \f
2410
2411
2412 typedef struct
2413 {
2414   char *ext;
2415   enum language lang;
2416 }
2417 filename_language;
2418
2419 static filename_language *filename_language_table;
2420 static int fl_table_size, fl_table_next;
2421
2422 static void
2423 add_filename_language (char *ext, enum language lang)
2424 {
2425   if (fl_table_next >= fl_table_size)
2426     {
2427       fl_table_size += 10;
2428       filename_language_table =
2429         xrealloc (filename_language_table,
2430                   fl_table_size * sizeof (*filename_language_table));
2431     }
2432
2433   filename_language_table[fl_table_next].ext = xstrdup (ext);
2434   filename_language_table[fl_table_next].lang = lang;
2435   fl_table_next++;
2436 }
2437
2438 static char *ext_args;
2439 static void
2440 show_ext_args (struct ui_file *file, int from_tty,
2441                struct cmd_list_element *c, const char *value)
2442 {
2443   fprintf_filtered (file, _("\
2444 Mapping between filename extension and source language is \"%s\".\n"),
2445                     value);
2446 }
2447
2448 static void
2449 set_ext_lang_command (char *args, int from_tty, struct cmd_list_element *e)
2450 {
2451   int i;
2452   char *cp = ext_args;
2453   enum language lang;
2454
2455   /* First arg is filename extension, starting with '.' */
2456   if (*cp != '.')
2457     error (_("'%s': Filename extension must begin with '.'"), ext_args);
2458
2459   /* Find end of first arg.  */
2460   while (*cp && !isspace (*cp))
2461     cp++;
2462
2463   if (*cp == '\0')
2464     error (_("'%s': two arguments required -- filename extension and language"),
2465            ext_args);
2466
2467   /* Null-terminate first arg */
2468   *cp++ = '\0';
2469
2470   /* Find beginning of second arg, which should be a source language.  */
2471   while (*cp && isspace (*cp))
2472     cp++;
2473
2474   if (*cp == '\0')
2475     error (_("'%s': two arguments required -- filename extension and language"),
2476            ext_args);
2477
2478   /* Lookup the language from among those we know.  */
2479   lang = language_enum (cp);
2480
2481   /* Now lookup the filename extension: do we already know it?  */
2482   for (i = 0; i < fl_table_next; i++)
2483     if (0 == strcmp (ext_args, filename_language_table[i].ext))
2484       break;
2485
2486   if (i >= fl_table_next)
2487     {
2488       /* new file extension */
2489       add_filename_language (ext_args, lang);
2490     }
2491   else
2492     {
2493       /* redefining a previously known filename extension */
2494
2495       /* if (from_tty) */
2496       /*   query ("Really make files of type %s '%s'?", */
2497       /*          ext_args, language_str (lang));           */
2498
2499       xfree (filename_language_table[i].ext);
2500       filename_language_table[i].ext = xstrdup (ext_args);
2501       filename_language_table[i].lang = lang;
2502     }
2503 }
2504
2505 static void
2506 info_ext_lang_command (char *args, int from_tty)
2507 {
2508   int i;
2509
2510   printf_filtered (_("Filename extensions and the languages they represent:"));
2511   printf_filtered ("\n\n");
2512   for (i = 0; i < fl_table_next; i++)
2513     printf_filtered ("\t%s\t- %s\n",
2514                      filename_language_table[i].ext,
2515                      language_str (filename_language_table[i].lang));
2516 }
2517
2518 static void
2519 init_filename_language_table (void)
2520 {
2521   if (fl_table_size == 0)       /* protect against repetition */
2522     {
2523       fl_table_size = 20;
2524       fl_table_next = 0;
2525       filename_language_table =
2526         xmalloc (fl_table_size * sizeof (*filename_language_table));
2527       add_filename_language (".c", language_c);
2528       add_filename_language (".C", language_cplus);
2529       add_filename_language (".cc", language_cplus);
2530       add_filename_language (".cp", language_cplus);
2531       add_filename_language (".cpp", language_cplus);
2532       add_filename_language (".cxx", language_cplus);
2533       add_filename_language (".c++", language_cplus);
2534       add_filename_language (".java", language_java);
2535       add_filename_language (".class", language_java);
2536       add_filename_language (".m", language_objc);
2537       add_filename_language (".f", language_fortran);
2538       add_filename_language (".F", language_fortran);
2539       add_filename_language (".s", language_asm);
2540       add_filename_language (".sx", language_asm);
2541       add_filename_language (".S", language_asm);
2542       add_filename_language (".pas", language_pascal);
2543       add_filename_language (".p", language_pascal);
2544       add_filename_language (".pp", language_pascal);
2545       add_filename_language (".adb", language_ada);
2546       add_filename_language (".ads", language_ada);
2547       add_filename_language (".a", language_ada);
2548       add_filename_language (".ada", language_ada);
2549     }
2550 }
2551
2552 enum language
2553 deduce_language_from_filename (char *filename)
2554 {
2555   int i;
2556   char *cp;
2557
2558   if (filename != NULL)
2559     if ((cp = strrchr (filename, '.')) != NULL)
2560       for (i = 0; i < fl_table_next; i++)
2561         if (strcmp (cp, filename_language_table[i].ext) == 0)
2562           return filename_language_table[i].lang;
2563
2564   return language_unknown;
2565 }
2566 \f
2567 /* allocate_symtab:
2568
2569    Allocate and partly initialize a new symbol table.  Return a pointer
2570    to it.  error() if no space.
2571
2572    Caller must set these fields:
2573    LINETABLE(symtab)
2574    symtab->blockvector
2575    symtab->dirname
2576    symtab->free_code
2577    symtab->free_ptr
2578  */
2579
2580 struct symtab *
2581 allocate_symtab (char *filename, struct objfile *objfile)
2582 {
2583   struct symtab *symtab;
2584
2585   symtab = (struct symtab *)
2586     obstack_alloc (&objfile->objfile_obstack, sizeof (struct symtab));
2587   memset (symtab, 0, sizeof (*symtab));
2588   symtab->filename = (char *) bcache (filename, strlen (filename) + 1,
2589                                       objfile->filename_cache);
2590   symtab->fullname = NULL;
2591   symtab->language = deduce_language_from_filename (filename);
2592   symtab->debugformat = "unknown";
2593
2594   /* Hook it to the objfile it comes from */
2595
2596   symtab->objfile = objfile;
2597   symtab->next = objfile->symtabs;
2598   objfile->symtabs = symtab;
2599
2600   return (symtab);
2601 }
2602
2603 struct partial_symtab *
2604 allocate_psymtab (const char *filename, struct objfile *objfile)
2605 {
2606   struct partial_symtab *psymtab;
2607
2608   if (objfile->free_psymtabs)
2609     {
2610       psymtab = objfile->free_psymtabs;
2611       objfile->free_psymtabs = psymtab->next;
2612     }
2613   else
2614     psymtab = (struct partial_symtab *)
2615       obstack_alloc (&objfile->objfile_obstack,
2616                      sizeof (struct partial_symtab));
2617
2618   memset (psymtab, 0, sizeof (struct partial_symtab));
2619   psymtab->filename = (char *) bcache (filename, strlen (filename) + 1,
2620                                        objfile->filename_cache);
2621   psymtab->symtab = NULL;
2622
2623   /* Prepend it to the psymtab list for the objfile it belongs to.
2624      Psymtabs are searched in most recent inserted -> least recent
2625      inserted order. */
2626
2627   psymtab->objfile = objfile;
2628   psymtab->next = objfile->psymtabs;
2629   objfile->psymtabs = psymtab;
2630 #if 0
2631   {
2632     struct partial_symtab **prev_pst;
2633     psymtab->objfile = objfile;
2634     psymtab->next = NULL;
2635     prev_pst = &(objfile->psymtabs);
2636     while ((*prev_pst) != NULL)
2637       prev_pst = &((*prev_pst)->next);
2638     (*prev_pst) = psymtab;
2639   }
2640 #endif
2641
2642   return (psymtab);
2643 }
2644
2645 void
2646 discard_psymtab (struct partial_symtab *pst)
2647 {
2648   struct partial_symtab **prev_pst;
2649
2650   /* From dbxread.c:
2651      Empty psymtabs happen as a result of header files which don't
2652      have any symbols in them.  There can be a lot of them.  But this
2653      check is wrong, in that a psymtab with N_SLINE entries but
2654      nothing else is not empty, but we don't realize that.  Fixing
2655      that without slowing things down might be tricky.  */
2656
2657   /* First, snip it out of the psymtab chain */
2658
2659   prev_pst = &(pst->objfile->psymtabs);
2660   while ((*prev_pst) != pst)
2661     prev_pst = &((*prev_pst)->next);
2662   (*prev_pst) = pst->next;
2663
2664   /* Next, put it on a free list for recycling */
2665
2666   pst->next = pst->objfile->free_psymtabs;
2667   pst->objfile->free_psymtabs = pst;
2668 }
2669 \f
2670
2671 /* Reset all data structures in gdb which may contain references to symbol
2672    table data.  */
2673
2674 void
2675 clear_symtab_users (void)
2676 {
2677   /* Someday, we should do better than this, by only blowing away
2678      the things that really need to be blown.  */
2679
2680   /* Clear the "current" symtab first, because it is no longer valid.
2681      breakpoint_re_set may try to access the current symtab.  */
2682   clear_current_source_symtab_and_line ();
2683
2684   clear_displays ();
2685   breakpoint_re_set ();
2686   set_default_breakpoint (0, NULL, 0, 0, 0);
2687   clear_pc_function_cache ();
2688   observer_notify_new_objfile (NULL);
2689
2690   /* Clear globals which might have pointed into a removed objfile.
2691      FIXME: It's not clear which of these are supposed to persist
2692      between expressions and which ought to be reset each time.  */
2693   expression_context_block = NULL;
2694   innermost_block = NULL;
2695
2696   /* Varobj may refer to old symbols, perform a cleanup.  */
2697   varobj_invalidate ();
2698
2699 }
2700
2701 static void
2702 clear_symtab_users_cleanup (void *ignore)
2703 {
2704   clear_symtab_users ();
2705 }
2706 \f
2707 /* Allocate and partially fill a partial symtab.  It will be
2708    completely filled at the end of the symbol list.
2709
2710    FILENAME is the name of the symbol-file we are reading from. */
2711
2712 struct partial_symtab *
2713 start_psymtab_common (struct objfile *objfile,
2714                       struct section_offsets *section_offsets,
2715                       const char *filename,
2716                       CORE_ADDR textlow, struct partial_symbol **global_syms,
2717                       struct partial_symbol **static_syms)
2718 {
2719   struct partial_symtab *psymtab;
2720
2721   psymtab = allocate_psymtab (filename, objfile);
2722   psymtab->section_offsets = section_offsets;
2723   psymtab->textlow = textlow;
2724   psymtab->texthigh = psymtab->textlow;         /* default */
2725   psymtab->globals_offset = global_syms - objfile->global_psymbols.list;
2726   psymtab->statics_offset = static_syms - objfile->static_psymbols.list;
2727   return (psymtab);
2728 }
2729 \f
2730 /* Helper function, initialises partial symbol structure and stashes 
2731    it into objfile's bcache.  Note that our caching mechanism will
2732    use all fields of struct partial_symbol to determine hash value of the
2733    structure.  In other words, having two symbols with the same name but
2734    different domain (or address) is possible and correct.  */
2735
2736 static const struct partial_symbol *
2737 add_psymbol_to_bcache (char *name, int namelength, int copy_name,
2738                        domain_enum domain,
2739                        enum address_class class,
2740                        long val,        /* Value as a long */
2741                        CORE_ADDR coreaddr,      /* Value as a CORE_ADDR */
2742                        enum language language, struct objfile *objfile,
2743                        int *added)
2744 {
2745   /* psymbol is static so that there will be no uninitialized gaps in the
2746      structure which might contain random data, causing cache misses in
2747      bcache. */
2748   static struct partial_symbol psymbol;
2749
2750   /* However, we must ensure that the entire 'value' field has been
2751      zeroed before assigning to it, because an assignment may not
2752      write the entire field.  */
2753   memset (&psymbol.ginfo.value, 0, sizeof (psymbol.ginfo.value));
2754   /* val and coreaddr are mutually exclusive, one of them *will* be zero */
2755   if (val != 0)
2756     {
2757       SYMBOL_VALUE (&psymbol) = val;
2758     }
2759   else
2760     {
2761       SYMBOL_VALUE_ADDRESS (&psymbol) = coreaddr;
2762     }
2763   SYMBOL_SECTION (&psymbol) = 0;
2764   SYMBOL_LANGUAGE (&psymbol) = language;
2765   PSYMBOL_DOMAIN (&psymbol) = domain;
2766   PSYMBOL_CLASS (&psymbol) = class;
2767
2768   SYMBOL_SET_NAMES (&psymbol, name, namelength, copy_name, objfile);
2769
2770   /* Stash the partial symbol away in the cache */
2771   return bcache_full (&psymbol, sizeof (struct partial_symbol),
2772                       objfile->psymbol_cache, added);
2773 }
2774
2775 /* Helper function, adds partial symbol to the given partial symbol
2776    list.  */
2777
2778 static void
2779 append_psymbol_to_list (struct psymbol_allocation_list *list,
2780                         const struct partial_symbol *psym,
2781                         struct objfile *objfile)
2782 {
2783   if (list->next >= list->list + list->size)
2784     extend_psymbol_list (list, objfile);
2785   *list->next++ = (struct partial_symbol *) psym;
2786   OBJSTAT (objfile, n_psyms++);
2787 }
2788
2789 /* Add a symbol with a long value to a psymtab.
2790    Since one arg is a struct, we pass in a ptr and deref it (sigh).
2791    Return the partial symbol that has been added.  */
2792
2793 /* NOTE: carlton/2003-09-11: The reason why we return the partial
2794    symbol is so that callers can get access to the symbol's demangled
2795    name, which they don't have any cheap way to determine otherwise.
2796    (Currenly, dwarf2read.c is the only file who uses that information,
2797    though it's possible that other readers might in the future.)
2798    Elena wasn't thrilled about that, and I don't blame her, but we
2799    couldn't come up with a better way to get that information.  If
2800    it's needed in other situations, we could consider breaking up
2801    SYMBOL_SET_NAMES to provide access to the demangled name lookup
2802    cache.  */
2803
2804 const struct partial_symbol *
2805 add_psymbol_to_list (char *name, int namelength, int copy_name,
2806                      domain_enum domain,
2807                      enum address_class class,
2808                      struct psymbol_allocation_list *list, 
2809                      long val,  /* Value as a long */
2810                      CORE_ADDR coreaddr,        /* Value as a CORE_ADDR */
2811                      enum language language, struct objfile *objfile)
2812 {
2813   const struct partial_symbol *psym;
2814
2815   int added;
2816
2817   /* Stash the partial symbol away in the cache */
2818   psym = add_psymbol_to_bcache (name, namelength, copy_name, domain, class,
2819                                 val, coreaddr, language, objfile, &added);
2820
2821   /* Do not duplicate global partial symbols.  */
2822   if (list == &objfile->global_psymbols
2823       && !added)
2824     return psym;
2825
2826   /* Save pointer to partial symbol in psymtab, growing symtab if needed. */
2827   append_psymbol_to_list (list, psym, objfile);
2828   return psym;
2829 }
2830
2831 /* Initialize storage for partial symbols.  */
2832
2833 void
2834 init_psymbol_list (struct objfile *objfile, int total_symbols)
2835 {
2836   /* Free any previously allocated psymbol lists.  */
2837
2838   if (objfile->global_psymbols.list)
2839     {
2840       xfree (objfile->global_psymbols.list);
2841     }
2842   if (objfile->static_psymbols.list)
2843     {
2844       xfree (objfile->static_psymbols.list);
2845     }
2846
2847   /* Current best guess is that approximately a twentieth
2848      of the total symbols (in a debugging file) are global or static
2849      oriented symbols */
2850
2851   objfile->global_psymbols.size = total_symbols / 10;
2852   objfile->static_psymbols.size = total_symbols / 10;
2853
2854   if (objfile->global_psymbols.size > 0)
2855     {
2856       objfile->global_psymbols.next =
2857         objfile->global_psymbols.list = (struct partial_symbol **)
2858         xmalloc ((objfile->global_psymbols.size
2859                   * sizeof (struct partial_symbol *)));
2860     }
2861   if (objfile->static_psymbols.size > 0)
2862     {
2863       objfile->static_psymbols.next =
2864         objfile->static_psymbols.list = (struct partial_symbol **)
2865         xmalloc ((objfile->static_psymbols.size
2866                   * sizeof (struct partial_symbol *)));
2867     }
2868 }
2869
2870 /* OVERLAYS:
2871    The following code implements an abstraction for debugging overlay sections.
2872
2873    The target model is as follows:
2874    1) The gnu linker will permit multiple sections to be mapped into the
2875    same VMA, each with its own unique LMA (or load address).
2876    2) It is assumed that some runtime mechanism exists for mapping the
2877    sections, one by one, from the load address into the VMA address.
2878    3) This code provides a mechanism for gdb to keep track of which
2879    sections should be considered to be mapped from the VMA to the LMA.
2880    This information is used for symbol lookup, and memory read/write.
2881    For instance, if a section has been mapped then its contents
2882    should be read from the VMA, otherwise from the LMA.
2883
2884    Two levels of debugger support for overlays are available.  One is
2885    "manual", in which the debugger relies on the user to tell it which
2886    overlays are currently mapped.  This level of support is
2887    implemented entirely in the core debugger, and the information about
2888    whether a section is mapped is kept in the objfile->obj_section table.
2889
2890    The second level of support is "automatic", and is only available if
2891    the target-specific code provides functionality to read the target's
2892    overlay mapping table, and translate its contents for the debugger
2893    (by updating the mapped state information in the obj_section tables).
2894
2895    The interface is as follows:
2896    User commands:
2897    overlay map <name>   -- tell gdb to consider this section mapped
2898    overlay unmap <name> -- tell gdb to consider this section unmapped
2899    overlay list         -- list the sections that GDB thinks are mapped
2900    overlay read-target  -- get the target's state of what's mapped
2901    overlay off/manual/auto -- set overlay debugging state
2902    Functional interface:
2903    find_pc_mapped_section(pc):    if the pc is in the range of a mapped
2904    section, return that section.
2905    find_pc_overlay(pc):       find any overlay section that contains
2906    the pc, either in its VMA or its LMA
2907    section_is_mapped(sect):       true if overlay is marked as mapped
2908    section_is_overlay(sect):      true if section's VMA != LMA
2909    pc_in_mapped_range(pc,sec):    true if pc belongs to section's VMA
2910    pc_in_unmapped_range(...):     true if pc belongs to section's LMA
2911    sections_overlap(sec1, sec2):  true if mapped sec1 and sec2 ranges overlap
2912    overlay_mapped_address(...):   map an address from section's LMA to VMA
2913    overlay_unmapped_address(...): map an address from section's VMA to LMA
2914    symbol_overlayed_address(...): Return a "current" address for symbol:
2915    either in VMA or LMA depending on whether
2916    the symbol's section is currently mapped
2917  */
2918
2919 /* Overlay debugging state: */
2920
2921 enum overlay_debugging_state overlay_debugging = ovly_off;
2922 int overlay_cache_invalid = 0;  /* True if need to refresh mapped state */
2923
2924 /* Function: section_is_overlay (SECTION)
2925    Returns true if SECTION has VMA not equal to LMA, ie.
2926    SECTION is loaded at an address different from where it will "run".  */
2927
2928 int
2929 section_is_overlay (struct obj_section *section)
2930 {
2931   if (overlay_debugging && section)
2932     {
2933       bfd *abfd = section->objfile->obfd;
2934       asection *bfd_section = section->the_bfd_section;
2935   
2936       if (bfd_section_lma (abfd, bfd_section) != 0
2937           && bfd_section_lma (abfd, bfd_section)
2938              != bfd_section_vma (abfd, bfd_section))
2939         return 1;
2940     }
2941
2942   return 0;
2943 }
2944
2945 /* Function: overlay_invalidate_all (void)
2946    Invalidate the mapped state of all overlay sections (mark it as stale).  */
2947
2948 static void
2949 overlay_invalidate_all (void)
2950 {
2951   struct objfile *objfile;
2952   struct obj_section *sect;
2953
2954   ALL_OBJSECTIONS (objfile, sect)
2955     if (section_is_overlay (sect))
2956       sect->ovly_mapped = -1;
2957 }
2958
2959 /* Function: section_is_mapped (SECTION)
2960    Returns true if section is an overlay, and is currently mapped.
2961
2962    Access to the ovly_mapped flag is restricted to this function, so
2963    that we can do automatic update.  If the global flag
2964    OVERLAY_CACHE_INVALID is set (by wait_for_inferior), then call
2965    overlay_invalidate_all.  If the mapped state of the particular
2966    section is stale, then call TARGET_OVERLAY_UPDATE to refresh it.  */
2967
2968 int
2969 section_is_mapped (struct obj_section *osect)
2970 {
2971   struct gdbarch *gdbarch;
2972
2973   if (osect == 0 || !section_is_overlay (osect))
2974     return 0;
2975
2976   switch (overlay_debugging)
2977     {
2978     default:
2979     case ovly_off:
2980       return 0;                 /* overlay debugging off */
2981     case ovly_auto:             /* overlay debugging automatic */
2982       /* Unles there is a gdbarch_overlay_update function,
2983          there's really nothing useful to do here (can't really go auto)  */
2984       gdbarch = get_objfile_arch (osect->objfile);
2985       if (gdbarch_overlay_update_p (gdbarch))
2986         {
2987           if (overlay_cache_invalid)
2988             {
2989               overlay_invalidate_all ();
2990               overlay_cache_invalid = 0;
2991             }
2992           if (osect->ovly_mapped == -1)
2993             gdbarch_overlay_update (gdbarch, osect);
2994         }
2995       /* fall thru to manual case */
2996     case ovly_on:               /* overlay debugging manual */
2997       return osect->ovly_mapped == 1;
2998     }
2999 }
3000
3001 /* Function: pc_in_unmapped_range
3002    If PC falls into the lma range of SECTION, return true, else false.  */
3003
3004 CORE_ADDR
3005 pc_in_unmapped_range (CORE_ADDR pc, struct obj_section *section)
3006 {
3007   if (section_is_overlay (section))
3008     {
3009       bfd *abfd = section->objfile->obfd;
3010       asection *bfd_section = section->the_bfd_section;
3011
3012       /* We assume the LMA is relocated by the same offset as the VMA.  */
3013       bfd_vma size = bfd_get_section_size (bfd_section);
3014       CORE_ADDR offset = obj_section_offset (section);
3015
3016       if (bfd_get_section_lma (abfd, bfd_section) + offset <= pc
3017           && pc < bfd_get_section_lma (abfd, bfd_section) + offset + size)
3018         return 1;
3019     }
3020
3021   return 0;
3022 }
3023
3024 /* Function: pc_in_mapped_range
3025    If PC falls into the vma range of SECTION, return true, else false.  */
3026
3027 CORE_ADDR
3028 pc_in_mapped_range (CORE_ADDR pc, struct obj_section *section)
3029 {
3030   if (section_is_overlay (section))
3031     {
3032       if (obj_section_addr (section) <= pc
3033           && pc < obj_section_endaddr (section))
3034         return 1;
3035     }
3036
3037   return 0;
3038 }
3039
3040
3041 /* Return true if the mapped ranges of sections A and B overlap, false
3042    otherwise.  */
3043 static int
3044 sections_overlap (struct obj_section *a, struct obj_section *b)
3045 {
3046   CORE_ADDR a_start = obj_section_addr (a);
3047   CORE_ADDR a_end = obj_section_endaddr (a);
3048   CORE_ADDR b_start = obj_section_addr (b);
3049   CORE_ADDR b_end = obj_section_endaddr (b);
3050
3051   return (a_start < b_end && b_start < a_end);
3052 }
3053
3054 /* Function: overlay_unmapped_address (PC, SECTION)
3055    Returns the address corresponding to PC in the unmapped (load) range.
3056    May be the same as PC.  */
3057
3058 CORE_ADDR
3059 overlay_unmapped_address (CORE_ADDR pc, struct obj_section *section)
3060 {
3061   if (section_is_overlay (section) && pc_in_mapped_range (pc, section))
3062     {
3063       bfd *abfd = section->objfile->obfd;
3064       asection *bfd_section = section->the_bfd_section;
3065
3066       return pc + bfd_section_lma (abfd, bfd_section)
3067                 - bfd_section_vma (abfd, bfd_section);
3068     }
3069
3070   return pc;
3071 }
3072
3073 /* Function: overlay_mapped_address (PC, SECTION)
3074    Returns the address corresponding to PC in the mapped (runtime) range.
3075    May be the same as PC.  */
3076
3077 CORE_ADDR
3078 overlay_mapped_address (CORE_ADDR pc, struct obj_section *section)
3079 {
3080   if (section_is_overlay (section) && pc_in_unmapped_range (pc, section))
3081     {
3082       bfd *abfd = section->objfile->obfd;
3083       asection *bfd_section = section->the_bfd_section;
3084
3085       return pc + bfd_section_vma (abfd, bfd_section)
3086                 - bfd_section_lma (abfd, bfd_section);
3087     }
3088
3089   return pc;
3090 }
3091
3092
3093 /* Function: symbol_overlayed_address
3094    Return one of two addresses (relative to the VMA or to the LMA),
3095    depending on whether the section is mapped or not.  */
3096
3097 CORE_ADDR
3098 symbol_overlayed_address (CORE_ADDR address, struct obj_section *section)
3099 {
3100   if (overlay_debugging)
3101     {
3102       /* If the symbol has no section, just return its regular address. */
3103       if (section == 0)
3104         return address;
3105       /* If the symbol's section is not an overlay, just return its address */
3106       if (!section_is_overlay (section))
3107         return address;
3108       /* If the symbol's section is mapped, just return its address */
3109       if (section_is_mapped (section))
3110         return address;
3111       /*
3112        * HOWEVER: if the symbol is in an overlay section which is NOT mapped,
3113        * then return its LOADED address rather than its vma address!!
3114        */
3115       return overlay_unmapped_address (address, section);
3116     }
3117   return address;
3118 }
3119
3120 /* Function: find_pc_overlay (PC)
3121    Return the best-match overlay section for PC:
3122    If PC matches a mapped overlay section's VMA, return that section.
3123    Else if PC matches an unmapped section's VMA, return that section.
3124    Else if PC matches an unmapped section's LMA, return that section.  */
3125
3126 struct obj_section *
3127 find_pc_overlay (CORE_ADDR pc)
3128 {
3129   struct objfile *objfile;
3130   struct obj_section *osect, *best_match = NULL;
3131
3132   if (overlay_debugging)
3133     ALL_OBJSECTIONS (objfile, osect)
3134       if (section_is_overlay (osect))
3135       {
3136         if (pc_in_mapped_range (pc, osect))
3137           {
3138             if (section_is_mapped (osect))
3139               return osect;
3140             else
3141               best_match = osect;
3142           }
3143         else if (pc_in_unmapped_range (pc, osect))
3144           best_match = osect;
3145       }
3146   return best_match;
3147 }
3148
3149 /* Function: find_pc_mapped_section (PC)
3150    If PC falls into the VMA address range of an overlay section that is
3151    currently marked as MAPPED, return that section.  Else return NULL.  */
3152
3153 struct obj_section *
3154 find_pc_mapped_section (CORE_ADDR pc)
3155 {
3156   struct objfile *objfile;
3157   struct obj_section *osect;
3158
3159   if (overlay_debugging)
3160     ALL_OBJSECTIONS (objfile, osect)
3161       if (pc_in_mapped_range (pc, osect) && section_is_mapped (osect))
3162         return osect;
3163
3164   return NULL;
3165 }
3166
3167 /* Function: list_overlays_command
3168    Print a list of mapped sections and their PC ranges */
3169
3170 void
3171 list_overlays_command (char *args, int from_tty)
3172 {
3173   int nmapped = 0;
3174   struct objfile *objfile;
3175   struct obj_section *osect;
3176
3177   if (overlay_debugging)
3178     ALL_OBJSECTIONS (objfile, osect)
3179       if (section_is_mapped (osect))
3180       {
3181         struct gdbarch *gdbarch = get_objfile_arch (objfile);
3182         const char *name;
3183         bfd_vma lma, vma;
3184         int size;
3185
3186         vma = bfd_section_vma (objfile->obfd, osect->the_bfd_section);
3187         lma = bfd_section_lma (objfile->obfd, osect->the_bfd_section);
3188         size = bfd_get_section_size (osect->the_bfd_section);
3189         name = bfd_section_name (objfile->obfd, osect->the_bfd_section);
3190
3191         printf_filtered ("Section %s, loaded at ", name);
3192         fputs_filtered (paddress (gdbarch, lma), gdb_stdout);
3193         puts_filtered (" - ");
3194         fputs_filtered (paddress (gdbarch, lma + size), gdb_stdout);
3195         printf_filtered (", mapped at ");
3196         fputs_filtered (paddress (gdbarch, vma), gdb_stdout);
3197         puts_filtered (" - ");
3198         fputs_filtered (paddress (gdbarch, vma + size), gdb_stdout);
3199         puts_filtered ("\n");
3200
3201         nmapped++;
3202       }
3203   if (nmapped == 0)
3204     printf_filtered (_("No sections are mapped.\n"));
3205 }
3206
3207 /* Function: map_overlay_command
3208    Mark the named section as mapped (ie. residing at its VMA address).  */
3209
3210 void
3211 map_overlay_command (char *args, int from_tty)
3212 {
3213   struct objfile *objfile, *objfile2;
3214   struct obj_section *sec, *sec2;
3215
3216   if (!overlay_debugging)
3217     error (_("\
3218 Overlay debugging not enabled.  Use either the 'overlay auto' or\n\
3219 the 'overlay manual' command."));
3220
3221   if (args == 0 || *args == 0)
3222     error (_("Argument required: name of an overlay section"));
3223
3224   /* First, find a section matching the user supplied argument */
3225   ALL_OBJSECTIONS (objfile, sec)
3226     if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args))
3227     {
3228       /* Now, check to see if the section is an overlay. */
3229       if (!section_is_overlay (sec))
3230         continue;               /* not an overlay section */
3231
3232       /* Mark the overlay as "mapped" */
3233       sec->ovly_mapped = 1;
3234
3235       /* Next, make a pass and unmap any sections that are
3236          overlapped by this new section: */
3237       ALL_OBJSECTIONS (objfile2, sec2)
3238         if (sec2->ovly_mapped && sec != sec2 && sections_overlap (sec, sec2))
3239         {
3240           if (info_verbose)
3241             printf_unfiltered (_("Note: section %s unmapped by overlap\n"),
3242                              bfd_section_name (objfile->obfd,
3243                                                sec2->the_bfd_section));
3244           sec2->ovly_mapped = 0;        /* sec2 overlaps sec: unmap sec2 */
3245         }
3246       return;
3247     }
3248   error (_("No overlay section called %s"), args);
3249 }
3250
3251 /* Function: unmap_overlay_command
3252    Mark the overlay section as unmapped
3253    (ie. resident in its LMA address range, rather than the VMA range).  */
3254
3255 void
3256 unmap_overlay_command (char *args, int from_tty)
3257 {
3258   struct objfile *objfile;
3259   struct obj_section *sec;
3260
3261   if (!overlay_debugging)
3262     error (_("\
3263 Overlay debugging not enabled.  Use either the 'overlay auto' or\n\
3264 the 'overlay manual' command."));
3265
3266   if (args == 0 || *args == 0)
3267     error (_("Argument required: name of an overlay section"));
3268
3269   /* First, find a section matching the user supplied argument */
3270   ALL_OBJSECTIONS (objfile, sec)
3271     if (!strcmp (bfd_section_name (objfile->obfd, sec->the_bfd_section), args))
3272     {
3273       if (!sec->ovly_mapped)
3274         error (_("Section %s is not mapped"), args);
3275       sec->ovly_mapped = 0;
3276       return;
3277     }
3278   error (_("No overlay section called %s"), args);
3279 }
3280
3281 /* Function: overlay_auto_command
3282    A utility command to turn on overlay debugging.
3283    Possibly this should be done via a set/show command. */
3284
3285 static void
3286 overlay_auto_command (char *args, int from_tty)
3287 {
3288   overlay_debugging = ovly_auto;
3289   enable_overlay_breakpoints ();
3290   if (info_verbose)
3291     printf_unfiltered (_("Automatic overlay debugging enabled."));
3292 }
3293
3294 /* Function: overlay_manual_command
3295    A utility command to turn on overlay debugging.
3296    Possibly this should be done via a set/show command. */
3297
3298 static void
3299 overlay_manual_command (char *args, int from_tty)
3300 {
3301   overlay_debugging = ovly_on;
3302   disable_overlay_breakpoints ();
3303   if (info_verbose)
3304     printf_unfiltered (_("Overlay debugging enabled."));
3305 }
3306
3307 /* Function: overlay_off_command
3308    A utility command to turn on overlay debugging.
3309    Possibly this should be done via a set/show command. */
3310
3311 static void
3312 overlay_off_command (char *args, int from_tty)
3313 {
3314   overlay_debugging = ovly_off;
3315   disable_overlay_breakpoints ();
3316   if (info_verbose)
3317     printf_unfiltered (_("Overlay debugging disabled."));
3318 }
3319
3320 static void
3321 overlay_load_command (char *args, int from_tty)
3322 {
3323   struct gdbarch *gdbarch = get_current_arch ();
3324
3325   if (gdbarch_overlay_update_p (gdbarch))
3326     gdbarch_overlay_update (gdbarch, NULL);
3327   else
3328     error (_("This target does not know how to read its overlay state."));
3329 }
3330
3331 /* Function: overlay_command
3332    A place-holder for a mis-typed command */
3333
3334 /* Command list chain containing all defined "overlay" subcommands. */
3335 struct cmd_list_element *overlaylist;
3336
3337 static void
3338 overlay_command (char *args, int from_tty)
3339 {
3340   printf_unfiltered
3341     ("\"overlay\" must be followed by the name of an overlay command.\n");
3342   help_list (overlaylist, "overlay ", -1, gdb_stdout);
3343 }
3344
3345
3346 /* Target Overlays for the "Simplest" overlay manager:
3347
3348    This is GDB's default target overlay layer.  It works with the
3349    minimal overlay manager supplied as an example by Cygnus.  The
3350    entry point is via a function pointer "gdbarch_overlay_update",
3351    so targets that use a different runtime overlay manager can
3352    substitute their own overlay_update function and take over the
3353    function pointer.
3354
3355    The overlay_update function pokes around in the target's data structures
3356    to see what overlays are mapped, and updates GDB's overlay mapping with
3357    this information.
3358
3359    In this simple implementation, the target data structures are as follows:
3360    unsigned _novlys;            /# number of overlay sections #/
3361    unsigned _ovly_table[_novlys][4] = {
3362    {VMA, SIZE, LMA, MAPPED},    /# one entry per overlay section #/
3363    {..., ...,  ..., ...},
3364    }
3365    unsigned _novly_regions;     /# number of overlay regions #/
3366    unsigned _ovly_region_table[_novly_regions][3] = {
3367    {VMA, SIZE, MAPPED_TO_LMA},  /# one entry per overlay region #/
3368    {..., ...,  ...},
3369    }
3370    These functions will attempt to update GDB's mappedness state in the
3371    symbol section table, based on the target's mappedness state.
3372
3373    To do this, we keep a cached copy of the target's _ovly_table, and
3374    attempt to detect when the cached copy is invalidated.  The main
3375    entry point is "simple_overlay_update(SECT), which looks up SECT in
3376    the cached table and re-reads only the entry for that section from
3377    the target (whenever possible).
3378  */
3379
3380 /* Cached, dynamically allocated copies of the target data structures: */
3381 static unsigned (*cache_ovly_table)[4] = 0;
3382 #if 0
3383 static unsigned (*cache_ovly_region_table)[3] = 0;
3384 #endif
3385 static unsigned cache_novlys = 0;
3386 #if 0
3387 static unsigned cache_novly_regions = 0;
3388 #endif
3389 static CORE_ADDR cache_ovly_table_base = 0;
3390 #if 0
3391 static CORE_ADDR cache_ovly_region_table_base = 0;
3392 #endif
3393 enum ovly_index
3394   {
3395     VMA, SIZE, LMA, MAPPED
3396   };
3397
3398 /* Throw away the cached copy of _ovly_table */
3399 static void
3400 simple_free_overlay_table (void)
3401 {
3402   if (cache_ovly_table)
3403     xfree (cache_ovly_table);
3404   cache_novlys = 0;
3405   cache_ovly_table = NULL;
3406   cache_ovly_table_base = 0;
3407 }
3408
3409 #if 0
3410 /* Throw away the cached copy of _ovly_region_table */
3411 static void
3412 simple_free_overlay_region_table (void)
3413 {
3414   if (cache_ovly_region_table)
3415     xfree (cache_ovly_region_table);
3416   cache_novly_regions = 0;
3417   cache_ovly_region_table = NULL;
3418   cache_ovly_region_table_base = 0;
3419 }
3420 #endif
3421
3422 /* Read an array of ints of size SIZE from the target into a local buffer.
3423    Convert to host order.  int LEN is number of ints  */
3424 static void
3425 read_target_long_array (CORE_ADDR memaddr, unsigned int *myaddr,
3426                         int len, int size, enum bfd_endian byte_order)
3427 {
3428   /* FIXME (alloca): Not safe if array is very large. */
3429   gdb_byte *buf = alloca (len * size);
3430   int i;
3431
3432   read_memory (memaddr, buf, len * size);
3433   for (i = 0; i < len; i++)
3434     myaddr[i] = extract_unsigned_integer (size * i + buf, size, byte_order);
3435 }
3436
3437 /* Find and grab a copy of the target _ovly_table
3438    (and _novlys, which is needed for the table's size) */
3439 static int
3440 simple_read_overlay_table (void)
3441 {
3442   struct minimal_symbol *novlys_msym, *ovly_table_msym;
3443   struct gdbarch *gdbarch;
3444   int word_size;
3445   enum bfd_endian byte_order;
3446
3447   simple_free_overlay_table ();
3448   novlys_msym = lookup_minimal_symbol ("_novlys", NULL, NULL);
3449   if (! novlys_msym)
3450     {
3451       error (_("Error reading inferior's overlay table: "
3452              "couldn't find `_novlys' variable\n"
3453              "in inferior.  Use `overlay manual' mode."));
3454       return 0;
3455     }
3456
3457   ovly_table_msym = lookup_minimal_symbol ("_ovly_table", NULL, NULL);
3458   if (! ovly_table_msym)
3459     {
3460       error (_("Error reading inferior's overlay table: couldn't find "
3461              "`_ovly_table' array\n"
3462              "in inferior.  Use `overlay manual' mode."));
3463       return 0;
3464     }
3465
3466   gdbarch = get_objfile_arch (msymbol_objfile (ovly_table_msym));
3467   word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT;
3468   byte_order = gdbarch_byte_order (gdbarch);
3469
3470   cache_novlys = read_memory_integer (SYMBOL_VALUE_ADDRESS (novlys_msym),
3471                                       4, byte_order);
3472   cache_ovly_table
3473     = (void *) xmalloc (cache_novlys * sizeof (*cache_ovly_table));
3474   cache_ovly_table_base = SYMBOL_VALUE_ADDRESS (ovly_table_msym);
3475   read_target_long_array (cache_ovly_table_base,
3476                           (unsigned int *) cache_ovly_table,
3477                           cache_novlys * 4, word_size, byte_order);
3478
3479   return 1;                     /* SUCCESS */
3480 }
3481
3482 #if 0
3483 /* Find and grab a copy of the target _ovly_region_table
3484    (and _novly_regions, which is needed for the table's size) */
3485 static int
3486 simple_read_overlay_region_table (void)
3487 {
3488   struct minimal_symbol *msym;
3489   struct gdbarch *gdbarch;
3490   int word_size;
3491   enum bfd_endian byte_order;
3492
3493   simple_free_overlay_region_table ();
3494   msym = lookup_minimal_symbol ("_novly_regions", NULL, NULL);
3495   if (msym == NULL)
3496     return 0;                   /* failure */
3497
3498   gdbarch = get_objfile_arch (msymbol_objfile (msym));
3499   word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT;
3500   byte_order = gdbarch_byte_order (gdbarch);
3501
3502   cache_novly_regions = read_memory_integer (SYMBOL_VALUE_ADDRESS (msym),
3503                                              4, byte_order);
3504
3505   cache_ovly_region_table = (void *) xmalloc (cache_novly_regions * 12);
3506   if (cache_ovly_region_table != NULL)
3507     {
3508       msym = lookup_minimal_symbol ("_ovly_region_table", NULL, NULL);
3509       if (msym != NULL)
3510         {
3511           cache_ovly_region_table_base = SYMBOL_VALUE_ADDRESS (msym);
3512           read_target_long_array (cache_ovly_region_table_base,
3513                                   (unsigned int *) cache_ovly_region_table,
3514                                   cache_novly_regions * 3,
3515                                   word_size, byte_order);
3516         }
3517       else
3518         return 0;               /* failure */
3519     }
3520   else
3521     return 0;                   /* failure */
3522   return 1;                     /* SUCCESS */
3523 }
3524 #endif
3525
3526 /* Function: simple_overlay_update_1
3527    A helper function for simple_overlay_update.  Assuming a cached copy
3528    of _ovly_table exists, look through it to find an entry whose vma,
3529    lma and size match those of OSECT.  Re-read the entry and make sure
3530    it still matches OSECT (else the table may no longer be valid).
3531    Set OSECT's mapped state to match the entry.  Return: 1 for
3532    success, 0 for failure.  */
3533
3534 static int
3535 simple_overlay_update_1 (struct obj_section *osect)
3536 {
3537   int i, size;
3538   bfd *obfd = osect->objfile->obfd;
3539   asection *bsect = osect->the_bfd_section;
3540   struct gdbarch *gdbarch = get_objfile_arch (osect->objfile);
3541   int word_size = gdbarch_long_bit (gdbarch) / TARGET_CHAR_BIT;
3542   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
3543
3544   size = bfd_get_section_size (osect->the_bfd_section);
3545   for (i = 0; i < cache_novlys; i++)
3546     if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect)
3547         && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect)
3548         /* && cache_ovly_table[i][SIZE] == size */ )
3549       {
3550         read_target_long_array (cache_ovly_table_base + i * word_size,
3551                                 (unsigned int *) cache_ovly_table[i],
3552                                 4, word_size, byte_order);
3553         if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect)
3554             && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect)
3555             /* && cache_ovly_table[i][SIZE] == size */ )
3556           {
3557             osect->ovly_mapped = cache_ovly_table[i][MAPPED];
3558             return 1;
3559           }
3560         else    /* Warning!  Warning!  Target's ovly table has changed! */
3561           return 0;
3562       }
3563   return 0;
3564 }
3565
3566 /* Function: simple_overlay_update
3567    If OSECT is NULL, then update all sections' mapped state
3568    (after re-reading the entire target _ovly_table).
3569    If OSECT is non-NULL, then try to find a matching entry in the
3570    cached ovly_table and update only OSECT's mapped state.
3571    If a cached entry can't be found or the cache isn't valid, then
3572    re-read the entire cache, and go ahead and update all sections.  */
3573
3574 void
3575 simple_overlay_update (struct obj_section *osect)
3576 {
3577   struct objfile *objfile;
3578
3579   /* Were we given an osect to look up?  NULL means do all of them. */
3580   if (osect)
3581     /* Have we got a cached copy of the target's overlay table? */
3582     if (cache_ovly_table != NULL)
3583       /* Does its cached location match what's currently in the symtab? */
3584       if (cache_ovly_table_base ==
3585           SYMBOL_VALUE_ADDRESS (lookup_minimal_symbol ("_ovly_table", NULL, NULL)))
3586         /* Then go ahead and try to look up this single section in the cache */
3587         if (simple_overlay_update_1 (osect))
3588           /* Found it!  We're done. */
3589           return;
3590
3591   /* Cached table no good: need to read the entire table anew.
3592      Or else we want all the sections, in which case it's actually
3593      more efficient to read the whole table in one block anyway.  */
3594
3595   if (! simple_read_overlay_table ())
3596     return;
3597
3598   /* Now may as well update all sections, even if only one was requested. */
3599   ALL_OBJSECTIONS (objfile, osect)
3600     if (section_is_overlay (osect))
3601     {
3602       int i, size;
3603       bfd *obfd = osect->objfile->obfd;
3604       asection *bsect = osect->the_bfd_section;
3605
3606       size = bfd_get_section_size (bsect);
3607       for (i = 0; i < cache_novlys; i++)
3608         if (cache_ovly_table[i][VMA] == bfd_section_vma (obfd, bsect)
3609             && cache_ovly_table[i][LMA] == bfd_section_lma (obfd, bsect)
3610             /* && cache_ovly_table[i][SIZE] == size */ )
3611           { /* obj_section matches i'th entry in ovly_table */
3612             osect->ovly_mapped = cache_ovly_table[i][MAPPED];
3613             break;              /* finished with inner for loop: break out */
3614           }
3615     }
3616 }
3617
3618 /* Set the output sections and output offsets for section SECTP in
3619    ABFD.  The relocation code in BFD will read these offsets, so we
3620    need to be sure they're initialized.  We map each section to itself,
3621    with no offset; this means that SECTP->vma will be honored.  */
3622
3623 static void
3624 symfile_dummy_outputs (bfd *abfd, asection *sectp, void *dummy)
3625 {
3626   sectp->output_section = sectp;
3627   sectp->output_offset = 0;
3628 }
3629
3630 /* Relocate the contents of a debug section SECTP in ABFD.  The
3631    contents are stored in BUF if it is non-NULL, or returned in a
3632    malloc'd buffer otherwise.
3633
3634    For some platforms and debug info formats, shared libraries contain
3635    relocations against the debug sections (particularly for DWARF-2;
3636    one affected platform is PowerPC GNU/Linux, although it depends on
3637    the version of the linker in use).  Also, ELF object files naturally
3638    have unresolved relocations for their debug sections.  We need to apply
3639    the relocations in order to get the locations of symbols correct.
3640    Another example that may require relocation processing, is the
3641    DWARF-2 .eh_frame section in .o files, although it isn't strictly a
3642    debug section.  */
3643
3644 bfd_byte *
3645 symfile_relocate_debug_section (bfd *abfd, asection *sectp, bfd_byte *buf)
3646 {
3647   /* We're only interested in sections with relocation
3648      information.  */
3649   if ((sectp->flags & SEC_RELOC) == 0)
3650     return NULL;
3651
3652   /* We will handle section offsets properly elsewhere, so relocate as if
3653      all sections begin at 0.  */
3654   bfd_map_over_sections (abfd, symfile_dummy_outputs, NULL);
3655
3656   return bfd_simple_get_relocated_section_contents (abfd, sectp, buf, NULL);
3657 }
3658
3659 struct symfile_segment_data *
3660 get_symfile_segment_data (bfd *abfd)
3661 {
3662   struct sym_fns *sf = find_sym_fns (abfd);
3663
3664   if (sf == NULL)
3665     return NULL;
3666
3667   return sf->sym_segments (abfd);
3668 }
3669
3670 void
3671 free_symfile_segment_data (struct symfile_segment_data *data)
3672 {
3673   xfree (data->segment_bases);
3674   xfree (data->segment_sizes);
3675   xfree (data->segment_info);
3676   xfree (data);
3677 }
3678
3679
3680 /* Given:
3681    - DATA, containing segment addresses from the object file ABFD, and
3682      the mapping from ABFD's sections onto the segments that own them,
3683      and
3684    - SEGMENT_BASES[0 .. NUM_SEGMENT_BASES - 1], holding the actual
3685      segment addresses reported by the target,
3686    store the appropriate offsets for each section in OFFSETS.
3687
3688    If there are fewer entries in SEGMENT_BASES than there are segments
3689    in DATA, then apply SEGMENT_BASES' last entry to all the segments.
3690
3691    If there are more entries, then ignore the extra.  The target may
3692    not be able to distinguish between an empty data segment and a
3693    missing data segment; a missing text segment is less plausible.  */
3694 int
3695 symfile_map_offsets_to_segments (bfd *abfd, struct symfile_segment_data *data,
3696                                  struct section_offsets *offsets,
3697                                  int num_segment_bases,
3698                                  const CORE_ADDR *segment_bases)
3699 {
3700   int i;
3701   asection *sect;
3702
3703   /* It doesn't make sense to call this function unless you have some
3704      segment base addresses.  */
3705   gdb_assert (segment_bases > 0);
3706
3707   /* If we do not have segment mappings for the object file, we
3708      can not relocate it by segments.  */
3709   gdb_assert (data != NULL);
3710   gdb_assert (data->num_segments > 0);
3711
3712   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
3713     {
3714       int which = data->segment_info[i];
3715
3716       gdb_assert (0 <= which && which <= data->num_segments);
3717
3718       /* Don't bother computing offsets for sections that aren't
3719          loaded as part of any segment.  */
3720       if (! which)
3721         continue;
3722
3723       /* Use the last SEGMENT_BASES entry as the address of any extra
3724          segments mentioned in DATA->segment_info.  */
3725       if (which > num_segment_bases)
3726         which = num_segment_bases;
3727
3728       offsets->offsets[i] = (segment_bases[which - 1]
3729                              - data->segment_bases[which - 1]);
3730     }
3731
3732   return 1;
3733 }
3734
3735 static void
3736 symfile_find_segment_sections (struct objfile *objfile)
3737 {
3738   bfd *abfd = objfile->obfd;
3739   int i;
3740   asection *sect;
3741   struct symfile_segment_data *data;
3742
3743   data = get_symfile_segment_data (objfile->obfd);
3744   if (data == NULL)
3745     return;
3746
3747   if (data->num_segments != 1 && data->num_segments != 2)
3748     {
3749       free_symfile_segment_data (data);
3750       return;
3751     }
3752
3753   for (i = 0, sect = abfd->sections; sect != NULL; i++, sect = sect->next)
3754     {
3755       CORE_ADDR vma;
3756       int which = data->segment_info[i];
3757
3758       if (which == 1)
3759         {
3760           if (objfile->sect_index_text == -1)
3761             objfile->sect_index_text = sect->index;
3762
3763           if (objfile->sect_index_rodata == -1)
3764             objfile->sect_index_rodata = sect->index;
3765         }
3766       else if (which == 2)
3767         {
3768           if (objfile->sect_index_data == -1)
3769             objfile->sect_index_data = sect->index;
3770
3771           if (objfile->sect_index_bss == -1)
3772             objfile->sect_index_bss = sect->index;
3773         }
3774     }
3775
3776   free_symfile_segment_data (data);
3777 }
3778
3779 void
3780 _initialize_symfile (void)
3781 {
3782   struct cmd_list_element *c;
3783
3784   c = add_cmd ("symbol-file", class_files, symbol_file_command, _("\
3785 Load symbol table from executable file FILE.\n\
3786 The `file' command can also load symbol tables, as well as setting the file\n\
3787 to execute."), &cmdlist);
3788   set_cmd_completer (c, filename_completer);
3789
3790   c = add_cmd ("add-symbol-file", class_files, add_symbol_file_command, _("\
3791 Load symbols from FILE, assuming FILE has been dynamically loaded.\n\
3792 Usage: add-symbol-file FILE ADDR [-s <SECT> <SECT_ADDR> -s <SECT> <SECT_ADDR> ...]\n\
3793 ADDR is the starting address of the file's text.\n\
3794 The optional arguments are section-name section-address pairs and\n\
3795 should be specified if the data and bss segments are not contiguous\n\
3796 with the text.  SECT is a section name to be loaded at SECT_ADDR."),
3797                &cmdlist);
3798   set_cmd_completer (c, filename_completer);
3799
3800   c = add_cmd ("load", class_files, load_command, _("\
3801 Dynamically load FILE into the running program, and record its symbols\n\
3802 for access from GDB.\n\
3803 A load OFFSET may also be given."), &cmdlist);
3804   set_cmd_completer (c, filename_completer);
3805
3806   add_setshow_boolean_cmd ("symbol-reloading", class_support,
3807                            &symbol_reloading, _("\
3808 Set dynamic symbol table reloading multiple times in one run."), _("\
3809 Show dynamic symbol table reloading multiple times in one run."), NULL,
3810                            NULL,
3811                            show_symbol_reloading,
3812                            &setlist, &showlist);
3813
3814   add_prefix_cmd ("overlay", class_support, overlay_command,
3815                   _("Commands for debugging overlays."), &overlaylist,
3816                   "overlay ", 0, &cmdlist);
3817
3818   add_com_alias ("ovly", "overlay", class_alias, 1);
3819   add_com_alias ("ov", "overlay", class_alias, 1);
3820
3821   add_cmd ("map-overlay", class_support, map_overlay_command,
3822            _("Assert that an overlay section is mapped."), &overlaylist);
3823
3824   add_cmd ("unmap-overlay", class_support, unmap_overlay_command,
3825            _("Assert that an overlay section is unmapped."), &overlaylist);
3826
3827   add_cmd ("list-overlays", class_support, list_overlays_command,
3828            _("List mappings of overlay sections."), &overlaylist);
3829
3830   add_cmd ("manual", class_support, overlay_manual_command,
3831            _("Enable overlay debugging."), &overlaylist);
3832   add_cmd ("off", class_support, overlay_off_command,
3833            _("Disable overlay debugging."), &overlaylist);
3834   add_cmd ("auto", class_support, overlay_auto_command,
3835            _("Enable automatic overlay debugging."), &overlaylist);
3836   add_cmd ("load-target", class_support, overlay_load_command,
3837            _("Read the overlay mapping state from the target."), &overlaylist);
3838
3839   /* Filename extension to source language lookup table: */
3840   init_filename_language_table ();
3841   add_setshow_string_noescape_cmd ("extension-language", class_files,
3842                                    &ext_args, _("\
3843 Set mapping between filename extension and source language."), _("\
3844 Show mapping between filename extension and source language."), _("\
3845 Usage: set extension-language .foo bar"),
3846                                    set_ext_lang_command,
3847                                    show_ext_args,
3848                                    &setlist, &showlist);
3849
3850   add_info ("extensions", info_ext_lang_command,
3851             _("All filename extensions associated with a source language."));
3852
3853   add_setshow_optional_filename_cmd ("debug-file-directory", class_support,
3854                                      &debug_file_directory, _("\
3855 Set the directories where separate debug symbols are searched for."), _("\
3856 Show the directories where separate debug symbols are searched for."), _("\
3857 Separate debug symbols are first searched for in the same\n\
3858 directory as the binary, then in the `" DEBUG_SUBDIRECTORY "' subdirectory,\n\
3859 and lastly at the path of the directory of the binary with\n\
3860 each global debug-file-directory component prepended."),
3861                                      NULL,
3862                                      show_debug_file_directory,
3863                                      &setlist, &showlist);
3864 }