OSDN Git Service

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