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