* buildsym.c (subfile_stack): Move here from buildsym.h.
[platform/upstream/binutils.git] / gdb / coffread.c
1 /* Read coff symbol tables and convert to internal format, for GDB.
2    Copyright (C) 1987-2013 Free Software Foundation, Inc.
3    Contributed by David D. Johnson, Brown University (ddj@cs.brown.edu).
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "symtab.h"
22 #include "gdbtypes.h"
23 #include "demangle.h"
24 #include "breakpoint.h"
25
26 #include "bfd.h"
27 #include "gdb_obstack.h"
28
29 #include "gdb_string.h"
30 #include <ctype.h>
31
32 #include "coff/internal.h"      /* Internal format of COFF symbols in BFD */
33 #include "libcoff.h"            /* FIXME secret internal data from BFD */
34 #include "objfiles.h"
35 #include "buildsym.h"
36 #include "gdb-stabs.h"
37 #include "stabsread.h"
38 #include "complaints.h"
39 #include "target.h"
40 #include "gdb_assert.h"
41 #include "block.h"
42 #include "dictionary.h"
43
44 #include "coff-pe-read.h"
45
46 #include "psymtab.h"
47
48 extern void _initialize_coffread (void);
49
50 /* Key for COFF-associated data.  */
51
52 static const struct objfile_data *coff_objfile_data_key;
53
54 /* The objfile we are currently reading.  */
55
56 static struct objfile *coffread_objfile;
57
58 struct coff_symfile_info
59   {
60     file_ptr min_lineno_offset; /* Where in file lowest line#s are.  */
61     file_ptr max_lineno_offset; /* 1+last byte of line#s in file.  */
62
63     CORE_ADDR textaddr;         /* Addr of .text section.  */
64     unsigned int textsize;      /* Size of .text section.  */
65     struct stab_section_list *stabsects;        /* .stab sections.  */
66     asection *stabstrsect;      /* Section pointer for .stab section.  */
67     char *stabstrdata;
68   };
69
70 /* Translate an external name string into a user-visible name.  */
71 #define EXTERNAL_NAME(string, abfd) \
72         (string[0] == bfd_get_symbol_leading_char (abfd) \
73         ? string + 1 : string)
74
75 /* To be an sdb debug type, type must have at least a basic or primary
76    derived type.  Using this rather than checking against T_NULL is
77    said to prevent core dumps if we try to operate on Michael Bloom
78    dbx-in-coff file.  */
79
80 #define SDB_TYPE(type) (BTYPE(type) | (type & N_TMASK))
81
82 /* Core address of start and end of text of current source file.
83    This comes from a ".text" symbol where x_nlinno > 0.  */
84
85 static CORE_ADDR current_source_start_addr;
86 static CORE_ADDR current_source_end_addr;
87
88 /* The addresses of the symbol table stream and number of symbols
89    of the object file we are reading (as copied into core).  */
90
91 static bfd *nlist_bfd_global;
92 static int nlist_nsyms_global;
93
94
95 /* Pointers to scratch storage, used for reading raw symbols and
96    auxents.  */
97
98 static char *temp_sym;
99 static char *temp_aux;
100
101 /* Local variables that hold the shift and mask values for the
102    COFF file that we are currently reading.  These come back to us
103    from BFD, and are referenced by their macro names, as well as
104    internally to the BTYPE, ISPTR, ISFCN, ISARY, ISTAG, and DECREF
105    macros from include/coff/internal.h .  */
106
107 static unsigned local_n_btmask;
108 static unsigned local_n_btshft;
109 static unsigned local_n_tmask;
110 static unsigned local_n_tshift;
111
112 #define N_BTMASK        local_n_btmask
113 #define N_BTSHFT        local_n_btshft
114 #define N_TMASK         local_n_tmask
115 #define N_TSHIFT        local_n_tshift
116
117 /* Local variables that hold the sizes in the file of various COFF
118    structures.  (We only need to know this to read them from the file
119    -- BFD will then translate the data in them, into `internal_xxx'
120    structs in the right byte order, alignment, etc.)  */
121
122 static unsigned local_linesz;
123 static unsigned local_symesz;
124 static unsigned local_auxesz;
125
126 /* This is set if this is a PE format file.  */
127
128 static int pe_file;
129
130 /* Chain of typedefs of pointers to empty struct/union types.
131    They are chained thru the SYMBOL_VALUE_CHAIN.  */
132
133 static struct symbol *opaque_type_chain[HASHSIZE];
134
135 /* Simplified internal version of coff symbol table information.  */
136
137 struct coff_symbol
138   {
139     char *c_name;
140     int c_symnum;               /* Symbol number of this entry.  */
141     int c_naux;                 /* 0 if syment only, 1 if syment +
142                                    auxent, etc.  */
143     CORE_ADDR c_value;
144     int c_sclass;
145     int c_secnum;
146     unsigned int c_type;
147   };
148
149 /* Vector of types defined so far, indexed by their type numbers.  */
150
151 static struct type **type_vector;
152
153 /* Number of elements allocated for type_vector currently.  */
154
155 static int type_vector_length;
156
157 /* Initial size of type vector.  Is realloc'd larger if needed, and
158    realloc'd down to the size actually used, when completed.  */
159
160 #define INITIAL_TYPE_VECTOR_LENGTH 160
161
162 extern void stabsread_clear_cache (void);
163
164 static struct type *coff_read_struct_type (int, int, int,
165                                            struct objfile *);
166
167 static struct type *decode_base_type (struct coff_symbol *,
168                                       unsigned int,
169                                       union internal_auxent *,
170                                       struct objfile *);
171
172 static struct type *decode_type (struct coff_symbol *, unsigned int,
173                                  union internal_auxent *,
174                                  struct objfile *);
175
176 static struct type *decode_function_type (struct coff_symbol *,
177                                           unsigned int,
178                                           union internal_auxent *,
179                                           struct objfile *);
180
181 static struct type *coff_read_enum_type (int, int, int,
182                                          struct objfile *);
183
184 static struct symbol *process_coff_symbol (struct coff_symbol *,
185                                            union internal_auxent *,
186                                            struct objfile *);
187
188 static void patch_opaque_types (struct symtab *);
189
190 static void enter_linenos (long, int, int, struct objfile *);
191
192 static void free_linetab (void);
193
194 static void free_linetab_cleanup (void *ignore);
195
196 static int init_lineno (bfd *, long, int);
197
198 static char *getsymname (struct internal_syment *);
199
200 static const char *coff_getfilename (union internal_auxent *);
201
202 static void free_stringtab (void);
203
204 static void free_stringtab_cleanup (void *ignore);
205
206 static int init_stringtab (bfd *, long);
207
208 static void read_one_sym (struct coff_symbol *,
209                           struct internal_syment *,
210                           union internal_auxent *);
211
212 static void coff_symtab_read (long, unsigned int, struct objfile *);
213 \f
214 /* We are called once per section from coff_symfile_read.  We
215    need to examine each section we are passed, check to see
216    if it is something we are interested in processing, and
217    if so, stash away some access information for the section.
218
219    FIXME: The section names should not be hardwired strings (what
220    should they be?  I don't think most object file formats have enough
221    section flags to specify what kind of debug section it is
222    -kingdon).  */
223
224 static void
225 coff_locate_sections (bfd *abfd, asection *sectp, void *csip)
226 {
227   struct coff_symfile_info *csi;
228   const char *name;
229
230   csi = (struct coff_symfile_info *) csip;
231   name = bfd_get_section_name (abfd, sectp);
232   if (strcmp (name, ".text") == 0)
233     {
234       csi->textaddr = bfd_section_vma (abfd, sectp);
235       csi->textsize += bfd_section_size (abfd, sectp);
236     }
237   else if (strncmp (name, ".text", sizeof ".text" - 1) == 0)
238     {
239       csi->textsize += bfd_section_size (abfd, sectp);
240     }
241   else if (strcmp (name, ".stabstr") == 0)
242     {
243       csi->stabstrsect = sectp;
244     }
245   else if (strncmp (name, ".stab", sizeof ".stab" - 1) == 0)
246     {
247       const char *s;
248
249       /* We can have multiple .stab sections if linked with
250          --split-by-reloc.  */
251       for (s = name + sizeof ".stab" - 1; *s != '\0'; s++)
252         if (!isdigit (*s))
253           break;
254       if (*s == '\0')
255         {
256           struct stab_section_list *n, **pn;
257
258           n = ((struct stab_section_list *)
259                xmalloc (sizeof (struct stab_section_list)));
260           n->section = sectp;
261           n->next = NULL;
262           for (pn = &csi->stabsects; *pn != NULL; pn = &(*pn)->next)
263             ;
264           *pn = n;
265
266           /* This will be run after coffstab_build_psymtabs is called
267              in coff_symfile_read, at which point we no longer need
268              the information.  */
269           make_cleanup (xfree, n);
270         }
271     }
272 }
273
274 /* Return the section_offsets* that CS points to.  */
275 static int cs_to_section (struct coff_symbol *, struct objfile *);
276
277 struct find_targ_sec_arg
278   {
279     int targ_index;
280     asection **resultp;
281   };
282
283 static void
284 find_targ_sec (bfd *abfd, asection *sect, void *obj)
285 {
286   struct find_targ_sec_arg *args = (struct find_targ_sec_arg *) obj;
287
288   if (sect->target_index == args->targ_index)
289     *args->resultp = sect;
290 }
291
292 /* Return the bfd_section that CS points to.  */
293 static struct bfd_section*
294 cs_to_bfd_section (struct coff_symbol *cs, struct objfile *objfile)
295 {
296   asection *sect = NULL;
297   struct find_targ_sec_arg args;
298
299   args.targ_index = cs->c_secnum;
300   args.resultp = &sect;
301   bfd_map_over_sections (objfile->obfd, find_targ_sec, &args);
302   return sect;
303 }
304
305 /* Return the section number (SECT_OFF_*) that CS points to.  */
306 static int
307 cs_to_section (struct coff_symbol *cs, struct objfile *objfile)
308 {
309   asection *sect = cs_to_bfd_section (cs, objfile);
310
311   if (sect == NULL)
312     return SECT_OFF_TEXT (objfile);
313   return gdb_bfd_section_index (objfile->obfd, sect);
314 }
315
316 /* Return the address of the section of a COFF symbol.  */
317
318 static CORE_ADDR cs_section_address (struct coff_symbol *, bfd *);
319
320 static CORE_ADDR
321 cs_section_address (struct coff_symbol *cs, bfd *abfd)
322 {
323   asection *sect = NULL;
324   struct find_targ_sec_arg args;
325   CORE_ADDR addr = 0;
326
327   args.targ_index = cs->c_secnum;
328   args.resultp = &sect;
329   bfd_map_over_sections (abfd, find_targ_sec, &args);
330   if (sect != NULL)
331     addr = bfd_get_section_vma (abfd, sect);
332   return addr;
333 }
334
335 /* Look up a coff type-number index.  Return the address of the slot
336    where the type for that index is stored.
337    The type-number is in INDEX. 
338
339    This can be used for finding the type associated with that index
340    or for associating a new type with the index.  */
341
342 static struct type **
343 coff_lookup_type (int index)
344 {
345   if (index >= type_vector_length)
346     {
347       int old_vector_length = type_vector_length;
348
349       type_vector_length *= 2;
350       if (index /* is still */  >= type_vector_length)
351         type_vector_length = index * 2;
352
353       type_vector = (struct type **)
354         xrealloc ((char *) type_vector,
355                   type_vector_length * sizeof (struct type *));
356       memset (&type_vector[old_vector_length], 0,
357          (type_vector_length - old_vector_length) * sizeof (struct type *));
358     }
359   return &type_vector[index];
360 }
361
362 /* Make sure there is a type allocated for type number index
363    and return the type object.
364    This can create an empty (zeroed) type object.  */
365
366 static struct type *
367 coff_alloc_type (int index)
368 {
369   struct type **type_addr = coff_lookup_type (index);
370   struct type *type = *type_addr;
371
372   /* If we are referring to a type not known at all yet,
373      allocate an empty type for it.
374      We will fill it in later if we find out how.  */
375   if (type == NULL)
376     {
377       type = alloc_type (coffread_objfile);
378       *type_addr = type;
379     }
380   return type;
381 }
382 \f
383 /* Start a new symtab for a new source file.
384    This is called when a COFF ".file" symbol is seen;
385    it indicates the start of data for one original source file.  */
386
387 static void
388 coff_start_symtab (const char *name)
389 {
390   start_symtab (
391   /* We fill in the filename later.  start_symtab puts this pointer
392      into last_source_file and we put it in subfiles->name, which
393      end_symtab frees; that's why it must be malloc'd.  */
394                  xstrdup (name),
395   /* We never know the directory name for COFF.  */
396                  NULL,
397   /* The start address is irrelevant, since we set
398      last_source_start_addr in coff_end_symtab.  */
399                  0);
400   record_debugformat ("COFF");
401 }
402
403 /* Save the vital information from when starting to read a file,
404    for use when closing off the current file.
405    NAME is the file name the symbols came from, START_ADDR is the
406    first text address for the file, and SIZE is the number of bytes of
407    text.  */
408
409 static void
410 complete_symtab (const char *name, CORE_ADDR start_addr, unsigned int size)
411 {
412   set_last_source_file (name);
413   current_source_start_addr = start_addr;
414   current_source_end_addr = start_addr + size;
415 }
416
417 /* Finish the symbol definitions for one main source file, close off
418    all the lexical contexts for that file (creating struct block's for
419    them), then make the struct symtab for that file and put it in the
420    list of all such.  */
421
422 static void
423 coff_end_symtab (struct objfile *objfile)
424 {
425   last_source_start_addr = current_source_start_addr;
426
427   end_symtab (current_source_end_addr, objfile,
428               SECT_OFF_TEXT (objfile));
429
430   /* Reinitialize for beginning of new file.  */
431   set_last_source_file (NULL);
432 }
433 \f
434 /* The linker sometimes generates some non-function symbols inside
435    functions referencing variables imported from another DLL.
436    Return nonzero if the given symbol corresponds to one of them.  */
437
438 static int
439 is_import_fixup_symbol (struct coff_symbol *cs,
440                         enum minimal_symbol_type type)
441 {
442   /* The following is a bit of a heuristic using the characterictics
443      of these fixup symbols, but should work well in practice...  */
444   int i;
445
446   /* Must be a non-static text symbol.  */
447   if (type != mst_text)
448     return 0;
449
450   /* Must be a non-function symbol.  */
451   if (ISFCN (cs->c_type))
452     return 0;
453
454   /* The name must start with "__fu<digits>__".  */
455   if (strncmp (cs->c_name, "__fu", 4) != 0)
456     return 0;
457   if (! isdigit (cs->c_name[4]))
458     return 0;
459   for (i = 5; cs->c_name[i] != '\0' && isdigit (cs->c_name[i]); i++)
460     /* Nothing, just incrementing index past all digits.  */;
461   if (cs->c_name[i] != '_' || cs->c_name[i + 1] != '_')
462     return 0;
463
464   return 1;
465 }
466
467 static struct minimal_symbol *
468 record_minimal_symbol (struct coff_symbol *cs, CORE_ADDR address,
469                        enum minimal_symbol_type type, int section, 
470                        struct objfile *objfile)
471 {
472   /* We don't want TDESC entry points in the minimal symbol table.  */
473   if (cs->c_name[0] == '@')
474     return NULL;
475
476   if (is_import_fixup_symbol (cs, type))
477     {
478       /* Because the value of these symbols is within a function code
479          range, these symbols interfere with the symbol-from-address
480          reverse lookup; this manifests itselfs in backtraces, or any
481          other commands that prints symbolic addresses.  Just pretend
482          these symbols do not exist.  */
483       return NULL;
484     }
485
486   return prim_record_minimal_symbol_and_info (cs->c_name, address,
487                                               type, section, objfile);
488 }
489 \f
490 /* coff_symfile_init ()
491    is the coff-specific initialization routine for reading symbols.
492    It is passed a struct objfile which contains, among other things,
493    the BFD for the file whose symbols are being read, and a slot for
494    a pointer to "private data" which we fill with cookies and other
495    treats for coff_symfile_read ().
496
497    We will only be called if this is a COFF or COFF-like file.  BFD
498    handles figuring out the format of the file, and code in symtab.c
499    uses BFD's determination to vector to us.
500
501    The ultimate result is a new symtab (or, FIXME, eventually a
502    psymtab).  */
503
504 static void
505 coff_symfile_init (struct objfile *objfile)
506 {
507   struct dbx_symfile_info *dbx;
508   struct coff_symfile_info *coff;
509
510   /* Allocate struct to keep track of stab reading.  */
511   dbx = XCNEW (struct dbx_symfile_info);
512   set_objfile_data (objfile, dbx_objfile_data_key, dbx);
513
514   /* Allocate struct to keep track of the symfile.  */
515   coff = XCNEW (struct coff_symfile_info);
516   set_objfile_data (objfile, coff_objfile_data_key, coff);
517
518   /* COFF objects may be reordered, so set OBJF_REORDERED.  If we
519      find this causes a significant slowdown in gdb then we could
520      set it in the debug symbol readers only when necessary.  */
521   objfile->flags |= OBJF_REORDERED;
522 }
523
524 /* This function is called for every section; it finds the outer
525    limits of the line table (minimum and maximum file offset) so that
526    the mainline code can read the whole thing for efficiency.  */
527
528 static void
529 find_linenos (bfd *abfd, struct bfd_section *asect, void *vpinfo)
530 {
531   struct coff_symfile_info *info;
532   int size, count;
533   file_ptr offset, maxoff;
534
535   /* WARNING WILL ROBINSON!  ACCESSING BFD-PRIVATE DATA HERE!  FIXME!  */
536   count = asect->lineno_count;
537   /* End of warning.  */
538
539   if (count == 0)
540     return;
541   size = count * local_linesz;
542
543   info = (struct coff_symfile_info *) vpinfo;
544   /* WARNING WILL ROBINSON!  ACCESSING BFD-PRIVATE DATA HERE!  FIXME!  */
545   offset = asect->line_filepos;
546   /* End of warning.  */
547
548   if (offset < info->min_lineno_offset || info->min_lineno_offset == 0)
549     info->min_lineno_offset = offset;
550
551   maxoff = offset + size;
552   if (maxoff > info->max_lineno_offset)
553     info->max_lineno_offset = maxoff;
554 }
555
556
557 /* The BFD for this file -- only good while we're actively reading
558    symbols into a psymtab or a symtab.  */
559
560 static bfd *symfile_bfd;
561
562 /* Read a symbol file, after initialization by coff_symfile_init.  */
563
564 static void
565 coff_symfile_read (struct objfile *objfile, int symfile_flags)
566 {
567   struct coff_symfile_info *info;
568   struct dbx_symfile_info *dbxinfo;
569   bfd *abfd = objfile->obfd;
570   coff_data_type *cdata = coff_data (abfd);
571   char *name = bfd_get_filename (abfd);
572   int val;
573   unsigned int num_symbols;
574   int symtab_offset;
575   int stringtab_offset;
576   struct cleanup *back_to, *cleanup_minimal_symbols;
577   int stabstrsize;
578   
579   info = objfile_data (objfile, coff_objfile_data_key);
580   dbxinfo = DBX_SYMFILE_INFO (objfile);
581   symfile_bfd = abfd;           /* Kludge for swap routines.  */
582
583 /* WARNING WILL ROBINSON!  ACCESSING BFD-PRIVATE DATA HERE!  FIXME!  */
584   num_symbols = bfd_get_symcount (abfd);        /* How many syms */
585   symtab_offset = cdata->sym_filepos;   /* Symbol table file offset */
586   stringtab_offset = symtab_offset +    /* String table file offset */
587     num_symbols * cdata->local_symesz;
588
589   /* Set a few file-statics that give us specific information about
590      the particular COFF file format we're reading.  */
591   local_n_btmask = cdata->local_n_btmask;
592   local_n_btshft = cdata->local_n_btshft;
593   local_n_tmask = cdata->local_n_tmask;
594   local_n_tshift = cdata->local_n_tshift;
595   local_linesz = cdata->local_linesz;
596   local_symesz = cdata->local_symesz;
597   local_auxesz = cdata->local_auxesz;
598
599   /* Allocate space for raw symbol and aux entries, based on their
600      space requirements as reported by BFD.  */
601   temp_sym = (char *) xmalloc
602     (cdata->local_symesz + cdata->local_auxesz);
603   temp_aux = temp_sym + cdata->local_symesz;
604   back_to = make_cleanup (free_current_contents, &temp_sym);
605
606   /* We need to know whether this is a PE file, because in PE files,
607      unlike standard COFF files, symbol values are stored as offsets
608      from the section address, rather than as absolute addresses.
609      FIXME: We should use BFD to read the symbol table, and thus avoid
610      this problem.  */
611   pe_file =
612     strncmp (bfd_get_target (objfile->obfd), "pe", 2) == 0
613     || strncmp (bfd_get_target (objfile->obfd), "epoc-pe", 7) == 0;
614
615   /* End of warning.  */
616
617   info->min_lineno_offset = 0;
618   info->max_lineno_offset = 0;
619
620   /* Only read line number information if we have symbols.
621
622      On Windows NT, some of the system's DLL's have sections with
623      PointerToLinenumbers fields that are non-zero, but point at
624      random places within the image file.  (In the case I found,
625      KERNEL32.DLL's .text section has a line number info pointer that
626      points into the middle of the string `lib\\i386\kernel32.dll'.)
627
628      However, these DLL's also have no symbols.  The line number
629      tables are meaningless without symbols.  And in fact, GDB never
630      uses the line number information unless there are symbols.  So we
631      can avoid spurious error messages (and maybe run a little
632      faster!) by not even reading the line number table unless we have
633      symbols.  */
634   if (num_symbols > 0)
635     {
636       /* Read the line number table, all at once.  */
637       bfd_map_over_sections (abfd, find_linenos, (void *) info);
638
639       make_cleanup (free_linetab_cleanup, 0 /*ignore*/);
640       val = init_lineno (abfd, info->min_lineno_offset,
641                          info->max_lineno_offset - info->min_lineno_offset);
642       if (val < 0)
643         error (_("\"%s\": error reading line numbers."), name);
644     }
645
646   /* Now read the string table, all at once.  */
647
648   make_cleanup (free_stringtab_cleanup, 0 /*ignore*/);
649   val = init_stringtab (abfd, stringtab_offset);
650   if (val < 0)
651     error (_("\"%s\": can't get string table"), name);
652
653   init_minimal_symbol_collection ();
654   cleanup_minimal_symbols = make_cleanup_discard_minimal_symbols ();
655
656   /* Now that the executable file is positioned at symbol table,
657      process it and define symbols accordingly.  */
658
659   coff_symtab_read ((long) symtab_offset, num_symbols, objfile);
660
661   /* Install any minimal symbols that have been collected as the
662      current minimal symbols for this objfile.  */
663
664   install_minimal_symbols (objfile);
665
666   if (pe_file)
667     {
668       struct minimal_symbol *msym;
669
670       ALL_OBJFILE_MSYMBOLS (objfile, msym)
671         {
672           const char *name = SYMBOL_LINKAGE_NAME (msym);
673
674           /* If the minimal symbols whose name are prefixed by "__imp_"
675              or "_imp_", get rid of the prefix, and search the minimal
676              symbol in OBJFILE.  Note that 'maintenance print msymbols'
677              shows that type of these "_imp_XXXX" symbols is mst_data.  */
678           if (MSYMBOL_TYPE (msym) == mst_data
679               && (strncmp (name, "__imp_", 6) == 0
680                   || strncmp (name, "_imp_", 5) == 0))
681             {
682               const char *name1 = (name[1] == '_' ? &name[7] : &name[6]);
683               struct minimal_symbol *found;
684
685               found = lookup_minimal_symbol (name1, NULL, objfile);
686               /* If found, there are symbols named "_imp_foo" and "foo"
687                  respectively in OBJFILE.  Set the type of symbol "foo"
688                  as 'mst_solib_trampoline'.  */
689               if (found != NULL && MSYMBOL_TYPE (found) == mst_text)
690                 MSYMBOL_TYPE (found) = mst_solib_trampoline;
691             }
692         }
693     }
694
695   /* Free the installed minimal symbol data.  */
696   do_cleanups (cleanup_minimal_symbols);
697
698   bfd_map_over_sections (abfd, coff_locate_sections, (void *) info);
699
700   if (info->stabsects)
701     {
702       if (!info->stabstrsect)
703         {
704           error (_("The debugging information in `%s' is corrupted.\nThe "
705                    "file has a `.stabs' section, but no `.stabstr' section."),
706                  name);
707         }
708
709       /* FIXME: dubious.  Why can't we use something normal like
710          bfd_get_section_contents?  */
711       bfd_seek (abfd, abfd->where, 0);
712
713       stabstrsize = bfd_section_size (abfd, info->stabstrsect);
714
715       coffstab_build_psymtabs (objfile,
716                                info->textaddr, info->textsize,
717                                info->stabsects,
718                                info->stabstrsect->filepos, stabstrsize);
719     }
720   if (dwarf2_has_info (objfile, NULL))
721     {
722       /* DWARF2 sections.  */
723       dwarf2_build_psymtabs (objfile);
724     }
725
726   dwarf2_build_frame_info (objfile);
727
728   /* Try to add separate debug file if no symbols table found.   */
729   if (!objfile_has_partial_symbols (objfile))
730     {
731       char *debugfile;
732
733       debugfile = find_separate_debug_file_by_debuglink (objfile);
734       make_cleanup (xfree, debugfile);
735
736       if (debugfile)
737         {
738           bfd *abfd = symfile_bfd_open (debugfile);
739
740           make_cleanup_bfd_unref (abfd);
741           symbol_file_add_separate (abfd, symfile_flags, objfile);
742         }
743     }
744
745   do_cleanups (back_to);
746 }
747
748 static void
749 coff_new_init (struct objfile *ignore)
750 {
751 }
752
753 /* Perform any local cleanups required when we are done with a
754    particular objfile.  I.E, we are in the process of discarding all
755    symbol information for an objfile, freeing up all memory held for
756    it, and unlinking the objfile struct from the global list of known
757    objfiles.  */
758
759 static void
760 coff_symfile_finish (struct objfile *objfile)
761 {
762   /* Let stabs reader clean up.  */
763   stabsread_clear_cache ();
764
765   dwarf2_free_objfile (objfile);
766 }
767 \f
768
769 /* Given pointers to a symbol table in coff style exec file,
770    analyze them and create struct symtab's describing the symbols.
771    NSYMS is the number of symbols in the symbol table.
772    We read them one at a time using read_one_sym ().  */
773
774 static void
775 coff_symtab_read (long symtab_offset, unsigned int nsyms,
776                   struct objfile *objfile)
777 {
778   struct gdbarch *gdbarch = get_objfile_arch (objfile);
779   struct context_stack *new;
780   struct coff_symbol coff_symbol;
781   struct coff_symbol *cs = &coff_symbol;
782   static struct internal_syment main_sym;
783   static union internal_auxent main_aux;
784   struct coff_symbol fcn_cs_saved;
785   static struct internal_syment fcn_sym_saved;
786   static union internal_auxent fcn_aux_saved;
787   struct symtab *s;
788   /* A .file is open.  */
789   int in_source_file = 0;
790   int next_file_symnum = -1;
791   /* Name of the current file.  */
792   const char *filestring = "";
793   int depth = 0;
794   int fcn_first_line = 0;
795   CORE_ADDR fcn_first_line_addr = 0;
796   int fcn_last_line = 0;
797   int fcn_start_addr = 0;
798   long fcn_line_ptr = 0;
799   int val;
800   CORE_ADDR tmpaddr;
801   struct minimal_symbol *msym;
802
803   /* Work around a stdio bug in SunOS4.1.1 (this makes me nervous....
804      it's hard to know I've really worked around it.  The fix should
805      be harmless, anyway).  The symptom of the bug is that the first
806      fread (in read_one_sym), will (in my example) actually get data
807      from file offset 268, when the fseek was to 264 (and ftell shows
808      264).  This causes all hell to break loose.  I was unable to
809      reproduce this on a short test program which operated on the same
810      file, performing (I think) the same sequence of operations.
811
812      It stopped happening when I put in this (former) rewind().
813
814      FIXME: Find out if this has been reported to Sun, whether it has
815      been fixed in a later release, etc.  */
816
817   bfd_seek (objfile->obfd, 0, 0);
818
819   /* Position to read the symbol table.  */
820   val = bfd_seek (objfile->obfd, (long) symtab_offset, 0);
821   if (val < 0)
822     perror_with_name (objfile->name);
823
824   coffread_objfile = objfile;
825   nlist_bfd_global = objfile->obfd;
826   nlist_nsyms_global = nsyms;
827   set_last_source_file (NULL);
828   memset (opaque_type_chain, 0, sizeof opaque_type_chain);
829
830   if (type_vector)              /* Get rid of previous one.  */
831     xfree (type_vector);
832   type_vector_length = INITIAL_TYPE_VECTOR_LENGTH;
833   type_vector = (struct type **)
834     xmalloc (type_vector_length * sizeof (struct type *));
835   memset (type_vector, 0, type_vector_length * sizeof (struct type *));
836
837   coff_start_symtab ("");
838
839   symnum = 0;
840   while (symnum < nsyms)
841     {
842       QUIT;                     /* Make this command interruptable.  */
843
844       read_one_sym (cs, &main_sym, &main_aux);
845
846       if (cs->c_symnum == next_file_symnum && cs->c_sclass != C_FILE)
847         {
848           if (get_last_source_file ())
849             coff_end_symtab (objfile);
850
851           coff_start_symtab ("_globals_");
852           /* coff_start_symtab will set the language of this symtab to
853              language_unknown, since such a ``file name'' is not
854              recognized.  Override that with the minimal language to
855              allow printing values in this symtab.  */
856           current_subfile->language = language_minimal;
857           complete_symtab ("_globals_", 0, 0);
858           /* Done with all files, everything from here on out is
859              globals.  */
860         }
861
862       /* Special case for file with type declarations only, no
863          text.  */
864       if (!get_last_source_file () && SDB_TYPE (cs->c_type)
865           && cs->c_secnum == N_DEBUG)
866         complete_symtab (filestring, 0, 0);
867
868       /* Typedefs should not be treated as symbol definitions.  */
869       if (ISFCN (cs->c_type) && cs->c_sclass != C_TPDEF)
870         {
871           /* Record all functions -- external and static -- in
872              minsyms.  */
873           int section = cs_to_section (cs, objfile);
874
875           tmpaddr = cs->c_value + ANOFFSET (objfile->section_offsets,
876                                             SECT_OFF_TEXT (objfile));
877           record_minimal_symbol (cs, tmpaddr, mst_text,
878                                  section, objfile);
879
880           fcn_line_ptr = main_aux.x_sym.x_fcnary.x_fcn.x_lnnoptr;
881           fcn_start_addr = tmpaddr;
882           fcn_cs_saved = *cs;
883           fcn_sym_saved = main_sym;
884           fcn_aux_saved = main_aux;
885           continue;
886         }
887
888       switch (cs->c_sclass)
889         {
890         case C_EFCN:
891         case C_EXTDEF:
892         case C_ULABEL:
893         case C_USTATIC:
894         case C_LINE:
895         case C_ALIAS:
896         case C_HIDDEN:
897           complaint (&symfile_complaints,
898                      _("Bad n_sclass for symbol %s"),
899                      cs->c_name);
900           break;
901
902         case C_FILE:
903           /* c_value field contains symnum of next .file entry in
904              table or symnum of first global after last .file.  */
905           next_file_symnum = cs->c_value;
906           if (cs->c_naux > 0)
907             filestring = coff_getfilename (&main_aux);
908           else
909             filestring = "";
910
911           /* Complete symbol table for last object file
912              containing debugging information.  */
913           if (get_last_source_file ())
914             {
915               coff_end_symtab (objfile);
916               coff_start_symtab (filestring);
917             }
918           in_source_file = 1;
919           break;
920
921           /* C_LABEL is used for labels and static functions.
922              Including it here allows gdb to see static functions when
923              no debug info is available.  */
924         case C_LABEL:
925           /* However, labels within a function can make weird
926              backtraces, so filter them out (from phdm@macqel.be).  */
927           if (within_function)
928             break;
929         case C_STAT:
930         case C_THUMBLABEL:
931         case C_THUMBSTAT:
932         case C_THUMBSTATFUNC:
933           if (cs->c_name[0] == '.')
934             {
935               if (strcmp (cs->c_name, ".text") == 0)
936                 {
937                   /* FIXME: don't wire in ".text" as section name or
938                      symbol name!  */
939                   /* Check for in_source_file deals with case of a
940                      file with debugging symbols followed by a later
941                      file with no symbols.  */
942                   if (in_source_file)
943                     complete_symtab (filestring,
944                     cs->c_value + ANOFFSET (objfile->section_offsets,
945                                             SECT_OFF_TEXT (objfile)),
946                                      main_aux.x_scn.x_scnlen);
947                   in_source_file = 0;
948                 }
949               /* Flush rest of '.' symbols.  */
950               break;
951             }
952           else if (!SDB_TYPE (cs->c_type)
953                    && cs->c_name[0] == 'L'
954                    && (strncmp (cs->c_name, "LI%", 3) == 0
955                        || strncmp (cs->c_name, "LF%", 3) == 0
956                        || strncmp (cs->c_name, "LC%", 3) == 0
957                        || strncmp (cs->c_name, "LP%", 3) == 0
958                        || strncmp (cs->c_name, "LPB%", 4) == 0
959                        || strncmp (cs->c_name, "LBB%", 4) == 0
960                        || strncmp (cs->c_name, "LBE%", 4) == 0
961                        || strncmp (cs->c_name, "LPBX%", 5) == 0))
962             /* At least on a 3b1, gcc generates swbeg and string labels
963                that look like this.  Ignore them.  */
964             break;
965           /* Fall in for static symbols that don't start with '.'  */
966         case C_THUMBEXT:
967         case C_THUMBEXTFUNC:
968         case C_EXT:
969           {
970             /* Record it in the minimal symbols regardless of
971                SDB_TYPE.  This parallels what we do for other debug
972                formats, and probably is needed to make
973                print_address_symbolic work right without the (now
974                gone) "set fast-symbolic-addr off" kludge.  */
975
976             enum minimal_symbol_type ms_type;
977             int sec;
978
979             if (cs->c_secnum == N_UNDEF)
980               {
981                 /* This is a common symbol.  We used to rely on
982                    the target to tell us whether it knows where
983                    the symbol has been relocated to, but none of
984                    the target implementations actually provided
985                    that operation.  So we just ignore the symbol,
986                    the same way we would do if we had a target-side
987                    symbol lookup which returned no match.  */
988                 break;
989               }
990             else if (cs->c_secnum == N_ABS)
991               {
992                 /* Use the correct minimal symbol type (and don't
993                    relocate) for absolute values.  */
994                 ms_type = mst_abs;
995                 sec = cs_to_section (cs, objfile);
996                 tmpaddr = cs->c_value;
997               }
998             else
999               {
1000                 asection *bfd_section = cs_to_bfd_section (cs, objfile);
1001
1002                 sec = cs_to_section (cs, objfile);
1003                 tmpaddr = cs->c_value;
1004                 /* Statics in a PE file also get relocated.  */
1005                 if (cs->c_sclass == C_EXT
1006                     || cs->c_sclass == C_THUMBEXTFUNC
1007                     || cs->c_sclass == C_THUMBEXT
1008                     || (pe_file && (cs->c_sclass == C_STAT)))
1009                   tmpaddr += ANOFFSET (objfile->section_offsets, sec);
1010
1011                 if (bfd_section->flags & SEC_CODE)
1012                   {
1013                     ms_type =
1014                       cs->c_sclass == C_EXT || cs->c_sclass == C_THUMBEXTFUNC
1015                       || cs->c_sclass == C_THUMBEXT ?
1016                       mst_text : mst_file_text;
1017                     tmpaddr = gdbarch_addr_bits_remove (gdbarch, tmpaddr);
1018                   }
1019                 else if (bfd_section->flags & SEC_ALLOC
1020                          && bfd_section->flags & SEC_LOAD)
1021                   {
1022                     ms_type =
1023                       cs->c_sclass == C_EXT || cs->c_sclass == C_THUMBEXT
1024                       ? mst_data : mst_file_data;
1025                   }
1026                 else if (bfd_section->flags & SEC_ALLOC)
1027                   {
1028                     ms_type =
1029                       cs->c_sclass == C_EXT || cs->c_sclass == C_THUMBEXT
1030                       ? mst_bss : mst_file_bss;
1031                   }
1032                 else
1033                   ms_type = mst_unknown;
1034               }
1035
1036             msym = record_minimal_symbol (cs, tmpaddr, ms_type,
1037                                           sec, objfile);
1038             if (msym)
1039               gdbarch_coff_make_msymbol_special (gdbarch,
1040                                                  cs->c_sclass, msym);
1041
1042             if (SDB_TYPE (cs->c_type))
1043               {
1044                 struct symbol *sym;
1045
1046                 sym = process_coff_symbol
1047                   (cs, &main_aux, objfile);
1048                 SYMBOL_VALUE (sym) = tmpaddr;
1049                 SYMBOL_SECTION (sym) = sec;
1050               }
1051           }
1052           break;
1053
1054         case C_FCN:
1055           if (strcmp (cs->c_name, ".bf") == 0)
1056             {
1057               within_function = 1;
1058
1059               /* Value contains address of first non-init type
1060                  code.  */
1061               /* main_aux.x_sym.x_misc.x_lnsz.x_lnno
1062                  contains line number of '{' }.  */
1063               if (cs->c_naux != 1)
1064                 complaint (&symfile_complaints,
1065                            _("`.bf' symbol %d has no aux entry"),
1066                            cs->c_symnum);
1067               fcn_first_line = main_aux.x_sym.x_misc.x_lnsz.x_lnno;
1068               fcn_first_line_addr = cs->c_value;
1069
1070               /* Might want to check that locals are 0 and
1071                  context_stack_depth is zero, and complain if not.  */
1072
1073               depth = 0;
1074               new = push_context (depth, fcn_start_addr);
1075               fcn_cs_saved.c_name = getsymname (&fcn_sym_saved);
1076               new->name =
1077                 process_coff_symbol (&fcn_cs_saved, 
1078                                      &fcn_aux_saved, objfile);
1079             }
1080           else if (strcmp (cs->c_name, ".ef") == 0)
1081             {
1082               if (!within_function)
1083                 error (_("Bad coff function information."));
1084               /* The value of .ef is the address of epilogue code;
1085                  not useful for gdb.  */
1086               /* { main_aux.x_sym.x_misc.x_lnsz.x_lnno
1087                  contains number of lines to '}' */
1088
1089               if (context_stack_depth <= 0)
1090                 {       /* We attempted to pop an empty context stack.  */
1091                   complaint (&symfile_complaints,
1092                              _("`.ef' symbol without matching `.bf' "
1093                                "symbol ignored starting at symnum %d"),
1094                              cs->c_symnum);
1095                   within_function = 0;
1096                   break;
1097                 }
1098
1099               new = pop_context ();
1100               /* Stack must be empty now.  */
1101               if (context_stack_depth > 0 || new == NULL)
1102                 {
1103                   complaint (&symfile_complaints,
1104                              _("Unmatched .ef symbol(s) ignored "
1105                                "starting at symnum %d"),
1106                              cs->c_symnum);
1107                   within_function = 0;
1108                   break;
1109                 }
1110               if (cs->c_naux != 1)
1111                 {
1112                   complaint (&symfile_complaints,
1113                              _("`.ef' symbol %d has no aux entry"),
1114                              cs->c_symnum);
1115                   fcn_last_line = 0x7FFFFFFF;
1116                 }
1117               else
1118                 {
1119                   fcn_last_line = main_aux.x_sym.x_misc.x_lnsz.x_lnno;
1120                 }
1121               /* fcn_first_line is the line number of the opening '{'.
1122                  Do not record it - because it would affect gdb's idea
1123                  of the line number of the first statement of the
1124                  function - except for one-line functions, for which
1125                  it is also the line number of all the statements and
1126                  of the closing '}', and for which we do not have any
1127                  other statement-line-number.  */
1128               if (fcn_last_line == 1)
1129                 record_line (current_subfile, fcn_first_line,
1130                              gdbarch_addr_bits_remove (gdbarch,
1131                                                        fcn_first_line_addr));
1132               else
1133                 enter_linenos (fcn_line_ptr, fcn_first_line,
1134                                fcn_last_line, objfile);
1135
1136               finish_block (new->name, &local_symbols,
1137                             new->old_blocks, new->start_addr,
1138                             fcn_cs_saved.c_value
1139                             + fcn_aux_saved.x_sym.x_misc.x_fsize
1140                             + ANOFFSET (objfile->section_offsets,
1141                                         SECT_OFF_TEXT (objfile)),
1142                             objfile
1143                 );
1144               within_function = 0;
1145             }
1146           break;
1147
1148         case C_BLOCK:
1149           if (strcmp (cs->c_name, ".bb") == 0)
1150             {
1151               tmpaddr = cs->c_value;
1152               tmpaddr += ANOFFSET (objfile->section_offsets,
1153                                    SECT_OFF_TEXT (objfile));
1154               push_context (++depth, tmpaddr);
1155             }
1156           else if (strcmp (cs->c_name, ".eb") == 0)
1157             {
1158               if (context_stack_depth <= 0)
1159                 {       /* We attempted to pop an empty context stack.  */
1160                   complaint (&symfile_complaints,
1161                              _("`.eb' symbol without matching `.bb' "
1162                                "symbol ignored starting at symnum %d"),
1163                              cs->c_symnum);
1164                   break;
1165                 }
1166
1167               new = pop_context ();
1168               if (depth-- != new->depth)
1169                 {
1170                   complaint (&symfile_complaints,
1171                              _("Mismatched .eb symbol ignored "
1172                                "starting at symnum %d"),
1173                              symnum);
1174                   break;
1175                 }
1176               if (local_symbols && context_stack_depth > 0)
1177                 {
1178                   tmpaddr =
1179                     cs->c_value + ANOFFSET (objfile->section_offsets,
1180                                             SECT_OFF_TEXT (objfile));
1181                   /* Make a block for the local symbols within.  */
1182                   finish_block (0, &local_symbols, new->old_blocks,
1183                                 new->start_addr, tmpaddr, objfile);
1184                 }
1185               /* Now pop locals of block just finished.  */
1186               local_symbols = new->locals;
1187             }
1188           break;
1189
1190         default:
1191           process_coff_symbol (cs, &main_aux, objfile);
1192           break;
1193         }
1194     }
1195
1196   if ((nsyms == 0) && (pe_file))
1197     {
1198       /* We've got no debugging symbols, but it's a portable
1199          executable, so try to read the export table.  */
1200       read_pe_exported_syms (objfile);
1201     }
1202
1203   if (get_last_source_file ())
1204     coff_end_symtab (objfile);
1205
1206   /* Patch up any opaque types (references to types that are not defined
1207      in the file where they are referenced, e.g. "struct foo *bar").  */
1208   ALL_OBJFILE_SYMTABS (objfile, s)
1209     patch_opaque_types (s);
1210
1211   coffread_objfile = NULL;
1212 }
1213 \f
1214 /* Routines for reading headers and symbols from executable.  */
1215
1216 /* Read the next symbol, swap it, and return it in both
1217    internal_syment form, and coff_symbol form.  Also return its first
1218    auxent, if any, in internal_auxent form, and skip any other
1219    auxents.  */
1220
1221 static void
1222 read_one_sym (struct coff_symbol *cs,
1223               struct internal_syment *sym,
1224               union internal_auxent *aux)
1225 {
1226   int i;
1227   bfd_size_type bytes;
1228
1229   cs->c_symnum = symnum;
1230   bytes = bfd_bread (temp_sym, local_symesz, nlist_bfd_global);
1231   if (bytes != local_symesz)
1232     error (_("%s: error reading symbols"), coffread_objfile->name);
1233   bfd_coff_swap_sym_in (symfile_bfd, temp_sym, (char *) sym);
1234   cs->c_naux = sym->n_numaux & 0xff;
1235   if (cs->c_naux >= 1)
1236     {
1237       bytes  = bfd_bread (temp_aux, local_auxesz, nlist_bfd_global);
1238       if (bytes != local_auxesz)
1239         error (_("%s: error reading symbols"), coffread_objfile->name);
1240       bfd_coff_swap_aux_in (symfile_bfd, temp_aux,
1241                             sym->n_type, sym->n_sclass,
1242                             0, cs->c_naux, (char *) aux);
1243       /* If more than one aux entry, read past it (only the first aux
1244          is important).  */
1245       for (i = 1; i < cs->c_naux; i++)
1246         {
1247           bytes = bfd_bread (temp_aux, local_auxesz, nlist_bfd_global);
1248           if (bytes != local_auxesz)
1249             error (_("%s: error reading symbols"), coffread_objfile->name);
1250         }
1251     }
1252   cs->c_name = getsymname (sym);
1253   cs->c_value = sym->n_value;
1254   cs->c_sclass = (sym->n_sclass & 0xff);
1255   cs->c_secnum = sym->n_scnum;
1256   cs->c_type = (unsigned) sym->n_type;
1257   if (!SDB_TYPE (cs->c_type))
1258     cs->c_type = 0;
1259
1260 #if 0
1261   if (cs->c_sclass & 128)
1262     printf (_("thumb symbol %s, class 0x%x\n"), cs->c_name, cs->c_sclass);
1263 #endif
1264
1265   symnum += 1 + cs->c_naux;
1266
1267   /* The PE file format stores symbol values as offsets within the
1268      section, rather than as absolute addresses.  We correct that
1269      here, if the symbol has an appropriate storage class.  FIXME: We
1270      should use BFD to read the symbols, rather than duplicating the
1271      work here.  */
1272   if (pe_file)
1273     {
1274       switch (cs->c_sclass)
1275         {
1276         case C_EXT:
1277         case C_THUMBEXT:
1278         case C_THUMBEXTFUNC:
1279         case C_SECTION:
1280         case C_NT_WEAK:
1281         case C_STAT:
1282         case C_THUMBSTAT:
1283         case C_THUMBSTATFUNC:
1284         case C_LABEL:
1285         case C_THUMBLABEL:
1286         case C_BLOCK:
1287         case C_FCN:
1288         case C_EFCN:
1289           if (cs->c_secnum != 0)
1290             cs->c_value += cs_section_address (cs, symfile_bfd);
1291           break;
1292         }
1293     }
1294 }
1295 \f
1296 /* Support for string table handling.  */
1297
1298 static char *stringtab = NULL;
1299
1300 static int
1301 init_stringtab (bfd *abfd, long offset)
1302 {
1303   long length;
1304   int val;
1305   unsigned char lengthbuf[4];
1306
1307   free_stringtab ();
1308
1309   /* If the file is stripped, the offset might be zero, indicating no
1310      string table.  Just return with `stringtab' set to null.  */
1311   if (offset == 0)
1312     return 0;
1313
1314   if (bfd_seek (abfd, offset, 0) < 0)
1315     return -1;
1316
1317   val = bfd_bread ((char *) lengthbuf, sizeof lengthbuf, abfd);
1318   length = bfd_h_get_32 (symfile_bfd, lengthbuf);
1319
1320   /* If no string table is needed, then the file may end immediately
1321      after the symbols.  Just return with `stringtab' set to null.  */
1322   if (val != sizeof lengthbuf || length < sizeof lengthbuf)
1323     return 0;
1324
1325   stringtab = (char *) xmalloc (length);
1326   /* This is in target format (probably not very useful, and not
1327      currently used), not host format.  */
1328   memcpy (stringtab, lengthbuf, sizeof lengthbuf);
1329   if (length == sizeof length)  /* Empty table -- just the count.  */
1330     return 0;
1331
1332   val = bfd_bread (stringtab + sizeof lengthbuf, 
1333                    length - sizeof lengthbuf, abfd);
1334   if (val != length - sizeof lengthbuf || stringtab[length - 1] != '\0')
1335     return -1;
1336
1337   return 0;
1338 }
1339
1340 static void
1341 free_stringtab (void)
1342 {
1343   if (stringtab)
1344     xfree (stringtab);
1345   stringtab = NULL;
1346 }
1347
1348 static void
1349 free_stringtab_cleanup (void *ignore)
1350 {
1351   free_stringtab ();
1352 }
1353
1354 static char *
1355 getsymname (struct internal_syment *symbol_entry)
1356 {
1357   static char buffer[SYMNMLEN + 1];
1358   char *result;
1359
1360   if (symbol_entry->_n._n_n._n_zeroes == 0)
1361     {
1362       /* FIXME: Probably should be detecting corrupt symbol files by
1363          seeing whether offset points to within the stringtab.  */
1364       result = stringtab + symbol_entry->_n._n_n._n_offset;
1365     }
1366   else
1367     {
1368       strncpy (buffer, symbol_entry->_n._n_name, SYMNMLEN);
1369       buffer[SYMNMLEN] = '\0';
1370       result = buffer;
1371     }
1372   return result;
1373 }
1374
1375 /* Extract the file name from the aux entry of a C_FILE symbol.
1376    Return only the last component of the name.  Result is in static
1377    storage and is only good for temporary use.  */
1378
1379 static const char *
1380 coff_getfilename (union internal_auxent *aux_entry)
1381 {
1382   static char buffer[BUFSIZ];
1383   const char *result;
1384
1385   if (aux_entry->x_file.x_n.x_zeroes == 0)
1386     {
1387       if (strlen (stringtab + aux_entry->x_file.x_n.x_offset) >= BUFSIZ)
1388         internal_error (__FILE__, __LINE__, _("coff file name too long"));
1389       strcpy (buffer, stringtab + aux_entry->x_file.x_n.x_offset);
1390     }
1391   else
1392     {
1393       strncpy (buffer, aux_entry->x_file.x_fname, FILNMLEN);
1394       buffer[FILNMLEN] = '\0';
1395     }
1396   result = buffer;
1397
1398   /* FIXME: We should not be throwing away the information about what
1399      directory.  It should go into dirname of the symtab, or some such
1400      place.  */
1401   result = lbasename (result);
1402   return (result);
1403 }
1404 \f
1405 /* Support for line number handling.  */
1406
1407 static char *linetab = NULL;
1408 static long linetab_offset;
1409 static unsigned long linetab_size;
1410
1411 /* Read in all the line numbers for fast lookups later.  Leave them in
1412    external (unswapped) format in memory; we'll swap them as we enter
1413    them into GDB's data structures.  */
1414
1415 static int
1416 init_lineno (bfd *abfd, long offset, int size)
1417 {
1418   int val;
1419
1420   linetab_offset = offset;
1421   linetab_size = size;
1422
1423   free_linetab ();
1424
1425   if (size == 0)
1426     return 0;
1427
1428   if (bfd_seek (abfd, offset, 0) < 0)
1429     return -1;
1430
1431   /* Allocate the desired table, plus a sentinel.  */
1432   linetab = (char *) xmalloc (size + local_linesz);
1433
1434   val = bfd_bread (linetab, size, abfd);
1435   if (val != size)
1436     return -1;
1437
1438   /* Terminate it with an all-zero sentinel record.  */
1439   memset (linetab + size, 0, local_linesz);
1440
1441   return 0;
1442 }
1443
1444 static void
1445 free_linetab (void)
1446 {
1447   if (linetab)
1448     xfree (linetab);
1449   linetab = NULL;
1450 }
1451
1452 static void
1453 free_linetab_cleanup (void *ignore)
1454 {
1455   free_linetab ();
1456 }
1457
1458 #if !defined (L_LNNO32)
1459 #define L_LNNO32(lp) ((lp)->l_lnno)
1460 #endif
1461
1462 static void
1463 enter_linenos (long file_offset, int first_line,
1464                int last_line, struct objfile *objfile)
1465 {
1466   struct gdbarch *gdbarch = get_objfile_arch (objfile);
1467   char *rawptr;
1468   struct internal_lineno lptr;
1469
1470   if (!linetab)
1471     return;
1472   if (file_offset < linetab_offset)
1473     {
1474       complaint (&symfile_complaints,
1475                  _("Line number pointer %ld lower than start of line numbers"),
1476                  file_offset);
1477       if (file_offset > linetab_size)   /* Too big to be an offset?  */
1478         return;
1479       file_offset += linetab_offset;    /* Try reading at that linetab
1480                                            offset.  */
1481     }
1482
1483   rawptr = &linetab[file_offset - linetab_offset];
1484
1485   /* Skip first line entry for each function.  */
1486   rawptr += local_linesz;
1487   /* Line numbers start at one for the first line of the function.  */
1488   first_line--;
1489
1490   /* If the line number table is full (e.g. 64K lines in COFF debug
1491      info), the next function's L_LNNO32 might not be zero, so don't
1492      overstep the table's end in any case.  */
1493   while (rawptr <= &linetab[0] + linetab_size)
1494     {
1495       bfd_coff_swap_lineno_in (symfile_bfd, rawptr, &lptr);
1496       rawptr += local_linesz;
1497       /* The next function, or the sentinel, will have L_LNNO32 zero;
1498          we exit.  */
1499       if (L_LNNO32 (&lptr) && L_LNNO32 (&lptr) <= last_line)
1500         {
1501           CORE_ADDR addr = lptr.l_addr.l_paddr;
1502           addr += ANOFFSET (objfile->section_offsets,
1503                             SECT_OFF_TEXT (objfile));
1504           record_line (current_subfile,
1505                        first_line + L_LNNO32 (&lptr),
1506                        gdbarch_addr_bits_remove (gdbarch, addr));
1507         }
1508       else
1509         break;
1510     }
1511 }
1512 \f
1513 static void
1514 patch_type (struct type *type, struct type *real_type)
1515 {
1516   struct type *target = TYPE_TARGET_TYPE (type);
1517   struct type *real_target = TYPE_TARGET_TYPE (real_type);
1518   int field_size = TYPE_NFIELDS (real_target) * sizeof (struct field);
1519
1520   TYPE_LENGTH (target) = TYPE_LENGTH (real_target);
1521   TYPE_NFIELDS (target) = TYPE_NFIELDS (real_target);
1522   TYPE_FIELDS (target) = (struct field *) TYPE_ALLOC (target,
1523                                                       field_size);
1524
1525   memcpy (TYPE_FIELDS (target), 
1526           TYPE_FIELDS (real_target), 
1527           field_size);
1528
1529   if (TYPE_NAME (real_target))
1530     {
1531       /* The previous copy of TYPE_NAME is allocated by
1532          process_coff_symbol.  */
1533       if (TYPE_NAME (target))
1534         xfree ((char*) TYPE_NAME (target));
1535       TYPE_NAME (target) = xstrdup (TYPE_NAME (real_target));
1536     }
1537 }
1538
1539 /* Patch up all appropriate typedef symbols in the opaque_type_chains
1540    so that they can be used to print out opaque data structures
1541    properly.  */
1542
1543 static void
1544 patch_opaque_types (struct symtab *s)
1545 {
1546   struct block *b;
1547   struct block_iterator iter;
1548   struct symbol *real_sym;
1549
1550   /* Go through the per-file symbols only.  */
1551   b = BLOCKVECTOR_BLOCK (BLOCKVECTOR (s), STATIC_BLOCK);
1552   ALL_BLOCK_SYMBOLS (b, iter, real_sym)
1553     {
1554       /* Find completed typedefs to use to fix opaque ones.
1555          Remove syms from the chain when their types are stored,
1556          but search the whole chain, as there may be several syms
1557          from different files with the same name.  */
1558       if (SYMBOL_CLASS (real_sym) == LOC_TYPEDEF
1559           && SYMBOL_DOMAIN (real_sym) == VAR_DOMAIN
1560           && TYPE_CODE (SYMBOL_TYPE (real_sym)) == TYPE_CODE_PTR
1561           && TYPE_LENGTH (TYPE_TARGET_TYPE (SYMBOL_TYPE (real_sym))) != 0)
1562         {
1563           const char *name = SYMBOL_LINKAGE_NAME (real_sym);
1564           int hash = hashname (name);
1565           struct symbol *sym, *prev;
1566
1567           prev = 0;
1568           for (sym = opaque_type_chain[hash]; sym;)
1569             {
1570               if (name[0] == SYMBOL_LINKAGE_NAME (sym)[0]
1571                   && strcmp (name + 1, SYMBOL_LINKAGE_NAME (sym) + 1) == 0)
1572                 {
1573                   if (prev)
1574                     {
1575                       SYMBOL_VALUE_CHAIN (prev) = SYMBOL_VALUE_CHAIN (sym);
1576                     }
1577                   else
1578                     {
1579                       opaque_type_chain[hash] = SYMBOL_VALUE_CHAIN (sym);
1580                     }
1581
1582                   patch_type (SYMBOL_TYPE (sym), SYMBOL_TYPE (real_sym));
1583
1584                   if (prev)
1585                     {
1586                       sym = SYMBOL_VALUE_CHAIN (prev);
1587                     }
1588                   else
1589                     {
1590                       sym = opaque_type_chain[hash];
1591                     }
1592                 }
1593               else
1594                 {
1595                   prev = sym;
1596                   sym = SYMBOL_VALUE_CHAIN (sym);
1597                 }
1598             }
1599         }
1600     }
1601 }
1602 \f
1603 static int
1604 coff_reg_to_regnum (struct symbol *sym, struct gdbarch *gdbarch)
1605 {
1606   return gdbarch_sdb_reg_to_regnum (gdbarch, SYMBOL_VALUE (sym));
1607 }
1608
1609 static const struct symbol_register_ops coff_register_funcs = {
1610   coff_reg_to_regnum
1611 };
1612
1613 /* The "aclass" index for computed COFF symbols.  */
1614
1615 static int coff_register_index;
1616
1617 static struct symbol *
1618 process_coff_symbol (struct coff_symbol *cs,
1619                      union internal_auxent *aux,
1620                      struct objfile *objfile)
1621 {
1622   struct symbol *sym = allocate_symbol (objfile);
1623   char *name;
1624
1625   name = cs->c_name;
1626   name = EXTERNAL_NAME (name, objfile->obfd);
1627   SYMBOL_SET_LANGUAGE (sym, current_subfile->language,
1628                        &objfile->objfile_obstack);
1629   SYMBOL_SET_NAMES (sym, name, strlen (name), 1, objfile);
1630
1631   /* default assumptions */
1632   SYMBOL_VALUE (sym) = cs->c_value;
1633   SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
1634   SYMBOL_SECTION (sym) = cs_to_section (cs, objfile);
1635
1636   if (ISFCN (cs->c_type))
1637     {
1638       SYMBOL_VALUE (sym) += ANOFFSET (objfile->section_offsets,
1639                                       SECT_OFF_TEXT (objfile));
1640       SYMBOL_TYPE (sym) =
1641         lookup_function_type (decode_function_type (cs, cs->c_type,
1642                                                     aux, objfile));
1643
1644       SYMBOL_ACLASS_INDEX (sym) = LOC_BLOCK;
1645       if (cs->c_sclass == C_STAT || cs->c_sclass == C_THUMBSTAT
1646           || cs->c_sclass == C_THUMBSTATFUNC)
1647         add_symbol_to_list (sym, &file_symbols);
1648       else if (cs->c_sclass == C_EXT || cs->c_sclass == C_THUMBEXT
1649                || cs->c_sclass == C_THUMBEXTFUNC)
1650         add_symbol_to_list (sym, &global_symbols);
1651     }
1652   else
1653     {
1654       SYMBOL_TYPE (sym) = decode_type (cs, cs->c_type, aux, objfile);
1655       switch (cs->c_sclass)
1656         {
1657         case C_NULL:
1658           break;
1659
1660         case C_AUTO:
1661           SYMBOL_ACLASS_INDEX (sym) = LOC_LOCAL;
1662           add_symbol_to_list (sym, &local_symbols);
1663           break;
1664
1665         case C_THUMBEXT:
1666         case C_THUMBEXTFUNC:
1667         case C_EXT:
1668           SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
1669           SYMBOL_VALUE_ADDRESS (sym) = (CORE_ADDR) cs->c_value;
1670           SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
1671                                                   SECT_OFF_TEXT (objfile));
1672           add_symbol_to_list (sym, &global_symbols);
1673           break;
1674
1675         case C_THUMBSTAT:
1676         case C_THUMBSTATFUNC:
1677         case C_STAT:
1678           SYMBOL_ACLASS_INDEX (sym) = LOC_STATIC;
1679           SYMBOL_VALUE_ADDRESS (sym) = (CORE_ADDR) cs->c_value;
1680           SYMBOL_VALUE_ADDRESS (sym) += ANOFFSET (objfile->section_offsets,
1681                                                   SECT_OFF_TEXT (objfile));
1682           if (within_function)
1683             {
1684               /* Static symbol of local scope.  */
1685               add_symbol_to_list (sym, &local_symbols);
1686             }
1687           else
1688             {
1689               /* Static symbol at top level of file.  */
1690               add_symbol_to_list (sym, &file_symbols);
1691             }
1692           break;
1693
1694 #ifdef C_GLBLREG                /* AMD coff */
1695         case C_GLBLREG:
1696 #endif
1697         case C_REG:
1698           SYMBOL_ACLASS_INDEX (sym) = coff_register_index;
1699           SYMBOL_VALUE (sym) = cs->c_value;
1700           add_symbol_to_list (sym, &local_symbols);
1701           break;
1702
1703         case C_THUMBLABEL:
1704         case C_LABEL:
1705           break;
1706
1707         case C_ARG:
1708           SYMBOL_ACLASS_INDEX (sym) = LOC_ARG;
1709           SYMBOL_IS_ARGUMENT (sym) = 1;
1710           add_symbol_to_list (sym, &local_symbols);
1711           break;
1712
1713         case C_REGPARM:
1714           SYMBOL_ACLASS_INDEX (sym) = coff_register_index;
1715           SYMBOL_IS_ARGUMENT (sym) = 1;
1716           SYMBOL_VALUE (sym) = cs->c_value;
1717           add_symbol_to_list (sym, &local_symbols);
1718           break;
1719
1720         case C_TPDEF:
1721           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
1722           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
1723
1724           /* If type has no name, give it one.  */
1725           if (TYPE_NAME (SYMBOL_TYPE (sym)) == 0)
1726             {
1727               if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_PTR
1728                   || TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_FUNC)
1729                 {
1730                   /* If we are giving a name to a type such as
1731                      "pointer to foo" or "function returning foo", we
1732                      better not set the TYPE_NAME.  If the program
1733                      contains "typedef char *caddr_t;", we don't want 
1734                      all variables of type char * to print as caddr_t.
1735                      This is not just a consequence of GDB's type
1736                      management; CC and GCC (at least through version
1737                      2.4) both output variables of either type char *
1738                      or caddr_t with the type refering to the C_TPDEF
1739                      symbol for caddr_t.  If a future compiler cleans
1740                      this up it GDB is not ready for it yet, but if it
1741                      becomes ready we somehow need to disable this
1742                      check (without breaking the PCC/GCC2.4 case).
1743
1744                      Sigh.
1745
1746                      Fortunately, this check seems not to be necessary
1747                      for anything except pointers or functions.  */
1748                   ;
1749                 }
1750               else
1751                 TYPE_NAME (SYMBOL_TYPE (sym)) =
1752                   xstrdup (SYMBOL_LINKAGE_NAME (sym));
1753             }
1754
1755           /* Keep track of any type which points to empty structured
1756              type, so it can be filled from a definition from another
1757              file.  A simple forward reference (TYPE_CODE_UNDEF) is
1758              not an empty structured type, though; the forward
1759              references work themselves out via the magic of
1760              coff_lookup_type.  */
1761           if (TYPE_CODE (SYMBOL_TYPE (sym)) == TYPE_CODE_PTR
1762               && TYPE_LENGTH (TYPE_TARGET_TYPE (SYMBOL_TYPE (sym))) == 0
1763               && TYPE_CODE (TYPE_TARGET_TYPE (SYMBOL_TYPE (sym)))
1764                  != TYPE_CODE_UNDEF)
1765             {
1766               int i = hashname (SYMBOL_LINKAGE_NAME (sym));
1767
1768               SYMBOL_VALUE_CHAIN (sym) = opaque_type_chain[i];
1769               opaque_type_chain[i] = sym;
1770             }
1771           add_symbol_to_list (sym, &file_symbols);
1772           break;
1773
1774         case C_STRTAG:
1775         case C_UNTAG:
1776         case C_ENTAG:
1777           SYMBOL_ACLASS_INDEX (sym) = LOC_TYPEDEF;
1778           SYMBOL_DOMAIN (sym) = STRUCT_DOMAIN;
1779
1780           /* Some compilers try to be helpful by inventing "fake"
1781              names for anonymous enums, structures, and unions, like
1782              "~0fake" or ".0fake".  Thanks, but no thanks...  */
1783           if (TYPE_TAG_NAME (SYMBOL_TYPE (sym)) == 0)
1784             if (SYMBOL_LINKAGE_NAME (sym) != NULL
1785                 && *SYMBOL_LINKAGE_NAME (sym) != '~'
1786                 && *SYMBOL_LINKAGE_NAME (sym) != '.')
1787               TYPE_TAG_NAME (SYMBOL_TYPE (sym)) =
1788                 concat (SYMBOL_LINKAGE_NAME (sym), (char *)NULL);
1789
1790           add_symbol_to_list (sym, &file_symbols);
1791           break;
1792
1793         default:
1794           break;
1795         }
1796     }
1797   return sym;
1798 }
1799 \f
1800 /* Decode a coff type specifier;  return the type that is meant.  */
1801
1802 static struct type *
1803 decode_type (struct coff_symbol *cs, unsigned int c_type,
1804              union internal_auxent *aux, struct objfile *objfile)
1805 {
1806   struct type *type = 0;
1807   unsigned int new_c_type;
1808
1809   if (c_type & ~N_BTMASK)
1810     {
1811       new_c_type = DECREF (c_type);
1812       if (ISPTR (c_type))
1813         {
1814           type = decode_type (cs, new_c_type, aux, objfile);
1815           type = lookup_pointer_type (type);
1816         }
1817       else if (ISFCN (c_type))
1818         {
1819           type = decode_type (cs, new_c_type, aux, objfile);
1820           type = lookup_function_type (type);
1821         }
1822       else if (ISARY (c_type))
1823         {
1824           int i, n;
1825           unsigned short *dim;
1826           struct type *base_type, *index_type, *range_type;
1827
1828           /* Define an array type.  */
1829           /* auxent refers to array, not base type.  */
1830           if (aux->x_sym.x_tagndx.l == 0)
1831             cs->c_naux = 0;
1832
1833           /* Shift the indices down.  */
1834           dim = &aux->x_sym.x_fcnary.x_ary.x_dimen[0];
1835           i = 1;
1836           n = dim[0];
1837           for (i = 0; *dim && i < DIMNUM - 1; i++, dim++)
1838             *dim = *(dim + 1);
1839           *dim = 0;
1840
1841           base_type = decode_type (cs, new_c_type, aux, objfile);
1842           index_type = objfile_type (objfile)->builtin_int;
1843           range_type =
1844             create_range_type ((struct type *) NULL, 
1845                                index_type, 0, n - 1);
1846           type =
1847             create_array_type ((struct type *) NULL, 
1848                                base_type, range_type);
1849         }
1850       return type;
1851     }
1852
1853   /* Reference to existing type.  This only occurs with the struct,
1854      union, and enum types.  EPI a29k coff fakes us out by producing
1855      aux entries with a nonzero x_tagndx for definitions of structs,
1856      unions, and enums, so we have to check the c_sclass field.  SCO
1857      3.2v4 cc gets confused with pointers to pointers to defined
1858      structs, and generates negative x_tagndx fields.  */
1859   if (cs->c_naux > 0 && aux->x_sym.x_tagndx.l != 0)
1860     {
1861       if (cs->c_sclass != C_STRTAG
1862           && cs->c_sclass != C_UNTAG
1863           && cs->c_sclass != C_ENTAG
1864           && aux->x_sym.x_tagndx.l >= 0)
1865         {
1866           type = coff_alloc_type (aux->x_sym.x_tagndx.l);
1867           return type;
1868         }
1869       else
1870         {
1871           complaint (&symfile_complaints,
1872                      _("Symbol table entry for %s has bad tagndx value"),
1873                      cs->c_name);
1874           /* And fall through to decode_base_type...  */
1875         }
1876     }
1877
1878   return decode_base_type (cs, BTYPE (c_type), aux, objfile);
1879 }
1880
1881 /* Decode a coff type specifier for function definition;
1882    return the type that the function returns.  */
1883
1884 static struct type *
1885 decode_function_type (struct coff_symbol *cs, 
1886                       unsigned int c_type,
1887                       union internal_auxent *aux, 
1888                       struct objfile *objfile)
1889 {
1890   if (aux->x_sym.x_tagndx.l == 0)
1891     cs->c_naux = 0;     /* auxent refers to function, not base
1892                            type.  */
1893
1894   return decode_type (cs, DECREF (c_type), aux, objfile);
1895 }
1896 \f
1897 /* Basic C types.  */
1898
1899 static struct type *
1900 decode_base_type (struct coff_symbol *cs, 
1901                   unsigned int c_type,
1902                   union internal_auxent *aux, 
1903                   struct objfile *objfile)
1904 {
1905   struct gdbarch *gdbarch = get_objfile_arch (objfile);
1906   struct type *type;
1907
1908   switch (c_type)
1909     {
1910     case T_NULL:
1911       /* Shows up with "void (*foo)();" structure members.  */
1912       return objfile_type (objfile)->builtin_void;
1913
1914 #ifdef T_VOID
1915     case T_VOID:
1916       /* Intel 960 COFF has this symbol and meaning.  */
1917       return objfile_type (objfile)->builtin_void;
1918 #endif
1919
1920     case T_CHAR:
1921       return objfile_type (objfile)->builtin_char;
1922
1923     case T_SHORT:
1924       return objfile_type (objfile)->builtin_short;
1925
1926     case T_INT:
1927       return objfile_type (objfile)->builtin_int;
1928
1929     case T_LONG:
1930       if (cs->c_sclass == C_FIELD
1931           && aux->x_sym.x_misc.x_lnsz.x_size
1932              > gdbarch_long_bit (gdbarch))
1933         return objfile_type (objfile)->builtin_long_long;
1934       else
1935         return objfile_type (objfile)->builtin_long;
1936
1937     case T_FLOAT:
1938       return objfile_type (objfile)->builtin_float;
1939
1940     case T_DOUBLE:
1941       return objfile_type (objfile)->builtin_double;
1942
1943     case T_LNGDBL:
1944       return objfile_type (objfile)->builtin_long_double;
1945
1946     case T_STRUCT:
1947       if (cs->c_naux != 1)
1948         {
1949           /* Anonymous structure type.  */
1950           type = coff_alloc_type (cs->c_symnum);
1951           TYPE_CODE (type) = TYPE_CODE_STRUCT;
1952           TYPE_NAME (type) = NULL;
1953           /* This used to set the tag to "<opaque>".  But I think
1954              setting it to NULL is right, and the printing code can
1955              print it as "struct {...}".  */
1956           TYPE_TAG_NAME (type) = NULL;
1957           INIT_CPLUS_SPECIFIC (type);
1958           TYPE_LENGTH (type) = 0;
1959           TYPE_FIELDS (type) = 0;
1960           TYPE_NFIELDS (type) = 0;
1961         }
1962       else
1963         {
1964           type = coff_read_struct_type (cs->c_symnum,
1965                                         aux->x_sym.x_misc.x_lnsz.x_size,
1966                                         aux->x_sym.x_fcnary.x_fcn.x_endndx.l,
1967                                         objfile);
1968         }
1969       return type;
1970
1971     case T_UNION:
1972       if (cs->c_naux != 1)
1973         {
1974           /* Anonymous union type.  */
1975           type = coff_alloc_type (cs->c_symnum);
1976           TYPE_NAME (type) = NULL;
1977           /* This used to set the tag to "<opaque>".  But I think
1978              setting it to NULL is right, and the printing code can
1979              print it as "union {...}".  */
1980           TYPE_TAG_NAME (type) = NULL;
1981           INIT_CPLUS_SPECIFIC (type);
1982           TYPE_LENGTH (type) = 0;
1983           TYPE_FIELDS (type) = 0;
1984           TYPE_NFIELDS (type) = 0;
1985         }
1986       else
1987         {
1988           type = coff_read_struct_type (cs->c_symnum,
1989                                         aux->x_sym.x_misc.x_lnsz.x_size,
1990                                         aux->x_sym.x_fcnary.x_fcn.x_endndx.l,
1991                                         objfile);
1992         }
1993       TYPE_CODE (type) = TYPE_CODE_UNION;
1994       return type;
1995
1996     case T_ENUM:
1997       if (cs->c_naux != 1)
1998         {
1999           /* Anonymous enum type.  */
2000           type = coff_alloc_type (cs->c_symnum);
2001           TYPE_CODE (type) = TYPE_CODE_ENUM;
2002           TYPE_NAME (type) = NULL;
2003           /* This used to set the tag to "<opaque>".  But I think
2004              setting it to NULL is right, and the printing code can
2005              print it as "enum {...}".  */
2006           TYPE_TAG_NAME (type) = NULL;
2007           TYPE_LENGTH (type) = 0;
2008           TYPE_FIELDS (type) = 0;
2009           TYPE_NFIELDS (type) = 0;
2010         }
2011       else
2012         {
2013           type = coff_read_enum_type (cs->c_symnum,
2014                                       aux->x_sym.x_misc.x_lnsz.x_size,
2015                                       aux->x_sym.x_fcnary.x_fcn.x_endndx.l,
2016                                       objfile);
2017         }
2018       return type;
2019
2020     case T_MOE:
2021       /* Shouldn't show up here.  */
2022       break;
2023
2024     case T_UCHAR:
2025       return objfile_type (objfile)->builtin_unsigned_char;
2026
2027     case T_USHORT:
2028       return objfile_type (objfile)->builtin_unsigned_short;
2029
2030     case T_UINT:
2031       return objfile_type (objfile)->builtin_unsigned_int;
2032
2033     case T_ULONG:
2034       if (cs->c_sclass == C_FIELD
2035           && aux->x_sym.x_misc.x_lnsz.x_size
2036              > gdbarch_long_bit (gdbarch))
2037         return objfile_type (objfile)->builtin_unsigned_long_long;
2038       else
2039         return objfile_type (objfile)->builtin_unsigned_long;
2040     }
2041   complaint (&symfile_complaints, 
2042              _("Unexpected type for symbol %s"), cs->c_name);
2043   return objfile_type (objfile)->builtin_void;
2044 }
2045 \f
2046 /* This page contains subroutines of read_type.  */
2047
2048 /* Read the description of a structure (or union type) and return an
2049    object describing the type.  */
2050
2051 static struct type *
2052 coff_read_struct_type (int index, int length, int lastsym,
2053                        struct objfile *objfile)
2054 {
2055   struct nextfield
2056     {
2057       struct nextfield *next;
2058       struct field field;
2059     };
2060
2061   struct type *type;
2062   struct nextfield *list = 0;
2063   struct nextfield *new;
2064   int nfields = 0;
2065   int n;
2066   char *name;
2067   struct coff_symbol member_sym;
2068   struct coff_symbol *ms = &member_sym;
2069   struct internal_syment sub_sym;
2070   union internal_auxent sub_aux;
2071   int done = 0;
2072
2073   type = coff_alloc_type (index);
2074   TYPE_CODE (type) = TYPE_CODE_STRUCT;
2075   INIT_CPLUS_SPECIFIC (type);
2076   TYPE_LENGTH (type) = length;
2077
2078   while (!done && symnum < lastsym && symnum < nlist_nsyms_global)
2079     {
2080       read_one_sym (ms, &sub_sym, &sub_aux);
2081       name = ms->c_name;
2082       name = EXTERNAL_NAME (name, objfile->obfd);
2083
2084       switch (ms->c_sclass)
2085         {
2086         case C_MOS:
2087         case C_MOU:
2088
2089           /* Get space to record the next field's data.  */
2090           new = (struct nextfield *) alloca (sizeof (struct nextfield));
2091           new->next = list;
2092           list = new;
2093
2094           /* Save the data.  */
2095           list->field.name = obstack_copy0 (&objfile->objfile_obstack,
2096                                             name, strlen (name));
2097           FIELD_TYPE (list->field) = decode_type (ms, ms->c_type,
2098                                                   &sub_aux, objfile);
2099           SET_FIELD_BITPOS (list->field, 8 * ms->c_value);
2100           FIELD_BITSIZE (list->field) = 0;
2101           nfields++;
2102           break;
2103
2104         case C_FIELD:
2105
2106           /* Get space to record the next field's data.  */
2107           new = (struct nextfield *) alloca (sizeof (struct nextfield));
2108           new->next = list;
2109           list = new;
2110
2111           /* Save the data.  */
2112           list->field.name = obstack_copy0 (&objfile->objfile_obstack,
2113                                             name, strlen (name));
2114           FIELD_TYPE (list->field) = decode_type (ms, ms->c_type,
2115                                                   &sub_aux, objfile);
2116           SET_FIELD_BITPOS (list->field, ms->c_value);
2117           FIELD_BITSIZE (list->field) = sub_aux.x_sym.x_misc.x_lnsz.x_size;
2118           nfields++;
2119           break;
2120
2121         case C_EOS:
2122           done = 1;
2123           break;
2124         }
2125     }
2126   /* Now create the vector of fields, and record how big it is.  */
2127
2128   TYPE_NFIELDS (type) = nfields;
2129   TYPE_FIELDS (type) = (struct field *)
2130     TYPE_ALLOC (type, sizeof (struct field) * nfields);
2131
2132   /* Copy the saved-up fields into the field vector.  */
2133
2134   for (n = nfields; list; list = list->next)
2135     TYPE_FIELD (type, --n) = list->field;
2136
2137   return type;
2138 }
2139 \f
2140 /* Read a definition of an enumeration type,
2141    and create and return a suitable type object.
2142    Also defines the symbols that represent the values of the type.  */
2143
2144 static struct type *
2145 coff_read_enum_type (int index, int length, int lastsym,
2146                      struct objfile *objfile)
2147 {
2148   struct gdbarch *gdbarch = get_objfile_arch (objfile);
2149   struct symbol *sym;
2150   struct type *type;
2151   int nsyms = 0;
2152   int done = 0;
2153   struct pending **symlist;
2154   struct coff_symbol member_sym;
2155   struct coff_symbol *ms = &member_sym;
2156   struct internal_syment sub_sym;
2157   union internal_auxent sub_aux;
2158   struct pending *osyms, *syms;
2159   int o_nsyms;
2160   int n;
2161   char *name;
2162   int unsigned_enum = 1;
2163
2164   type = coff_alloc_type (index);
2165   if (within_function)
2166     symlist = &local_symbols;
2167   else
2168     symlist = &file_symbols;
2169   osyms = *symlist;
2170   o_nsyms = osyms ? osyms->nsyms : 0;
2171
2172   while (!done && symnum < lastsym && symnum < nlist_nsyms_global)
2173     {
2174       read_one_sym (ms, &sub_sym, &sub_aux);
2175       name = ms->c_name;
2176       name = EXTERNAL_NAME (name, objfile->obfd);
2177
2178       switch (ms->c_sclass)
2179         {
2180         case C_MOE:
2181           sym = allocate_symbol (objfile);
2182
2183           SYMBOL_SET_LINKAGE_NAME (sym,
2184                                    obstack_copy0 (&objfile->objfile_obstack,
2185                                                   name, strlen (name)));
2186           SYMBOL_ACLASS_INDEX (sym) = LOC_CONST;
2187           SYMBOL_DOMAIN (sym) = VAR_DOMAIN;
2188           SYMBOL_VALUE (sym) = ms->c_value;
2189           add_symbol_to_list (sym, symlist);
2190           nsyms++;
2191           break;
2192
2193         case C_EOS:
2194           /* Sometimes the linker (on 386/ix 2.0.2 at least) screws
2195              up the count of how many symbols to read.  So stop
2196              on .eos.  */
2197           done = 1;
2198           break;
2199         }
2200     }
2201
2202   /* Now fill in the fields of the type-structure.  */
2203
2204   if (length > 0)
2205     TYPE_LENGTH (type) = length;
2206   else /* Assume ints.  */
2207     TYPE_LENGTH (type) = gdbarch_int_bit (gdbarch) / TARGET_CHAR_BIT;
2208   TYPE_CODE (type) = TYPE_CODE_ENUM;
2209   TYPE_NFIELDS (type) = nsyms;
2210   TYPE_FIELDS (type) = (struct field *)
2211     TYPE_ALLOC (type, sizeof (struct field) * nsyms);
2212
2213   /* Find the symbols for the values and put them into the type.
2214      The symbols can be found in the symlist that we put them on
2215      to cause them to be defined.  osyms contains the old value
2216      of that symlist; everything up to there was defined by us.  */
2217   /* Note that we preserve the order of the enum constants, so
2218      that in something like "enum {FOO, LAST_THING=FOO}" we print
2219      FOO, not LAST_THING.  */
2220
2221   for (syms = *symlist, n = 0; syms; syms = syms->next)
2222     {
2223       int j = 0;
2224
2225       if (syms == osyms)
2226         j = o_nsyms;
2227       for (; j < syms->nsyms; j++, n++)
2228         {
2229           struct symbol *xsym = syms->symbol[j];
2230
2231           SYMBOL_TYPE (xsym) = type;
2232           TYPE_FIELD_NAME (type, n) = SYMBOL_LINKAGE_NAME (xsym);
2233           SET_FIELD_ENUMVAL (TYPE_FIELD (type, n), SYMBOL_VALUE (xsym));
2234           if (SYMBOL_VALUE (xsym) < 0)
2235             unsigned_enum = 0;
2236           TYPE_FIELD_BITSIZE (type, n) = 0;
2237         }
2238       if (syms == osyms)
2239         break;
2240     }
2241
2242   if (unsigned_enum)
2243     TYPE_UNSIGNED (type) = 1;
2244
2245   return type;
2246 }
2247
2248 /* Register our ability to parse symbols for coff BFD files.  */
2249
2250 static const struct sym_fns coff_sym_fns =
2251 {
2252   bfd_target_coff_flavour,
2253   coff_new_init,                /* sym_new_init: init anything gbl to
2254                                    entire symtab */
2255   coff_symfile_init,            /* sym_init: read initial info, setup
2256                                    for sym_read() */
2257   coff_symfile_read,            /* sym_read: read a symbol file into
2258                                    symtab */
2259   NULL,                         /* sym_read_psymbols */
2260   coff_symfile_finish,          /* sym_finish: finished with file,
2261                                    cleanup */
2262   default_symfile_offsets,      /* sym_offsets: xlate external to
2263                                    internal form */
2264   default_symfile_segments,     /* sym_segments: Get segment
2265                                    information from a file */
2266   NULL,                         /* sym_read_linetable  */
2267
2268   default_symfile_relocate,     /* sym_relocate: Relocate a debug
2269                                    section.  */
2270   NULL,                         /* sym_probe_fns */
2271   &psym_functions
2272 };
2273
2274 /* Free the per-objfile COFF data.  */
2275
2276 static void
2277 coff_free_info (struct objfile *objfile, void *arg)
2278 {
2279   xfree (arg);
2280 }
2281
2282 void
2283 _initialize_coffread (void)
2284 {
2285   add_symtab_fns (&coff_sym_fns);
2286
2287   coff_objfile_data_key = register_objfile_data_with_cleanup (NULL,
2288                                                               coff_free_info);
2289
2290   coff_register_index
2291     = register_symbol_register_impl (LOC_REGISTER, &coff_register_funcs);
2292 }