More fixes for memory access errors triggered by attemps to examine corrupted binaries.
[external/binutils.git] / bfd / ecoff.c
1 /* Generic ECOFF (Extended-COFF) routines.
2    Copyright (C) 1990-2014 Free Software Foundation, Inc.
3    Original version by Per Bothner.
4    Full support added by Ian Lance Taylor, ian@cygnus.com.
5
6    This file is part of BFD, the Binary File Descriptor library.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
21    MA 02110-1301, USA.  */
22
23 #include "sysdep.h"
24 #include "bfd.h"
25 #include "bfdlink.h"
26 #include "libbfd.h"
27 #include "aout/ar.h"
28 #include "aout/stab_gnu.h"
29
30 /* FIXME: We need the definitions of N_SET[ADTB], but aout64.h defines
31    some other stuff which we don't want and which conflicts with stuff
32    we do want.  */
33 #include "libaout.h"
34 #include "aout/aout64.h"
35 #undef N_ABS
36 #undef exec_hdr
37 #undef obj_sym_filepos
38
39 #include "coff/internal.h"
40 #include "coff/sym.h"
41 #include "coff/symconst.h"
42 #include "coff/ecoff.h"
43 #include "libcoff.h"
44 #include "libecoff.h"
45 #include "libiberty.h"
46
47 #define streq(a, b)     (strcmp ((a), (b)) == 0)
48 #define strneq(a, b, n) (strncmp ((a), (b), (n)) == 0)
49
50 \f
51 /* This stuff is somewhat copied from coffcode.h.  */
52 static asection bfd_debug_section =
53 {
54   /* name,      id,  index, next, prev, flags, user_set_vma,       */
55      "*DEBUG*", 0,   0,     NULL, NULL, 0,     0,
56   /* linker_mark, linker_has_input, gc_mark, compress_status,      */
57      0,           0,                1,       0,
58   /* segment_mark, sec_info_type, use_rela_p,                      */
59      0,            0,             0,
60   /* sec_flg0, sec_flg1, sec_flg2, sec_flg3, sec_flg4, sec_flg5,   */
61      0,        0,        0,        0,        0,        0,
62   /* vma, lma, size, rawsize, compressed_size, relax, relax_count, */
63      0,   0,   0,    0,       0,               0,     0,
64   /* output_offset, output_section, alignment_power,               */
65      0,             NULL,           0,
66   /* relocation, orelocation, reloc_count, filepos, rel_filepos,   */
67      NULL,       NULL,        0,           0,       0,
68   /* line_filepos, userdata, contents, lineno, lineno_count,       */
69      0,            NULL,     NULL,     NULL,   0,
70   /* entsize, kept_section, moving_line_filepos,                   */
71      0,       NULL,         0,
72   /* target_index, used_by_bfd, constructor_chain, owner,          */
73      0,            NULL,        NULL,              NULL,
74   /* symbol,                                                       */
75      NULL,
76   /* symbol_ptr_ptr,                                               */
77      NULL,
78   /* map_head, map_tail                                            */
79      { NULL }, { NULL }
80 };
81
82 /* Create an ECOFF object.  */
83
84 bfd_boolean
85 _bfd_ecoff_mkobject (bfd *abfd)
86 {
87   bfd_size_type amt = sizeof (ecoff_data_type);
88
89   abfd->tdata.ecoff_obj_data = (struct ecoff_tdata *) bfd_zalloc (abfd, amt);
90   if (abfd->tdata.ecoff_obj_data == NULL)
91     return FALSE;
92
93   return TRUE;
94 }
95
96 /* This is a hook called by coff_real_object_p to create any backend
97    specific information.  */
98
99 void *
100 _bfd_ecoff_mkobject_hook (bfd *abfd, void * filehdr, void * aouthdr)
101 {
102   struct internal_filehdr *internal_f = (struct internal_filehdr *) filehdr;
103   struct internal_aouthdr *internal_a = (struct internal_aouthdr *) aouthdr;
104   ecoff_data_type *ecoff;
105
106   if (! _bfd_ecoff_mkobject (abfd))
107     return NULL;
108
109   ecoff = ecoff_data (abfd);
110   ecoff->gp_size = 8;
111   ecoff->sym_filepos = internal_f->f_symptr;
112
113   if (internal_a != NULL)
114     {
115       int i;
116
117       ecoff->text_start = internal_a->text_start;
118       ecoff->text_end = internal_a->text_start + internal_a->tsize;
119       ecoff->gp = internal_a->gp_value;
120       ecoff->gprmask = internal_a->gprmask;
121       for (i = 0; i < 4; i++)
122         ecoff->cprmask[i] = internal_a->cprmask[i];
123       ecoff->fprmask = internal_a->fprmask;
124       if (internal_a->magic == ECOFF_AOUT_ZMAGIC)
125         abfd->flags |= D_PAGED;
126       else
127         abfd->flags &=~ D_PAGED;
128     }
129
130   /* It turns out that no special action is required by the MIPS or
131      Alpha ECOFF backends.  They have different information in the
132      a.out header, but we just copy it all (e.g., gprmask, cprmask and
133      fprmask) and let the swapping routines ensure that only relevant
134      information is written out.  */
135
136   return (void *) ecoff;
137 }
138
139 /* Initialize a new section.  */
140
141 bfd_boolean
142 _bfd_ecoff_new_section_hook (bfd *abfd, asection *section)
143 {
144   unsigned int i;
145   static struct
146   {
147     const char * name;
148     flagword flags;
149   }
150   section_flags [] =
151   {
152     { _TEXT,   SEC_ALLOC | SEC_CODE | SEC_LOAD },
153     { _INIT,   SEC_ALLOC | SEC_CODE | SEC_LOAD },
154     { _FINI,   SEC_ALLOC | SEC_CODE | SEC_LOAD },
155     { _DATA,   SEC_ALLOC | SEC_DATA | SEC_LOAD },
156     { _SDATA,  SEC_ALLOC | SEC_DATA | SEC_LOAD },
157     { _RDATA,  SEC_ALLOC | SEC_DATA | SEC_LOAD | SEC_READONLY},
158     { _LIT8,   SEC_ALLOC | SEC_DATA | SEC_LOAD | SEC_READONLY},
159     { _LIT4,   SEC_ALLOC | SEC_DATA | SEC_LOAD | SEC_READONLY},
160     { _RCONST, SEC_ALLOC | SEC_DATA | SEC_LOAD | SEC_READONLY},
161     { _PDATA,  SEC_ALLOC | SEC_DATA | SEC_LOAD | SEC_READONLY},
162     { _BSS,    SEC_ALLOC},
163     { _SBSS,   SEC_ALLOC},
164     /* An Irix 4 shared libary.  */
165     { _LIB,    SEC_COFF_SHARED_LIBRARY}
166   };
167
168   section->alignment_power = 4;
169
170   for (i = 0; i < ARRAY_SIZE (section_flags); i++)
171     if (streq (section->name, section_flags[i].name))
172       {
173         section->flags |= section_flags[i].flags;
174         break;
175       }
176
177
178   /* Probably any other section name is SEC_NEVER_LOAD, but I'm
179      uncertain about .init on some systems and I don't know how shared
180      libraries work.  */
181
182   return _bfd_generic_new_section_hook (abfd, section);
183 }
184
185 /* Determine the machine architecture and type.  This is called from
186    the generic COFF routines.  It is the inverse of ecoff_get_magic,
187    below.  This could be an ECOFF backend routine, with one version
188    for each target, but there aren't all that many ECOFF targets.  */
189
190 bfd_boolean
191 _bfd_ecoff_set_arch_mach_hook (bfd *abfd, void * filehdr)
192 {
193   struct internal_filehdr *internal_f = (struct internal_filehdr *) filehdr;
194   enum bfd_architecture arch;
195   unsigned long mach;
196
197   switch (internal_f->f_magic)
198     {
199     case MIPS_MAGIC_1:
200     case MIPS_MAGIC_LITTLE:
201     case MIPS_MAGIC_BIG:
202       arch = bfd_arch_mips;
203       mach = bfd_mach_mips3000;
204       break;
205
206     case MIPS_MAGIC_LITTLE2:
207     case MIPS_MAGIC_BIG2:
208       /* MIPS ISA level 2: the r6000.  */
209       arch = bfd_arch_mips;
210       mach = bfd_mach_mips6000;
211       break;
212
213     case MIPS_MAGIC_LITTLE3:
214     case MIPS_MAGIC_BIG3:
215       /* MIPS ISA level 3: the r4000.  */
216       arch = bfd_arch_mips;
217       mach = bfd_mach_mips4000;
218       break;
219
220     case ALPHA_MAGIC:
221       arch = bfd_arch_alpha;
222       mach = 0;
223       break;
224
225     default:
226       arch = bfd_arch_obscure;
227       mach = 0;
228       break;
229     }
230
231   return bfd_default_set_arch_mach (abfd, arch, mach);
232 }
233
234 bfd_boolean
235 _bfd_ecoff_no_long_sections (bfd *abfd, int enable)
236 {
237   (void) abfd;
238   (void) enable;
239   return FALSE;
240 }
241
242 /* Get the magic number to use based on the architecture and machine.
243    This is the inverse of _bfd_ecoff_set_arch_mach_hook, above.  */
244
245 static int
246 ecoff_get_magic (bfd *abfd)
247 {
248   int big, little;
249
250   switch (bfd_get_arch (abfd))
251     {
252     case bfd_arch_mips:
253       switch (bfd_get_mach (abfd))
254         {
255         default:
256         case 0:
257         case bfd_mach_mips3000:
258           big = MIPS_MAGIC_BIG;
259           little = MIPS_MAGIC_LITTLE;
260           break;
261
262         case bfd_mach_mips6000:
263           big = MIPS_MAGIC_BIG2;
264           little = MIPS_MAGIC_LITTLE2;
265           break;
266
267         case bfd_mach_mips4000:
268           big = MIPS_MAGIC_BIG3;
269           little = MIPS_MAGIC_LITTLE3;
270           break;
271         }
272
273       return bfd_big_endian (abfd) ? big : little;
274
275     case bfd_arch_alpha:
276       return ALPHA_MAGIC;
277
278     default:
279       abort ();
280       return 0;
281     }
282 }
283
284 /* Get the section s_flags to use for a section.  */
285
286 static long
287 ecoff_sec_to_styp_flags (const char *name, flagword flags)
288 {
289   unsigned int i;
290   static struct
291   {
292     const char * name;
293     long flags;
294   }
295   styp_flags [] =
296   {
297     { _TEXT,    STYP_TEXT       },
298     { _DATA,    STYP_DATA       },
299     { _SDATA,   STYP_SDATA      },
300     { _RDATA,   STYP_RDATA      },
301     { _LITA,    STYP_LITA       },
302     { _LIT8,    STYP_LIT8       },
303     { _LIT4,    STYP_LIT4       },
304     { _BSS,     STYP_BSS        },
305     { _SBSS,    STYP_SBSS       },
306     { _INIT,    STYP_ECOFF_INIT },
307     { _FINI,    STYP_ECOFF_FINI },
308     { _PDATA,   STYP_PDATA      },
309     { _XDATA,   STYP_XDATA      },
310     { _LIB,     STYP_ECOFF_LIB  },
311     { _GOT,     STYP_GOT        },
312     { _HASH,    STYP_HASH       },
313     { _DYNAMIC, STYP_DYNAMIC    },
314     { _LIBLIST, STYP_LIBLIST    },
315     { _RELDYN,  STYP_RELDYN     },
316     { _CONFLIC, STYP_CONFLIC    },
317     { _DYNSTR,  STYP_DYNSTR     },
318     { _DYNSYM,  STYP_DYNSYM     },
319     { _RCONST,  STYP_RCONST     }
320   };
321   long styp = 0;
322
323   for (i = 0; i < ARRAY_SIZE (styp_flags); i++)
324     if (streq (name, styp_flags[i].name))
325       {
326         styp = styp_flags[i].flags;
327         break;
328       }
329
330   if (styp == 0)
331     {
332       if (streq (name, _COMMENT))
333         {
334           styp = STYP_COMMENT;
335           flags &=~ SEC_NEVER_LOAD;
336         }
337       else if (flags & SEC_CODE)
338         styp = STYP_TEXT;
339       else if (flags & SEC_DATA)
340         styp = STYP_DATA;
341       else if (flags & SEC_READONLY)
342         styp = STYP_RDATA;
343       else if (flags & SEC_LOAD)
344         styp = STYP_REG;
345       else
346         styp = STYP_BSS;
347     }
348
349   if (flags & SEC_NEVER_LOAD)
350     styp |= STYP_NOLOAD;
351
352   return styp;
353 }
354
355 /* Get the BFD flags to use for a section.  */
356
357 bfd_boolean
358 _bfd_ecoff_styp_to_sec_flags (bfd *abfd ATTRIBUTE_UNUSED,
359                               void * hdr,
360                               const char *name ATTRIBUTE_UNUSED,
361                               asection *section ATTRIBUTE_UNUSED,
362                               flagword * flags_ptr)
363 {
364   struct internal_scnhdr *internal_s = (struct internal_scnhdr *) hdr;
365   long styp_flags = internal_s->s_flags;
366   flagword sec_flags = 0;
367
368   if (styp_flags & STYP_NOLOAD)
369     sec_flags |= SEC_NEVER_LOAD;
370
371   /* For 386 COFF, at least, an unloadable text or data section is
372      actually a shared library section.  */
373   if ((styp_flags & STYP_TEXT)
374       || (styp_flags & STYP_ECOFF_INIT)
375       || (styp_flags & STYP_ECOFF_FINI)
376       || (styp_flags & STYP_DYNAMIC)
377       || (styp_flags & STYP_LIBLIST)
378       || (styp_flags & STYP_RELDYN)
379       || styp_flags == STYP_CONFLIC
380       || (styp_flags & STYP_DYNSTR)
381       || (styp_flags & STYP_DYNSYM)
382       || (styp_flags & STYP_HASH))
383     {
384       if (sec_flags & SEC_NEVER_LOAD)
385         sec_flags |= SEC_CODE | SEC_COFF_SHARED_LIBRARY;
386       else
387         sec_flags |= SEC_CODE | SEC_LOAD | SEC_ALLOC;
388     }
389   else if ((styp_flags & STYP_DATA)
390            || (styp_flags & STYP_RDATA)
391            || (styp_flags & STYP_SDATA)
392            || styp_flags == STYP_PDATA
393            || styp_flags == STYP_XDATA
394            || (styp_flags & STYP_GOT)
395            || styp_flags == STYP_RCONST)
396     {
397       if (sec_flags & SEC_NEVER_LOAD)
398         sec_flags |= SEC_DATA | SEC_COFF_SHARED_LIBRARY;
399       else
400         sec_flags |= SEC_DATA | SEC_LOAD | SEC_ALLOC;
401       if ((styp_flags & STYP_RDATA)
402           || styp_flags == STYP_PDATA
403           || styp_flags == STYP_RCONST)
404         sec_flags |= SEC_READONLY;
405     }
406   else if ((styp_flags & STYP_BSS)
407            || (styp_flags & STYP_SBSS))
408     sec_flags |= SEC_ALLOC;
409   else if ((styp_flags & STYP_INFO) || styp_flags == STYP_COMMENT)
410     sec_flags |= SEC_NEVER_LOAD;
411   else if ((styp_flags & STYP_LITA)
412            || (styp_flags & STYP_LIT8)
413            || (styp_flags & STYP_LIT4))
414     sec_flags |= SEC_DATA | SEC_LOAD | SEC_ALLOC | SEC_READONLY;
415   else if (styp_flags & STYP_ECOFF_LIB)
416     sec_flags |= SEC_COFF_SHARED_LIBRARY;
417   else
418     sec_flags |= SEC_ALLOC | SEC_LOAD;
419
420   * flags_ptr = sec_flags;
421   return TRUE;
422 }
423 \f
424 /* Read in the symbolic header for an ECOFF object file.  */
425
426 static bfd_boolean
427 ecoff_slurp_symbolic_header (bfd *abfd)
428 {
429   const struct ecoff_backend_data * const backend = ecoff_backend (abfd);
430   bfd_size_type external_hdr_size;
431   void * raw = NULL;
432   HDRR *internal_symhdr;
433
434   /* See if we've already read it in.  */
435   if (ecoff_data (abfd)->debug_info.symbolic_header.magic ==
436       backend->debug_swap.sym_magic)
437     return TRUE;
438
439   /* See whether there is a symbolic header.  */
440   if (ecoff_data (abfd)->sym_filepos == 0)
441     {
442       bfd_get_symcount (abfd) = 0;
443       return TRUE;
444     }
445
446   /* At this point bfd_get_symcount (abfd) holds the number of symbols
447      as read from the file header, but on ECOFF this is always the
448      size of the symbolic information header.  It would be cleaner to
449      handle this when we first read the file in coffgen.c.  */
450   external_hdr_size = backend->debug_swap.external_hdr_size;
451   if (bfd_get_symcount (abfd) != external_hdr_size)
452     {
453       bfd_set_error (bfd_error_bad_value);
454       return FALSE;
455     }
456
457   /* Read the symbolic information header.  */
458   raw = bfd_malloc (external_hdr_size);
459   if (raw == NULL)
460     goto error_return;
461
462   if (bfd_seek (abfd, ecoff_data (abfd)->sym_filepos, SEEK_SET) != 0
463       || bfd_bread (raw, external_hdr_size, abfd) != external_hdr_size)
464     goto error_return;
465   internal_symhdr = &ecoff_data (abfd)->debug_info.symbolic_header;
466   (*backend->debug_swap.swap_hdr_in) (abfd, raw, internal_symhdr);
467
468   if (internal_symhdr->magic != backend->debug_swap.sym_magic)
469     {
470       bfd_set_error (bfd_error_bad_value);
471       goto error_return;
472     }
473
474   /* Now we can get the correct number of symbols.  */
475   bfd_get_symcount (abfd) = (internal_symhdr->isymMax
476                              + internal_symhdr->iextMax);
477
478   if (raw != NULL)
479     free (raw);
480   return TRUE;
481  error_return:
482   if (raw != NULL)
483     free (raw);
484   return FALSE;
485 }
486
487 /* Read in and swap the important symbolic information for an ECOFF
488    object file.  This is called by gdb via the read_debug_info entry
489    point in the backend structure.  */
490
491 bfd_boolean
492 _bfd_ecoff_slurp_symbolic_info (bfd *abfd,
493                                 asection *ignore ATTRIBUTE_UNUSED,
494                                 struct ecoff_debug_info *debug)
495 {
496   const struct ecoff_backend_data * const backend = ecoff_backend (abfd);
497   HDRR *internal_symhdr;
498   bfd_size_type raw_base;
499   bfd_size_type raw_size;
500   void * raw;
501   bfd_size_type external_fdr_size;
502   char *fraw_src;
503   char *fraw_end;
504   struct fdr *fdr_ptr;
505   bfd_size_type raw_end;
506   bfd_size_type cb_end;
507   bfd_size_type amt;
508   file_ptr pos;
509
510   BFD_ASSERT (debug == &ecoff_data (abfd)->debug_info);
511
512   /* Check whether we've already gotten it, and whether there's any to
513      get.  */
514   if (ecoff_data (abfd)->raw_syments != NULL)
515     return TRUE;
516   if (ecoff_data (abfd)->sym_filepos == 0)
517     {
518       bfd_get_symcount (abfd) = 0;
519       return TRUE;
520     }
521
522   if (! ecoff_slurp_symbolic_header (abfd))
523     return FALSE;
524
525   internal_symhdr = &debug->symbolic_header;
526
527   /* Read all the symbolic information at once.  */
528   raw_base = (ecoff_data (abfd)->sym_filepos
529               + backend->debug_swap.external_hdr_size);
530
531   /* Alpha ecoff makes the determination of raw_size difficult. It has
532      an undocumented debug data section between the symhdr and the first
533      documented section. And the ordering of the sections varies between
534      statically and dynamically linked executables.
535      If bfd supports SEEK_END someday, this code could be simplified.  */
536   raw_end = 0;
537
538 #define UPDATE_RAW_END(start, count, size) \
539   cb_end = internal_symhdr->start + internal_symhdr->count * (size); \
540   if (cb_end > raw_end) \
541     raw_end = cb_end
542
543   UPDATE_RAW_END (cbLineOffset, cbLine, sizeof (unsigned char));
544   UPDATE_RAW_END (cbDnOffset, idnMax, backend->debug_swap.external_dnr_size);
545   UPDATE_RAW_END (cbPdOffset, ipdMax, backend->debug_swap.external_pdr_size);
546   UPDATE_RAW_END (cbSymOffset, isymMax, backend->debug_swap.external_sym_size);
547   /* eraxxon@alumni.rice.edu: ioptMax refers to the size of the
548      optimization symtab, not the number of entries.  */
549   UPDATE_RAW_END (cbOptOffset, ioptMax, sizeof (char));
550   UPDATE_RAW_END (cbAuxOffset, iauxMax, sizeof (union aux_ext));
551   UPDATE_RAW_END (cbSsOffset, issMax, sizeof (char));
552   UPDATE_RAW_END (cbSsExtOffset, issExtMax, sizeof (char));
553   UPDATE_RAW_END (cbFdOffset, ifdMax, backend->debug_swap.external_fdr_size);
554   UPDATE_RAW_END (cbRfdOffset, crfd, backend->debug_swap.external_rfd_size);
555   UPDATE_RAW_END (cbExtOffset, iextMax, backend->debug_swap.external_ext_size);
556
557 #undef UPDATE_RAW_END
558
559   raw_size = raw_end - raw_base;
560   if (raw_size == 0)
561     {
562       ecoff_data (abfd)->sym_filepos = 0;
563       return TRUE;
564     }
565   raw = bfd_alloc (abfd, raw_size);
566   if (raw == NULL)
567     return FALSE;
568
569   pos = ecoff_data (abfd)->sym_filepos;
570   pos += backend->debug_swap.external_hdr_size;
571   if (bfd_seek (abfd, pos, SEEK_SET) != 0
572       || bfd_bread (raw, raw_size, abfd) != raw_size)
573     {
574       bfd_release (abfd, raw);
575       return FALSE;
576     }
577
578   ecoff_data (abfd)->raw_syments = raw;
579
580   /* Get pointers for the numeric offsets in the HDRR structure.  */
581 #define FIX(off1, off2, type)                           \
582   if (internal_symhdr->off1 == 0)                       \
583     debug->off2 = NULL;                                 \
584   else                                                  \
585     debug->off2 = (type) ((char *) raw                  \
586                           + (internal_symhdr->off1      \
587                              - raw_base))
588
589   FIX (cbLineOffset, line, unsigned char *);
590   FIX (cbDnOffset, external_dnr, void *);
591   FIX (cbPdOffset, external_pdr, void *);
592   FIX (cbSymOffset, external_sym, void *);
593   FIX (cbOptOffset, external_opt, void *);
594   FIX (cbAuxOffset, external_aux, union aux_ext *);
595   FIX (cbSsOffset, ss, char *);
596   FIX (cbSsExtOffset, ssext, char *);
597   FIX (cbFdOffset, external_fdr, void *);
598   FIX (cbRfdOffset, external_rfd, void *);
599   FIX (cbExtOffset, external_ext, void *);
600 #undef FIX
601
602   /* I don't want to always swap all the data, because it will just
603      waste time and most programs will never look at it.  The only
604      time the linker needs most of the debugging information swapped
605      is when linking big-endian and little-endian MIPS object files
606      together, which is not a common occurrence.
607
608      We need to look at the fdr to deal with a lot of information in
609      the symbols, so we swap them here.  */
610   amt = internal_symhdr->ifdMax;
611   amt *= sizeof (struct fdr);
612   debug->fdr = (FDR *) bfd_alloc (abfd, amt);
613   if (debug->fdr == NULL)
614     return FALSE;
615   external_fdr_size = backend->debug_swap.external_fdr_size;
616   fdr_ptr = debug->fdr;
617   fraw_src = (char *) debug->external_fdr;
618   /* PR 17512: file: 3372-1243-0.004.  */
619   if (fraw_src == NULL && internal_symhdr->ifdMax > 0)
620     return FALSE;
621   fraw_end = fraw_src + internal_symhdr->ifdMax * external_fdr_size;
622   for (; fraw_src < fraw_end; fraw_src += external_fdr_size, fdr_ptr++)
623     (*backend->debug_swap.swap_fdr_in) (abfd, (void *) fraw_src, fdr_ptr);
624
625   return TRUE;
626 }
627 \f
628 /* ECOFF symbol table routines.  The ECOFF symbol table is described
629    in gcc/mips-tfile.c.  */
630
631 /* ECOFF uses two common sections.  One is the usual one, and the
632    other is for small objects.  All the small objects are kept
633    together, and then referenced via the gp pointer, which yields
634    faster assembler code.  This is what we use for the small common
635    section.  */
636 static asection ecoff_scom_section;
637 static asymbol ecoff_scom_symbol;
638 static asymbol *ecoff_scom_symbol_ptr;
639
640 /* Create an empty symbol.  */
641
642 asymbol *
643 _bfd_ecoff_make_empty_symbol (bfd *abfd)
644 {
645   ecoff_symbol_type *new_symbol;
646   bfd_size_type amt = sizeof (ecoff_symbol_type);
647
648   new_symbol = (ecoff_symbol_type *) bfd_zalloc (abfd, amt);
649   if (new_symbol == NULL)
650     return NULL;
651   new_symbol->symbol.section = NULL;
652   new_symbol->fdr = NULL;
653   new_symbol->local = FALSE;
654   new_symbol->native = NULL;
655   new_symbol->symbol.the_bfd = abfd;
656   return &new_symbol->symbol;
657 }
658
659 /* Set the BFD flags and section for an ECOFF symbol.  */
660
661 static bfd_boolean
662 ecoff_set_symbol_info (bfd *abfd,
663                        SYMR *ecoff_sym,
664                        asymbol *asym,
665                        int ext,
666                        int weak)
667 {
668   asym->the_bfd = abfd;
669   asym->value = ecoff_sym->value;
670   asym->section = &bfd_debug_section;
671   asym->udata.i = 0;
672
673   /* Most symbol types are just for debugging.  */
674   switch (ecoff_sym->st)
675     {
676     case stGlobal:
677     case stStatic:
678     case stLabel:
679     case stProc:
680     case stStaticProc:
681       break;
682     case stNil:
683       if (ECOFF_IS_STAB (ecoff_sym))
684         {
685           asym->flags = BSF_DEBUGGING;
686           return TRUE;
687         }
688       break;
689     default:
690       asym->flags = BSF_DEBUGGING;
691       return TRUE;
692     }
693
694   if (weak)
695     asym->flags = BSF_EXPORT | BSF_WEAK;
696   else if (ext)
697     asym->flags = BSF_EXPORT | BSF_GLOBAL;
698   else
699     {
700       asym->flags = BSF_LOCAL;
701       /* Normally, a local stProc symbol will have a corresponding
702          external symbol.  We mark the local symbol as a debugging
703          symbol, in order to prevent nm from printing both out.
704          Similarly, we mark stLabel and stabs symbols as debugging
705          symbols.  In both cases, we do want to set the value
706          correctly based on the symbol class.  */
707       if (ecoff_sym->st == stProc
708           || ecoff_sym->st == stLabel
709           || ECOFF_IS_STAB (ecoff_sym))
710         asym->flags |= BSF_DEBUGGING;
711     }
712
713   if (ecoff_sym->st == stProc || ecoff_sym->st == stStaticProc)
714     asym->flags |= BSF_FUNCTION;
715
716   switch (ecoff_sym->sc)
717     {
718     case scNil:
719       /* Used for compiler generated labels.  Leave them in the
720          debugging section, and mark them as local.  If BSF_DEBUGGING
721          is set, then nm does not display them for some reason.  If no
722          flags are set then the linker whines about them.  */
723       asym->flags = BSF_LOCAL;
724       break;
725     case scText:
726       asym->section = bfd_make_section_old_way (abfd, _TEXT);
727       asym->value -= asym->section->vma;
728       break;
729     case scData:
730       asym->section = bfd_make_section_old_way (abfd, _DATA);
731       asym->value -= asym->section->vma;
732       break;
733     case scBss:
734       asym->section = bfd_make_section_old_way (abfd, _BSS);
735       asym->value -= asym->section->vma;
736       break;
737     case scRegister:
738       asym->flags = BSF_DEBUGGING;
739       break;
740     case scAbs:
741       asym->section = bfd_abs_section_ptr;
742       break;
743     case scUndefined:
744       asym->section = bfd_und_section_ptr;
745       asym->flags = 0;
746       asym->value = 0;
747       break;
748     case scCdbLocal:
749     case scBits:
750     case scCdbSystem:
751     case scRegImage:
752     case scInfo:
753     case scUserStruct:
754       asym->flags = BSF_DEBUGGING;
755       break;
756     case scSData:
757       asym->section = bfd_make_section_old_way (abfd, ".sdata");
758       asym->value -= asym->section->vma;
759       break;
760     case scSBss:
761       asym->section = bfd_make_section_old_way (abfd, ".sbss");
762       asym->value -= asym->section->vma;
763       break;
764     case scRData:
765       asym->section = bfd_make_section_old_way (abfd, ".rdata");
766       asym->value -= asym->section->vma;
767       break;
768     case scVar:
769       asym->flags = BSF_DEBUGGING;
770       break;
771     case scCommon:
772       if (asym->value > ecoff_data (abfd)->gp_size)
773         {
774           asym->section = bfd_com_section_ptr;
775           asym->flags = 0;
776           break;
777         }
778       /* Fall through.  */
779     case scSCommon:
780       if (ecoff_scom_section.name == NULL)
781         {
782           /* Initialize the small common section.  */
783           ecoff_scom_section.name = SCOMMON;
784           ecoff_scom_section.flags = SEC_IS_COMMON;
785           ecoff_scom_section.output_section = &ecoff_scom_section;
786           ecoff_scom_section.symbol = &ecoff_scom_symbol;
787           ecoff_scom_section.symbol_ptr_ptr = &ecoff_scom_symbol_ptr;
788           ecoff_scom_symbol.name = SCOMMON;
789           ecoff_scom_symbol.flags = BSF_SECTION_SYM;
790           ecoff_scom_symbol.section = &ecoff_scom_section;
791           ecoff_scom_symbol_ptr = &ecoff_scom_symbol;
792         }
793       asym->section = &ecoff_scom_section;
794       asym->flags = 0;
795       break;
796     case scVarRegister:
797     case scVariant:
798       asym->flags = BSF_DEBUGGING;
799       break;
800     case scSUndefined:
801       asym->section = bfd_und_section_ptr;
802       asym->flags = 0;
803       asym->value = 0;
804       break;
805     case scInit:
806       asym->section = bfd_make_section_old_way (abfd, ".init");
807       asym->value -= asym->section->vma;
808       break;
809     case scBasedVar:
810     case scXData:
811     case scPData:
812       asym->flags = BSF_DEBUGGING;
813       break;
814     case scFini:
815       asym->section = bfd_make_section_old_way (abfd, ".fini");
816       asym->value -= asym->section->vma;
817       break;
818     case scRConst:
819       asym->section = bfd_make_section_old_way (abfd, ".rconst");
820       asym->value -= asym->section->vma;
821       break;
822     default:
823       break;
824     }
825
826   /* Look for special constructors symbols and make relocation entries
827      in a special construction section.  These are produced by the
828      -fgnu-linker argument to g++.  */
829   if (ECOFF_IS_STAB (ecoff_sym))
830     {
831       switch (ECOFF_UNMARK_STAB (ecoff_sym->index))
832         {
833         default:
834           break;
835
836         case N_SETA:
837         case N_SETT:
838         case N_SETD:
839         case N_SETB:
840           /* Mark the symbol as a constructor.  */
841           asym->flags |= BSF_CONSTRUCTOR;
842           break;
843         }
844     }
845   return TRUE;
846 }
847
848 /* Read an ECOFF symbol table.  */
849
850 bfd_boolean
851 _bfd_ecoff_slurp_symbol_table (bfd *abfd)
852 {
853   const struct ecoff_backend_data * const backend = ecoff_backend (abfd);
854   const bfd_size_type external_ext_size
855     = backend->debug_swap.external_ext_size;
856   const bfd_size_type external_sym_size
857     = backend->debug_swap.external_sym_size;
858   void (* const swap_ext_in) (bfd *, void *, EXTR *)
859     = backend->debug_swap.swap_ext_in;
860   void (* const swap_sym_in) (bfd *, void *, SYMR *)
861     = backend->debug_swap.swap_sym_in;
862   bfd_size_type internal_size;
863   ecoff_symbol_type *internal;
864   ecoff_symbol_type *internal_ptr;
865   char *eraw_src;
866   char *eraw_end;
867   FDR *fdr_ptr;
868   FDR *fdr_end;
869
870   /* If we've already read in the symbol table, do nothing.  */
871   if (ecoff_data (abfd)->canonical_symbols != NULL)
872     return TRUE;
873
874   /* Get the symbolic information.  */
875   if (! _bfd_ecoff_slurp_symbolic_info (abfd, NULL,
876                                         &ecoff_data (abfd)->debug_info))
877     return FALSE;
878   if (bfd_get_symcount (abfd) == 0)
879     return TRUE;
880
881   internal_size = bfd_get_symcount (abfd);
882   internal_size *= sizeof (ecoff_symbol_type);
883   internal = (ecoff_symbol_type *) bfd_alloc (abfd, internal_size);
884   if (internal == NULL)
885     return FALSE;
886
887   internal_ptr = internal;
888   eraw_src = (char *) ecoff_data (abfd)->debug_info.external_ext;
889   eraw_end = (eraw_src
890               + (ecoff_data (abfd)->debug_info.symbolic_header.iextMax
891                  * external_ext_size));
892   for (; eraw_src < eraw_end; eraw_src += external_ext_size, internal_ptr++)
893     {
894       EXTR internal_esym;
895
896       (*swap_ext_in) (abfd, (void *) eraw_src, &internal_esym);
897
898       /* PR 17512: file: 3372-1000-0.004.  */
899       if (internal_esym.asym.iss >= ecoff_data (abfd)->debug_info.symbolic_header.issExtMax)
900         return FALSE;
901
902       internal_ptr->symbol.name = (ecoff_data (abfd)->debug_info.ssext
903                                    + internal_esym.asym.iss);
904       if (!ecoff_set_symbol_info (abfd, &internal_esym.asym,
905                                   &internal_ptr->symbol, 1,
906                                   internal_esym.weakext))
907         return FALSE;
908       /* The alpha uses a negative ifd field for section symbols.  */
909       if (internal_esym.ifd >= 0)
910         internal_ptr->fdr = (ecoff_data (abfd)->debug_info.fdr
911                              + internal_esym.ifd);
912       else
913         internal_ptr->fdr = NULL;
914       internal_ptr->local = FALSE;
915       internal_ptr->native = (void *) eraw_src;
916     }
917
918   /* The local symbols must be accessed via the fdr's, because the
919      string and aux indices are relative to the fdr information.  */
920   fdr_ptr = ecoff_data (abfd)->debug_info.fdr;
921   fdr_end = fdr_ptr + ecoff_data (abfd)->debug_info.symbolic_header.ifdMax;
922   for (; fdr_ptr < fdr_end; fdr_ptr++)
923     {
924       char *lraw_src;
925       char *lraw_end;
926
927       lraw_src = ((char *) ecoff_data (abfd)->debug_info.external_sym
928                   + fdr_ptr->isymBase * external_sym_size);
929       lraw_end = lraw_src + fdr_ptr->csym * external_sym_size;
930       for (;
931            lraw_src < lraw_end;
932            lraw_src += external_sym_size, internal_ptr++)
933         {
934           SYMR internal_sym;
935
936           (*swap_sym_in) (abfd, (void *) lraw_src, &internal_sym);
937           internal_ptr->symbol.name = (ecoff_data (abfd)->debug_info.ss
938                                        + fdr_ptr->issBase
939                                        + internal_sym.iss);
940           if (!ecoff_set_symbol_info (abfd, &internal_sym,
941                                       &internal_ptr->symbol, 0, 0))
942             return FALSE;
943           internal_ptr->fdr = fdr_ptr;
944           internal_ptr->local = TRUE;
945           internal_ptr->native = (void *) lraw_src;
946         }
947     }
948
949   ecoff_data (abfd)->canonical_symbols = internal;
950
951   return TRUE;
952 }
953
954 /* Return the amount of space needed for the canonical symbols.  */
955
956 long
957 _bfd_ecoff_get_symtab_upper_bound (bfd *abfd)
958 {
959   if (! _bfd_ecoff_slurp_symbolic_info (abfd, NULL,
960                                         &ecoff_data (abfd)->debug_info))
961     return -1;
962
963   if (bfd_get_symcount (abfd) == 0)
964     return 0;
965
966   return (bfd_get_symcount (abfd) + 1) * (sizeof (ecoff_symbol_type *));
967 }
968
969 /* Get the canonical symbols.  */
970
971 long
972 _bfd_ecoff_canonicalize_symtab (bfd *abfd, asymbol **alocation)
973 {
974   unsigned int counter = 0;
975   ecoff_symbol_type *symbase;
976   ecoff_symbol_type **location = (ecoff_symbol_type **) alocation;
977
978   if (! _bfd_ecoff_slurp_symbol_table (abfd))
979     return -1;
980   if (bfd_get_symcount (abfd) == 0)
981     return 0;
982
983   symbase = ecoff_data (abfd)->canonical_symbols;
984   while (counter < bfd_get_symcount (abfd))
985     {
986       *(location++) = symbase++;
987       counter++;
988     }
989   *location++ = NULL;
990   return bfd_get_symcount (abfd);
991 }
992
993 /* Turn ECOFF type information into a printable string.
994    ecoff_emit_aggregate and ecoff_type_to_string are from
995    gcc/mips-tdump.c, with swapping added and used_ptr removed.  */
996
997 /* Write aggregate information to a string.  */
998
999 static void
1000 ecoff_emit_aggregate (bfd *abfd,
1001                       FDR *fdr,
1002                       char *string,
1003                       RNDXR *rndx,
1004                       long isym,
1005                       const char *which)
1006 {
1007   const struct ecoff_debug_swap * const debug_swap =
1008     &ecoff_backend (abfd)->debug_swap;
1009   struct ecoff_debug_info * const debug_info = &ecoff_data (abfd)->debug_info;
1010   unsigned int ifd = rndx->rfd;
1011   unsigned int indx = rndx->index;
1012   const char *name;
1013
1014   if (ifd == 0xfff)
1015     ifd = isym;
1016
1017   /* An ifd of -1 is an opaque type.  An escaped index of 0 is a
1018      struct return type of a procedure compiled without -g.  */
1019   if (ifd == 0xffffffff
1020       || (rndx->rfd == 0xfff && indx == 0))
1021     name = "<undefined>";
1022   else if (indx == indexNil)
1023     name = "<no name>";
1024   else
1025     {
1026       SYMR sym;
1027
1028       if (debug_info->external_rfd == NULL)
1029         fdr = debug_info->fdr + ifd;
1030       else
1031         {
1032           RFDT rfd;
1033
1034           (*debug_swap->swap_rfd_in) (abfd,
1035                                       ((char *) debug_info->external_rfd
1036                                        + ((fdr->rfdBase + ifd)
1037                                           * debug_swap->external_rfd_size)),
1038                                       &rfd);
1039           fdr = debug_info->fdr + rfd;
1040         }
1041
1042       indx += fdr->isymBase;
1043
1044       (*debug_swap->swap_sym_in) (abfd,
1045                                   ((char *) debug_info->external_sym
1046                                    + indx * debug_swap->external_sym_size),
1047                                   &sym);
1048
1049       name = debug_info->ss + fdr->issBase + sym.iss;
1050     }
1051
1052   sprintf (string,
1053            "%s %s { ifd = %u, index = %lu }",
1054            which, name, ifd,
1055            ((unsigned long) indx
1056             + debug_info->symbolic_header.iextMax));
1057 }
1058
1059 /* Convert the type information to string format.  */
1060
1061 static char *
1062 ecoff_type_to_string (bfd *abfd, FDR *fdr, unsigned int indx)
1063 {
1064   union aux_ext *aux_ptr;
1065   int bigendian;
1066   AUXU u;
1067   struct qual
1068   {
1069     unsigned int  type;
1070     int  low_bound;
1071     int  high_bound;
1072     int  stride;
1073   } qualifiers[7];
1074   unsigned int basic_type;
1075   int i;
1076   char buffer1[1024];
1077   static char buffer2[1024];
1078   char *p1 = buffer1;
1079   char *p2 = buffer2;
1080   RNDXR rndx;
1081
1082   aux_ptr = ecoff_data (abfd)->debug_info.external_aux + fdr->iauxBase;
1083   bigendian = fdr->fBigendian;
1084
1085   for (i = 0; i < 7; i++)
1086     {
1087       qualifiers[i].low_bound = 0;
1088       qualifiers[i].high_bound = 0;
1089       qualifiers[i].stride = 0;
1090     }
1091
1092   if (AUX_GET_ISYM (bigendian, &aux_ptr[indx]) == (bfd_vma) -1)
1093     return "-1 (no type)";
1094   _bfd_ecoff_swap_tir_in (bigendian, &aux_ptr[indx++].a_ti, &u.ti);
1095
1096   basic_type = u.ti.bt;
1097   qualifiers[0].type = u.ti.tq0;
1098   qualifiers[1].type = u.ti.tq1;
1099   qualifiers[2].type = u.ti.tq2;
1100   qualifiers[3].type = u.ti.tq3;
1101   qualifiers[4].type = u.ti.tq4;
1102   qualifiers[5].type = u.ti.tq5;
1103   qualifiers[6].type = tqNil;
1104
1105   /* Go get the basic type.  */
1106   switch (basic_type)
1107     {
1108     case btNil:                 /* Undefined.  */
1109       strcpy (p1, "nil");
1110       break;
1111
1112     case btAdr:                 /* Address - integer same size as pointer.  */
1113       strcpy (p1, "address");
1114       break;
1115
1116     case btChar:                /* Character.  */
1117       strcpy (p1, "char");
1118       break;
1119
1120     case btUChar:               /* Unsigned character.  */
1121       strcpy (p1, "unsigned char");
1122       break;
1123
1124     case btShort:               /* Short.  */
1125       strcpy (p1, "short");
1126       break;
1127
1128     case btUShort:              /* Unsigned short.  */
1129       strcpy (p1, "unsigned short");
1130       break;
1131
1132     case btInt:                 /* Int.  */
1133       strcpy (p1, "int");
1134       break;
1135
1136     case btUInt:                /* Unsigned int.  */
1137       strcpy (p1, "unsigned int");
1138       break;
1139
1140     case btLong:                /* Long.  */
1141       strcpy (p1, "long");
1142       break;
1143
1144     case btULong:               /* Unsigned long.  */
1145       strcpy (p1, "unsigned long");
1146       break;
1147
1148     case btFloat:               /* Float (real).  */
1149       strcpy (p1, "float");
1150       break;
1151
1152     case btDouble:              /* Double (real).  */
1153       strcpy (p1, "double");
1154       break;
1155
1156       /* Structures add 1-2 aux words:
1157          1st word is [ST_RFDESCAPE, offset] pointer to struct def;
1158          2nd word is file index if 1st word rfd is ST_RFDESCAPE.  */
1159
1160     case btStruct:              /* Structure (Record).  */
1161       _bfd_ecoff_swap_rndx_in (bigendian, &aux_ptr[indx].a_rndx, &rndx);
1162       ecoff_emit_aggregate (abfd, fdr, p1, &rndx,
1163                             (long) AUX_GET_ISYM (bigendian, &aux_ptr[indx+1]),
1164                             "struct");
1165       indx++;                   /* Skip aux words.  */
1166       break;
1167
1168       /* Unions add 1-2 aux words:
1169          1st word is [ST_RFDESCAPE, offset] pointer to union def;
1170          2nd word is file index if 1st word rfd is ST_RFDESCAPE.  */
1171
1172     case btUnion:               /* Union.  */
1173       _bfd_ecoff_swap_rndx_in (bigendian, &aux_ptr[indx].a_rndx, &rndx);
1174       ecoff_emit_aggregate (abfd, fdr, p1, &rndx,
1175                             (long) AUX_GET_ISYM (bigendian, &aux_ptr[indx+1]),
1176                             "union");
1177       indx++;                   /* Skip aux words.  */
1178       break;
1179
1180       /* Enumerations add 1-2 aux words:
1181          1st word is [ST_RFDESCAPE, offset] pointer to enum def;
1182          2nd word is file index if 1st word rfd is ST_RFDESCAPE.  */
1183
1184     case btEnum:                /* Enumeration.  */
1185       _bfd_ecoff_swap_rndx_in (bigendian, &aux_ptr[indx].a_rndx, &rndx);
1186       ecoff_emit_aggregate (abfd, fdr, p1, &rndx,
1187                             (long) AUX_GET_ISYM (bigendian, &aux_ptr[indx+1]),
1188                             "enum");
1189       indx++;                   /* Skip aux words.  */
1190       break;
1191
1192     case btTypedef:             /* Defined via a typedef, isymRef points.  */
1193       strcpy (p1, "typedef");
1194       break;
1195
1196     case btRange:               /* Subrange of int.  */
1197       strcpy (p1, "subrange");
1198       break;
1199
1200     case btSet:                 /* Pascal sets.  */
1201       strcpy (p1, "set");
1202       break;
1203
1204     case btComplex:             /* Fortran complex.  */
1205       strcpy (p1, "complex");
1206       break;
1207
1208     case btDComplex:            /* Fortran double complex.  */
1209       strcpy (p1, "double complex");
1210       break;
1211
1212     case btIndirect:            /* Forward or unnamed typedef.  */
1213       strcpy (p1, "forward/unamed typedef");
1214       break;
1215
1216     case btFixedDec:            /* Fixed Decimal.  */
1217       strcpy (p1, "fixed decimal");
1218       break;
1219
1220     case btFloatDec:            /* Float Decimal.  */
1221       strcpy (p1, "float decimal");
1222       break;
1223
1224     case btString:              /* Varying Length Character String.  */
1225       strcpy (p1, "string");
1226       break;
1227
1228     case btBit:                 /* Aligned Bit String.  */
1229       strcpy (p1, "bit");
1230       break;
1231
1232     case btPicture:             /* Picture.  */
1233       strcpy (p1, "picture");
1234       break;
1235
1236     case btVoid:                /* Void.  */
1237       strcpy (p1, "void");
1238       break;
1239
1240     default:
1241       sprintf (p1, _("Unknown basic type %d"), (int) basic_type);
1242       break;
1243     }
1244
1245   p1 += strlen (buffer1);
1246
1247   /* If this is a bitfield, get the bitsize.  */
1248   if (u.ti.fBitfield)
1249     {
1250       int bitsize;
1251
1252       bitsize = AUX_GET_WIDTH (bigendian, &aux_ptr[indx++]);
1253       sprintf (p1, " : %d", bitsize);
1254       p1 += strlen (buffer1);
1255     }
1256
1257   /* Deal with any qualifiers.  */
1258   if (qualifiers[0].type != tqNil)
1259     {
1260       /* Snarf up any array bounds in the correct order.  Arrays
1261          store 5 successive words in the aux. table:
1262                 word 0  RNDXR to type of the bounds (ie, int)
1263                 word 1  Current file descriptor index
1264                 word 2  low bound
1265                 word 3  high bound (or -1 if [])
1266                 word 4  stride size in bits.  */
1267       for (i = 0; i < 7; i++)
1268         {
1269           if (qualifiers[i].type == tqArray)
1270             {
1271               qualifiers[i].low_bound =
1272                 AUX_GET_DNLOW (bigendian, &aux_ptr[indx+2]);
1273               qualifiers[i].high_bound =
1274                 AUX_GET_DNHIGH (bigendian, &aux_ptr[indx+3]);
1275               qualifiers[i].stride =
1276                 AUX_GET_WIDTH (bigendian, &aux_ptr[indx+4]);
1277               indx += 5;
1278             }
1279         }
1280
1281       /* Now print out the qualifiers.  */
1282       for (i = 0; i < 6; i++)
1283         {
1284           switch (qualifiers[i].type)
1285             {
1286             case tqNil:
1287             case tqMax:
1288               break;
1289
1290             case tqPtr:
1291               strcpy (p2, "ptr to ");
1292               p2 += sizeof ("ptr to ")-1;
1293               break;
1294
1295             case tqVol:
1296               strcpy (p2, "volatile ");
1297               p2 += sizeof ("volatile ")-1;
1298               break;
1299
1300             case tqFar:
1301               strcpy (p2, "far ");
1302               p2 += sizeof ("far ")-1;
1303               break;
1304
1305             case tqProc:
1306               strcpy (p2, "func. ret. ");
1307               p2 += sizeof ("func. ret. ");
1308               break;
1309
1310             case tqArray:
1311               {
1312                 int first_array = i;
1313                 int j;
1314
1315                 /* Print array bounds reversed (ie, in the order the C
1316                    programmer writes them).  C is such a fun language....  */
1317                 while (i < 5 && qualifiers[i+1].type == tqArray)
1318                   i++;
1319
1320                 for (j = i; j >= first_array; j--)
1321                   {
1322                     strcpy (p2, "array [");
1323                     p2 += sizeof ("array [")-1;
1324                     if (qualifiers[j].low_bound != 0)
1325                       sprintf (p2,
1326                                "%ld:%ld {%ld bits}",
1327                                (long) qualifiers[j].low_bound,
1328                                (long) qualifiers[j].high_bound,
1329                                (long) qualifiers[j].stride);
1330
1331                     else if (qualifiers[j].high_bound != -1)
1332                       sprintf (p2,
1333                                "%ld {%ld bits}",
1334                                (long) (qualifiers[j].high_bound + 1),
1335                                (long) (qualifiers[j].stride));
1336
1337                     else
1338                       sprintf (p2, " {%ld bits}", (long) (qualifiers[j].stride));
1339
1340                     p2 += strlen (p2);
1341                     strcpy (p2, "] of ");
1342                     p2 += sizeof ("] of ")-1;
1343                   }
1344               }
1345               break;
1346             }
1347         }
1348     }
1349
1350   strcpy (p2, buffer1);
1351   return buffer2;
1352 }
1353
1354 /* Return information about ECOFF symbol SYMBOL in RET.  */
1355
1356 void
1357 _bfd_ecoff_get_symbol_info (bfd *abfd ATTRIBUTE_UNUSED,
1358                             asymbol *symbol,
1359                             symbol_info *ret)
1360 {
1361   bfd_symbol_info (symbol, ret);
1362 }
1363
1364 /* Return whether this is a local label.  */
1365
1366 bfd_boolean
1367 _bfd_ecoff_bfd_is_local_label_name (bfd *abfd ATTRIBUTE_UNUSED,
1368                                     const char *name)
1369 {
1370   return name[0] == '$';
1371 }
1372
1373 /* Print information about an ECOFF symbol.  */
1374
1375 void
1376 _bfd_ecoff_print_symbol (bfd *abfd,
1377                          void * filep,
1378                          asymbol *symbol,
1379                          bfd_print_symbol_type how)
1380 {
1381   const struct ecoff_debug_swap * const debug_swap
1382     = &ecoff_backend (abfd)->debug_swap;
1383   FILE *file = (FILE *)filep;
1384
1385   switch (how)
1386     {
1387     case bfd_print_symbol_name:
1388       fprintf (file, "%s", symbol->name);
1389       break;
1390     case bfd_print_symbol_more:
1391       if (ecoffsymbol (symbol)->local)
1392         {
1393           SYMR ecoff_sym;
1394
1395           (*debug_swap->swap_sym_in) (abfd, ecoffsymbol (symbol)->native,
1396                                       &ecoff_sym);
1397           fprintf (file, "ecoff local ");
1398           fprintf_vma (file, (bfd_vma) ecoff_sym.value);
1399           fprintf (file, " %x %x", (unsigned) ecoff_sym.st,
1400                    (unsigned) ecoff_sym.sc);
1401         }
1402       else
1403         {
1404           EXTR ecoff_ext;
1405
1406           (*debug_swap->swap_ext_in) (abfd, ecoffsymbol (symbol)->native,
1407                                       &ecoff_ext);
1408           fprintf (file, "ecoff extern ");
1409           fprintf_vma (file, (bfd_vma) ecoff_ext.asym.value);
1410           fprintf (file, " %x %x", (unsigned) ecoff_ext.asym.st,
1411                    (unsigned) ecoff_ext.asym.sc);
1412         }
1413       break;
1414     case bfd_print_symbol_all:
1415       /* Print out the symbols in a reasonable way.  */
1416       {
1417         char type;
1418         int pos;
1419         EXTR ecoff_ext;
1420         char jmptbl;
1421         char cobol_main;
1422         char weakext;
1423
1424         if (ecoffsymbol (symbol)->local)
1425           {
1426             (*debug_swap->swap_sym_in) (abfd, ecoffsymbol (symbol)->native,
1427                                         &ecoff_ext.asym);
1428             type = 'l';
1429             pos = ((((char *) ecoffsymbol (symbol)->native
1430                      - (char *) ecoff_data (abfd)->debug_info.external_sym)
1431                     / debug_swap->external_sym_size)
1432                    + ecoff_data (abfd)->debug_info.symbolic_header.iextMax);
1433             jmptbl = ' ';
1434             cobol_main = ' ';
1435             weakext = ' ';
1436           }
1437         else
1438           {
1439             (*debug_swap->swap_ext_in) (abfd, ecoffsymbol (symbol)->native,
1440                                         &ecoff_ext);
1441             type = 'e';
1442             pos = (((char *) ecoffsymbol (symbol)->native
1443                     - (char *) ecoff_data (abfd)->debug_info.external_ext)
1444                    / debug_swap->external_ext_size);
1445             jmptbl = ecoff_ext.jmptbl ? 'j' : ' ';
1446             cobol_main = ecoff_ext.cobol_main ? 'c' : ' ';
1447             weakext = ecoff_ext.weakext ? 'w' : ' ';
1448           }
1449
1450         fprintf (file, "[%3d] %c ",
1451                  pos, type);
1452         fprintf_vma (file, (bfd_vma) ecoff_ext.asym.value);
1453         fprintf (file, " st %x sc %x indx %x %c%c%c %s",
1454                  (unsigned) ecoff_ext.asym.st,
1455                  (unsigned) ecoff_ext.asym.sc,
1456                  (unsigned) ecoff_ext.asym.index,
1457                  jmptbl, cobol_main, weakext,
1458                  symbol->name);
1459
1460         if (ecoffsymbol (symbol)->fdr != NULL
1461             && ecoff_ext.asym.index != indexNil)
1462           {
1463             FDR *fdr;
1464             unsigned int indx;
1465             int bigendian;
1466             bfd_size_type sym_base;
1467             union aux_ext *aux_base;
1468
1469             fdr = ecoffsymbol (symbol)->fdr;
1470             indx = ecoff_ext.asym.index;
1471
1472             /* sym_base is used to map the fdr relative indices which
1473                appear in the file to the position number which we are
1474                using.  */
1475             sym_base = fdr->isymBase;
1476             if (ecoffsymbol (symbol)->local)
1477               sym_base +=
1478                 ecoff_data (abfd)->debug_info.symbolic_header.iextMax;
1479
1480             /* aux_base is the start of the aux entries for this file;
1481                asym.index is an offset from this.  */
1482             aux_base = (ecoff_data (abfd)->debug_info.external_aux
1483                         + fdr->iauxBase);
1484
1485             /* The aux entries are stored in host byte order; the
1486                order is indicated by a bit in the fdr.  */
1487             bigendian = fdr->fBigendian;
1488
1489             /* This switch is basically from gcc/mips-tdump.c.  */
1490             switch (ecoff_ext.asym.st)
1491               {
1492               case stNil:
1493               case stLabel:
1494                 break;
1495
1496               case stFile:
1497               case stBlock:
1498                 fprintf (file, _("\n      End+1 symbol: %ld"),
1499                          (long) (indx + sym_base));
1500                 break;
1501
1502               case stEnd:
1503                 if (ecoff_ext.asym.sc == scText
1504                     || ecoff_ext.asym.sc == scInfo)
1505                   fprintf (file, _("\n      First symbol: %ld"),
1506                            (long) (indx + sym_base));
1507                 else
1508                   fprintf (file, _("\n      First symbol: %ld"),
1509                            ((long)
1510                             (AUX_GET_ISYM (bigendian,
1511                                            &aux_base[ecoff_ext.asym.index])
1512                              + sym_base)));
1513                 break;
1514
1515               case stProc:
1516               case stStaticProc:
1517                 if (ECOFF_IS_STAB (&ecoff_ext.asym))
1518                   ;
1519                 else if (ecoffsymbol (symbol)->local)
1520                   fprintf (file, _("\n      End+1 symbol: %-7ld   Type:  %s"),
1521                            ((long)
1522                             (AUX_GET_ISYM (bigendian,
1523                                            &aux_base[ecoff_ext.asym.index])
1524                              + sym_base)),
1525                            ecoff_type_to_string (abfd, fdr, indx + 1));
1526                 else
1527                   fprintf (file, _("\n      Local symbol: %ld"),
1528                            ((long) indx
1529                             + (long) sym_base
1530                             + (ecoff_data (abfd)
1531                                ->debug_info.symbolic_header.iextMax)));
1532                 break;
1533
1534               case stStruct:
1535                 fprintf (file, _("\n      struct; End+1 symbol: %ld"),
1536                          (long) (indx + sym_base));
1537                 break;
1538
1539               case stUnion:
1540                 fprintf (file, _("\n      union; End+1 symbol: %ld"),
1541                          (long) (indx + sym_base));
1542                 break;
1543
1544               case stEnum:
1545                 fprintf (file, _("\n      enum; End+1 symbol: %ld"),
1546                          (long) (indx + sym_base));
1547                 break;
1548
1549               default:
1550                 if (! ECOFF_IS_STAB (&ecoff_ext.asym))
1551                   fprintf (file, _("\n      Type: %s"),
1552                            ecoff_type_to_string (abfd, fdr, indx));
1553                 break;
1554               }
1555           }
1556       }
1557       break;
1558     }
1559 }
1560 \f
1561 /* Read in the relocs for a section.  */
1562
1563 static bfd_boolean
1564 ecoff_slurp_reloc_table (bfd *abfd,
1565                          asection *section,
1566                          asymbol **symbols)
1567 {
1568   const struct ecoff_backend_data * const backend = ecoff_backend (abfd);
1569   arelent *internal_relocs;
1570   bfd_size_type external_reloc_size;
1571   bfd_size_type amt;
1572   char *external_relocs;
1573   arelent *rptr;
1574   unsigned int i;
1575
1576   if (section->relocation != NULL
1577       || section->reloc_count == 0
1578       || (section->flags & SEC_CONSTRUCTOR) != 0)
1579     return TRUE;
1580
1581   if (! _bfd_ecoff_slurp_symbol_table (abfd))
1582     return FALSE;
1583
1584   amt = section->reloc_count;
1585   amt *= sizeof (arelent);
1586   internal_relocs = (arelent *) bfd_alloc (abfd, amt);
1587
1588   external_reloc_size = backend->external_reloc_size;
1589   amt = external_reloc_size * section->reloc_count;
1590   external_relocs = (char *) bfd_alloc (abfd, amt);
1591   if (internal_relocs == NULL || external_relocs == NULL)
1592     return FALSE;
1593   if (bfd_seek (abfd, section->rel_filepos, SEEK_SET) != 0)
1594     return FALSE;
1595   if (bfd_bread (external_relocs, amt, abfd) != amt)
1596     return FALSE;
1597
1598   for (i = 0, rptr = internal_relocs; i < section->reloc_count; i++, rptr++)
1599     {
1600       struct internal_reloc intern;
1601
1602       (*backend->swap_reloc_in) (abfd,
1603                                  external_relocs + i * external_reloc_size,
1604                                  &intern);
1605
1606       if (intern.r_extern)
1607         {
1608           /* r_symndx is an index into the external symbols.  */
1609           BFD_ASSERT (intern.r_symndx >= 0
1610                       && (intern.r_symndx
1611                           < (ecoff_data (abfd)
1612                              ->debug_info.symbolic_header.iextMax)));
1613           rptr->sym_ptr_ptr = symbols + intern.r_symndx;
1614           rptr->addend = 0;
1615         }
1616       else if (intern.r_symndx == RELOC_SECTION_NONE
1617                || intern.r_symndx == RELOC_SECTION_ABS)
1618         {
1619           rptr->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
1620           rptr->addend = 0;
1621         }
1622       else
1623         {
1624           const char *sec_name;
1625           asection *sec;
1626
1627           /* r_symndx is a section key.  */
1628           switch (intern.r_symndx)
1629             {
1630             case RELOC_SECTION_TEXT:  sec_name = _TEXT;  break;
1631             case RELOC_SECTION_RDATA: sec_name = _RDATA; break;
1632             case RELOC_SECTION_DATA:  sec_name = _DATA;  break;
1633             case RELOC_SECTION_SDATA: sec_name = _SDATA; break;
1634             case RELOC_SECTION_SBSS:  sec_name = _SBSS;  break;
1635             case RELOC_SECTION_BSS:   sec_name = _BSS;   break;
1636             case RELOC_SECTION_INIT:  sec_name = _INIT;  break;
1637             case RELOC_SECTION_LIT8:  sec_name = _LIT8;  break;
1638             case RELOC_SECTION_LIT4:  sec_name = _LIT4;  break;
1639             case RELOC_SECTION_XDATA: sec_name = _XDATA; break;
1640             case RELOC_SECTION_PDATA: sec_name = _PDATA; break;
1641             case RELOC_SECTION_FINI:  sec_name = _FINI;  break;
1642             case RELOC_SECTION_LITA:  sec_name = _LITA;  break;
1643             case RELOC_SECTION_RCONST: sec_name = _RCONST; break;
1644             default: abort ();
1645             }
1646
1647           sec = bfd_get_section_by_name (abfd, sec_name);
1648           if (sec == NULL)
1649             abort ();
1650           rptr->sym_ptr_ptr = sec->symbol_ptr_ptr;
1651
1652           rptr->addend = - bfd_get_section_vma (abfd, sec);
1653         }
1654
1655       rptr->address = intern.r_vaddr - bfd_get_section_vma (abfd, section);
1656
1657       /* Let the backend select the howto field and do any other
1658          required processing.  */
1659       (*backend->adjust_reloc_in) (abfd, &intern, rptr);
1660     }
1661
1662   bfd_release (abfd, external_relocs);
1663
1664   section->relocation = internal_relocs;
1665
1666   return TRUE;
1667 }
1668
1669 /* Get a canonical list of relocs.  */
1670
1671 long
1672 _bfd_ecoff_canonicalize_reloc (bfd *abfd,
1673                                asection *section,
1674                                arelent **relptr,
1675                                asymbol **symbols)
1676 {
1677   unsigned int count;
1678
1679   if (section->flags & SEC_CONSTRUCTOR)
1680     {
1681       arelent_chain *chain;
1682
1683       /* This section has relocs made up by us, not the file, so take
1684          them out of their chain and place them into the data area
1685          provided.  */
1686       for (count = 0, chain = section->constructor_chain;
1687            count < section->reloc_count;
1688            count++, chain = chain->next)
1689         *relptr++ = &chain->relent;
1690     }
1691   else
1692     {
1693       arelent *tblptr;
1694
1695       if (! ecoff_slurp_reloc_table (abfd, section, symbols))
1696         return -1;
1697
1698       tblptr = section->relocation;
1699
1700       for (count = 0; count < section->reloc_count; count++)
1701         *relptr++ = tblptr++;
1702     }
1703
1704   *relptr = NULL;
1705
1706   return section->reloc_count;
1707 }
1708 \f
1709 /* Provided a BFD, a section and an offset into the section, calculate
1710    and return the name of the source file and the line nearest to the
1711    wanted location.  */
1712
1713 bfd_boolean
1714 _bfd_ecoff_find_nearest_line (bfd *abfd,
1715                               asymbol **symbols ATTRIBUTE_UNUSED,
1716                               asection *section,
1717                               bfd_vma offset,
1718                               const char **filename_ptr,
1719                               const char **functionname_ptr,
1720                               unsigned int *retline_ptr,
1721                               unsigned int *discriminator_ptr)
1722 {
1723   const struct ecoff_debug_swap * const debug_swap
1724     = &ecoff_backend (abfd)->debug_swap;
1725   struct ecoff_debug_info * const debug_info = &ecoff_data (abfd)->debug_info;
1726   struct ecoff_find_line *line_info;
1727
1728   /* Make sure we have the FDR's.  */
1729   if (! _bfd_ecoff_slurp_symbolic_info (abfd, NULL, debug_info)
1730       || bfd_get_symcount (abfd) == 0)
1731     return FALSE;
1732
1733   if (ecoff_data (abfd)->find_line_info == NULL)
1734     {
1735       bfd_size_type amt = sizeof (struct ecoff_find_line);
1736
1737       ecoff_data (abfd)->find_line_info =
1738           (struct ecoff_find_line *) bfd_zalloc (abfd, amt);
1739       if (ecoff_data (abfd)->find_line_info == NULL)
1740         return FALSE;
1741     }
1742
1743   if (discriminator_ptr)
1744     *discriminator_ptr = 0;
1745   line_info = ecoff_data (abfd)->find_line_info;
1746   return _bfd_ecoff_locate_line (abfd, section, offset, debug_info,
1747                                  debug_swap, line_info, filename_ptr,
1748                                  functionname_ptr, retline_ptr);
1749 }
1750 \f
1751 /* Copy private BFD data.  This is called by objcopy and strip.  We
1752    use it to copy the ECOFF debugging information from one BFD to the
1753    other.  It would be theoretically possible to represent the ECOFF
1754    debugging information in the symbol table.  However, it would be a
1755    lot of work, and there would be little gain (gas, gdb, and ld
1756    already access the ECOFF debugging information via the
1757    ecoff_debug_info structure, and that structure would have to be
1758    retained in order to support ECOFF debugging in MIPS ELF).
1759
1760    The debugging information for the ECOFF external symbols comes from
1761    the symbol table, so this function only handles the other debugging
1762    information.  */
1763
1764 bfd_boolean
1765 _bfd_ecoff_bfd_copy_private_bfd_data (bfd *ibfd, bfd *obfd)
1766 {
1767   struct ecoff_debug_info *iinfo = &ecoff_data (ibfd)->debug_info;
1768   struct ecoff_debug_info *oinfo = &ecoff_data (obfd)->debug_info;
1769   int i;
1770   asymbol **sym_ptr_ptr;
1771   size_t c;
1772   bfd_boolean local;
1773
1774   /* We only want to copy information over if both BFD's use ECOFF
1775      format.  */
1776   if (bfd_get_flavour (ibfd) != bfd_target_ecoff_flavour
1777       || bfd_get_flavour (obfd) != bfd_target_ecoff_flavour)
1778     return TRUE;
1779
1780   /* Copy the GP value and the register masks.  */
1781   ecoff_data (obfd)->gp = ecoff_data (ibfd)->gp;
1782   ecoff_data (obfd)->gprmask = ecoff_data (ibfd)->gprmask;
1783   ecoff_data (obfd)->fprmask = ecoff_data (ibfd)->fprmask;
1784   for (i = 0; i < 3; i++)
1785     ecoff_data (obfd)->cprmask[i] = ecoff_data (ibfd)->cprmask[i];
1786
1787   /* Copy the version stamp.  */
1788   oinfo->symbolic_header.vstamp = iinfo->symbolic_header.vstamp;
1789
1790   /* If there are no symbols, don't copy any debugging information.  */
1791   c = bfd_get_symcount (obfd);
1792   sym_ptr_ptr = bfd_get_outsymbols (obfd);
1793   if (c == 0 || sym_ptr_ptr == NULL)
1794     return TRUE;
1795
1796   /* See if there are any local symbols.  */
1797   local = FALSE;
1798   for (; c > 0; c--, sym_ptr_ptr++)
1799     {
1800       if (ecoffsymbol (*sym_ptr_ptr)->local)
1801         {
1802           local = TRUE;
1803           break;
1804         }
1805     }
1806
1807   if (local)
1808     {
1809       /* There are some local symbols.  We just bring over all the
1810          debugging information.  FIXME: This is not quite the right
1811          thing to do.  If the user has asked us to discard all
1812          debugging information, then we are probably going to wind up
1813          keeping it because there will probably be some local symbol
1814          which objcopy did not discard.  We should actually break
1815          apart the debugging information and only keep that which
1816          applies to the symbols we want to keep.  */
1817       oinfo->symbolic_header.ilineMax = iinfo->symbolic_header.ilineMax;
1818       oinfo->symbolic_header.cbLine = iinfo->symbolic_header.cbLine;
1819       oinfo->line = iinfo->line;
1820
1821       oinfo->symbolic_header.idnMax = iinfo->symbolic_header.idnMax;
1822       oinfo->external_dnr = iinfo->external_dnr;
1823
1824       oinfo->symbolic_header.ipdMax = iinfo->symbolic_header.ipdMax;
1825       oinfo->external_pdr = iinfo->external_pdr;
1826
1827       oinfo->symbolic_header.isymMax = iinfo->symbolic_header.isymMax;
1828       oinfo->external_sym = iinfo->external_sym;
1829
1830       oinfo->symbolic_header.ioptMax = iinfo->symbolic_header.ioptMax;
1831       oinfo->external_opt = iinfo->external_opt;
1832
1833       oinfo->symbolic_header.iauxMax = iinfo->symbolic_header.iauxMax;
1834       oinfo->external_aux = iinfo->external_aux;
1835
1836       oinfo->symbolic_header.issMax = iinfo->symbolic_header.issMax;
1837       oinfo->ss = iinfo->ss;
1838
1839       oinfo->symbolic_header.ifdMax = iinfo->symbolic_header.ifdMax;
1840       oinfo->external_fdr = iinfo->external_fdr;
1841
1842       oinfo->symbolic_header.crfd = iinfo->symbolic_header.crfd;
1843       oinfo->external_rfd = iinfo->external_rfd;
1844     }
1845   else
1846     {
1847       /* We are discarding all the local symbol information.  Look
1848          through the external symbols and remove all references to FDR
1849          or aux information.  */
1850       c = bfd_get_symcount (obfd);
1851       sym_ptr_ptr = bfd_get_outsymbols (obfd);
1852       for (; c > 0; c--, sym_ptr_ptr++)
1853         {
1854           EXTR esym;
1855
1856           (*(ecoff_backend (obfd)->debug_swap.swap_ext_in))
1857             (obfd, ecoffsymbol (*sym_ptr_ptr)->native, &esym);
1858           esym.ifd = ifdNil;
1859           esym.asym.index = indexNil;
1860           (*(ecoff_backend (obfd)->debug_swap.swap_ext_out))
1861             (obfd, &esym, ecoffsymbol (*sym_ptr_ptr)->native);
1862         }
1863     }
1864
1865   return TRUE;
1866 }
1867 \f
1868 /* Set the architecture.  The supported architecture is stored in the
1869    backend pointer.  We always set the architecture anyhow, since many
1870    callers ignore the return value.  */
1871
1872 bfd_boolean
1873 _bfd_ecoff_set_arch_mach (bfd *abfd,
1874                           enum bfd_architecture arch,
1875                           unsigned long machine)
1876 {
1877   bfd_default_set_arch_mach (abfd, arch, machine);
1878   return arch == ecoff_backend (abfd)->arch;
1879 }
1880
1881 /* Get the size of the section headers.  */
1882
1883 int
1884 _bfd_ecoff_sizeof_headers (bfd *abfd,
1885                            struct bfd_link_info *info ATTRIBUTE_UNUSED)
1886 {
1887   asection *current;
1888   int c;
1889   int ret;
1890
1891   c = 0;
1892   for (current = abfd->sections;
1893        current != NULL;
1894        current = current->next)
1895     ++c;
1896
1897   ret = (bfd_coff_filhsz (abfd)
1898          + bfd_coff_aoutsz (abfd)
1899          + c * bfd_coff_scnhsz (abfd));
1900   return (int) BFD_ALIGN (ret, 16);
1901 }
1902
1903 /* Get the contents of a section.  */
1904
1905 bfd_boolean
1906 _bfd_ecoff_get_section_contents (bfd *abfd,
1907                                  asection *section,
1908                                  void * location,
1909                                  file_ptr offset,
1910                                  bfd_size_type count)
1911 {
1912   return _bfd_generic_get_section_contents (abfd, section, location,
1913                                             offset, count);
1914 }
1915
1916 /* Sort sections by VMA, but put SEC_ALLOC sections first.  This is
1917    called via qsort.  */
1918
1919 static int
1920 ecoff_sort_hdrs (const void * arg1, const void * arg2)
1921 {
1922   const asection *hdr1 = *(const asection **) arg1;
1923   const asection *hdr2 = *(const asection **) arg2;
1924
1925   if ((hdr1->flags & SEC_ALLOC) != 0)
1926     {
1927       if ((hdr2->flags & SEC_ALLOC) == 0)
1928         return -1;
1929     }
1930   else
1931     {
1932       if ((hdr2->flags & SEC_ALLOC) != 0)
1933         return 1;
1934     }
1935   if (hdr1->vma < hdr2->vma)
1936     return -1;
1937   else if (hdr1->vma > hdr2->vma)
1938     return 1;
1939   else
1940     return 0;
1941 }
1942
1943 /* Calculate the file position for each section, and set
1944    reloc_filepos.  */
1945
1946 static bfd_boolean
1947 ecoff_compute_section_file_positions (bfd *abfd)
1948 {
1949   file_ptr sofar, file_sofar;
1950   asection **sorted_hdrs;
1951   asection *current;
1952   unsigned int i;
1953   file_ptr old_sofar;
1954   bfd_boolean rdata_in_text;
1955   bfd_boolean first_data, first_nonalloc;
1956   const bfd_vma round = ecoff_backend (abfd)->round;
1957   bfd_size_type amt;
1958
1959   sofar = _bfd_ecoff_sizeof_headers (abfd, NULL);
1960   file_sofar = sofar;
1961
1962   /* Sort the sections by VMA.  */
1963   amt = abfd->section_count;
1964   amt *= sizeof (asection *);
1965   sorted_hdrs = (asection **) bfd_malloc (amt);
1966   if (sorted_hdrs == NULL)
1967     return FALSE;
1968   for (current = abfd->sections, i = 0;
1969        current != NULL;
1970        current = current->next, i++)
1971     sorted_hdrs[i] = current;
1972   BFD_ASSERT (i == abfd->section_count);
1973
1974   qsort (sorted_hdrs, abfd->section_count, sizeof (asection *),
1975          ecoff_sort_hdrs);
1976
1977   /* Some versions of the OSF linker put the .rdata section in the
1978      text segment, and some do not.  */
1979   rdata_in_text = ecoff_backend (abfd)->rdata_in_text;
1980   if (rdata_in_text)
1981     {
1982       for (i = 0; i < abfd->section_count; i++)
1983         {
1984           current = sorted_hdrs[i];
1985           if (streq (current->name, _RDATA))
1986             break;
1987           if ((current->flags & SEC_CODE) == 0
1988               && ! streq (current->name, _PDATA)
1989               && ! streq (current->name, _RCONST))
1990             {
1991               rdata_in_text = FALSE;
1992               break;
1993             }
1994         }
1995     }
1996   ecoff_data (abfd)->rdata_in_text = rdata_in_text;
1997
1998   first_data = TRUE;
1999   first_nonalloc = TRUE;
2000   for (i = 0; i < abfd->section_count; i++)
2001     {
2002       unsigned int alignment_power;
2003
2004       current = sorted_hdrs[i];
2005
2006       /* For the Alpha ECOFF .pdata section the lnnoptr field is
2007          supposed to indicate the number of .pdata entries that are
2008          really in the section.  Each entry is 8 bytes.  We store this
2009          away in line_filepos before increasing the section size.  */
2010       if (streq (current->name, _PDATA))
2011         current->line_filepos = current->size / 8;
2012
2013       alignment_power = current->alignment_power;
2014
2015       /* On Ultrix, the data sections in an executable file must be
2016          aligned to a page boundary within the file.  This does not
2017          affect the section size, though.  FIXME: Does this work for
2018          other platforms?  It requires some modification for the
2019          Alpha, because .rdata on the Alpha goes with the text, not
2020          the data.  */
2021       if ((abfd->flags & EXEC_P) != 0
2022           && (abfd->flags & D_PAGED) != 0
2023           && ! first_data
2024           && (current->flags & SEC_CODE) == 0
2025           && (! rdata_in_text
2026               || ! streq (current->name, _RDATA))
2027           && ! streq (current->name, _PDATA)
2028           && ! streq (current->name, _RCONST))
2029         {
2030           sofar = (sofar + round - 1) &~ (round - 1);
2031           file_sofar = (file_sofar + round - 1) &~ (round - 1);
2032           first_data = FALSE;
2033         }
2034       else if (streq (current->name, _LIB))
2035         {
2036           /* On Irix 4, the location of contents of the .lib section
2037              from a shared library section is also rounded up to a
2038              page boundary.  */
2039
2040           sofar = (sofar + round - 1) &~ (round - 1);
2041           file_sofar = (file_sofar + round - 1) &~ (round - 1);
2042         }
2043       else if (first_nonalloc
2044                && (current->flags & SEC_ALLOC) == 0
2045                && (abfd->flags & D_PAGED) != 0)
2046         {
2047           /* Skip up to the next page for an unallocated section, such
2048              as the .comment section on the Alpha.  This leaves room
2049              for the .bss section.  */
2050           first_nonalloc = FALSE;
2051           sofar = (sofar + round - 1) &~ (round - 1);
2052           file_sofar = (file_sofar + round - 1) &~ (round - 1);
2053         }
2054
2055       /* Align the sections in the file to the same boundary on
2056          which they are aligned in virtual memory.  */
2057       sofar = BFD_ALIGN (sofar, 1 << alignment_power);
2058       if ((current->flags & SEC_HAS_CONTENTS) != 0)
2059         file_sofar = BFD_ALIGN (file_sofar, 1 << alignment_power);
2060
2061       if ((abfd->flags & D_PAGED) != 0
2062           && (current->flags & SEC_ALLOC) != 0)
2063         {
2064           sofar += (current->vma - sofar) % round;
2065           if ((current->flags & SEC_HAS_CONTENTS) != 0)
2066             file_sofar += (current->vma - file_sofar) % round;
2067         }
2068
2069       if ((current->flags & (SEC_HAS_CONTENTS | SEC_LOAD)) != 0)
2070         current->filepos = file_sofar;
2071
2072       sofar += current->size;
2073       if ((current->flags & SEC_HAS_CONTENTS) != 0)
2074         file_sofar += current->size;
2075
2076       /* Make sure that this section is of the right size too.  */
2077       old_sofar = sofar;
2078       sofar = BFD_ALIGN (sofar, 1 << alignment_power);
2079       if ((current->flags & SEC_HAS_CONTENTS) != 0)
2080         file_sofar = BFD_ALIGN (file_sofar, 1 << alignment_power);
2081       current->size += sofar - old_sofar;
2082     }
2083
2084   free (sorted_hdrs);
2085   sorted_hdrs = NULL;
2086
2087   ecoff_data (abfd)->reloc_filepos = file_sofar;
2088
2089   return TRUE;
2090 }
2091
2092 /* Determine the location of the relocs for all the sections in the
2093    output file, as well as the location of the symbolic debugging
2094    information.  */
2095
2096 static bfd_size_type
2097 ecoff_compute_reloc_file_positions (bfd *abfd)
2098 {
2099   const bfd_size_type external_reloc_size =
2100     ecoff_backend (abfd)->external_reloc_size;
2101   file_ptr reloc_base;
2102   bfd_size_type reloc_size;
2103   asection *current;
2104   file_ptr sym_base;
2105
2106   if (! abfd->output_has_begun)
2107     {
2108       if (! ecoff_compute_section_file_positions (abfd))
2109         abort ();
2110       abfd->output_has_begun = TRUE;
2111     }
2112
2113   reloc_base = ecoff_data (abfd)->reloc_filepos;
2114
2115   reloc_size = 0;
2116   for (current = abfd->sections;
2117        current != NULL;
2118        current = current->next)
2119     {
2120       if (current->reloc_count == 0)
2121         current->rel_filepos = 0;
2122       else
2123         {
2124           bfd_size_type relsize;
2125
2126           current->rel_filepos = reloc_base;
2127           relsize = current->reloc_count * external_reloc_size;
2128           reloc_size += relsize;
2129           reloc_base += relsize;
2130         }
2131     }
2132
2133   sym_base = ecoff_data (abfd)->reloc_filepos + reloc_size;
2134
2135   /* At least on Ultrix, the symbol table of an executable file must
2136      be aligned to a page boundary.  FIXME: Is this true on other
2137      platforms?  */
2138   if ((abfd->flags & EXEC_P) != 0
2139       && (abfd->flags & D_PAGED) != 0)
2140     sym_base = ((sym_base + ecoff_backend (abfd)->round - 1)
2141                 &~ (ecoff_backend (abfd)->round - 1));
2142
2143   ecoff_data (abfd)->sym_filepos = sym_base;
2144
2145   return reloc_size;
2146 }
2147
2148 /* Set the contents of a section.  */
2149
2150 bfd_boolean
2151 _bfd_ecoff_set_section_contents (bfd *abfd,
2152                                  asection *section,
2153                                  const void * location,
2154                                  file_ptr offset,
2155                                  bfd_size_type count)
2156 {
2157   file_ptr pos;
2158
2159   /* This must be done first, because bfd_set_section_contents is
2160      going to set output_has_begun to TRUE.  */
2161   if (! abfd->output_has_begun
2162       && ! ecoff_compute_section_file_positions (abfd))
2163     return FALSE;
2164
2165   /* Handle the .lib section specially so that Irix 4 shared libraries
2166      work out.  See coff_set_section_contents in coffcode.h.  */
2167   if (streq (section->name, _LIB))
2168     {
2169       bfd_byte *rec, *recend;
2170
2171       rec = (bfd_byte *) location;
2172       recend = rec + count;
2173       while (rec < recend)
2174         {
2175           ++section->lma;
2176           rec += bfd_get_32 (abfd, rec) * 4;
2177         }
2178
2179       BFD_ASSERT (rec == recend);
2180     }
2181
2182   if (count == 0)
2183     return TRUE;
2184
2185   pos = section->filepos + offset;
2186   if (bfd_seek (abfd, pos, SEEK_SET) != 0
2187       || bfd_bwrite (location, count, abfd) != count)
2188     return FALSE;
2189
2190   return TRUE;
2191 }
2192
2193 /* Get the GP value for an ECOFF file.  This is a hook used by
2194    nlmconv.  */
2195
2196 bfd_vma
2197 bfd_ecoff_get_gp_value (bfd *abfd)
2198 {
2199   if (bfd_get_flavour (abfd) != bfd_target_ecoff_flavour
2200       || bfd_get_format (abfd) != bfd_object)
2201     {
2202       bfd_set_error (bfd_error_invalid_operation);
2203       return 0;
2204     }
2205
2206   return ecoff_data (abfd)->gp;
2207 }
2208
2209 /* Set the GP value for an ECOFF file.  This is a hook used by the
2210    assembler.  */
2211
2212 bfd_boolean
2213 bfd_ecoff_set_gp_value (bfd *abfd, bfd_vma gp_value)
2214 {
2215   if (bfd_get_flavour (abfd) != bfd_target_ecoff_flavour
2216       || bfd_get_format (abfd) != bfd_object)
2217     {
2218       bfd_set_error (bfd_error_invalid_operation);
2219       return FALSE;
2220     }
2221
2222   ecoff_data (abfd)->gp = gp_value;
2223
2224   return TRUE;
2225 }
2226
2227 /* Set the register masks for an ECOFF file.  This is a hook used by
2228    the assembler.  */
2229
2230 bfd_boolean
2231 bfd_ecoff_set_regmasks (bfd *abfd,
2232                         unsigned long gprmask,
2233                         unsigned long fprmask,
2234                         unsigned long *cprmask)
2235 {
2236   ecoff_data_type *tdata;
2237
2238   if (bfd_get_flavour (abfd) != bfd_target_ecoff_flavour
2239       || bfd_get_format (abfd) != bfd_object)
2240     {
2241       bfd_set_error (bfd_error_invalid_operation);
2242       return FALSE;
2243     }
2244
2245   tdata = ecoff_data (abfd);
2246   tdata->gprmask = gprmask;
2247   tdata->fprmask = fprmask;
2248   if (cprmask != NULL)
2249     {
2250       int i;
2251
2252       for (i = 0; i < 3; i++)
2253         tdata->cprmask[i] = cprmask[i];
2254     }
2255
2256   return TRUE;
2257 }
2258
2259 /* Get ECOFF EXTR information for an external symbol.  This function
2260    is passed to bfd_ecoff_debug_externals.  */
2261
2262 static bfd_boolean
2263 ecoff_get_extr (asymbol *sym, EXTR *esym)
2264 {
2265   ecoff_symbol_type *ecoff_sym_ptr;
2266   bfd *input_bfd;
2267
2268   if (bfd_asymbol_flavour (sym) != bfd_target_ecoff_flavour
2269       || ecoffsymbol (sym)->native == NULL)
2270     {
2271       /* Don't include debugging, local, or section symbols.  */
2272       if ((sym->flags & BSF_DEBUGGING) != 0
2273           || (sym->flags & BSF_LOCAL) != 0
2274           || (sym->flags & BSF_SECTION_SYM) != 0)
2275         return FALSE;
2276
2277       esym->jmptbl = 0;
2278       esym->cobol_main = 0;
2279       esym->weakext = (sym->flags & BSF_WEAK) != 0;
2280       esym->reserved = 0;
2281       esym->ifd = ifdNil;
2282       /* FIXME: we can do better than this for st and sc.  */
2283       esym->asym.st = stGlobal;
2284       esym->asym.sc = scAbs;
2285       esym->asym.reserved = 0;
2286       esym->asym.index = indexNil;
2287       return TRUE;
2288     }
2289
2290   ecoff_sym_ptr = ecoffsymbol (sym);
2291
2292   if (ecoff_sym_ptr->local)
2293     return FALSE;
2294
2295   input_bfd = bfd_asymbol_bfd (sym);
2296   (*(ecoff_backend (input_bfd)->debug_swap.swap_ext_in))
2297     (input_bfd, ecoff_sym_ptr->native, esym);
2298
2299   /* If the symbol was defined by the linker, then esym will be
2300      undefined but sym will not be.  Get a better class for such a
2301      symbol.  */
2302   if ((esym->asym.sc == scUndefined
2303        || esym->asym.sc == scSUndefined)
2304       && ! bfd_is_und_section (bfd_get_section (sym)))
2305     esym->asym.sc = scAbs;
2306
2307   /* Adjust the FDR index for the symbol by that used for the input
2308      BFD.  */
2309   if (esym->ifd != -1)
2310     {
2311       struct ecoff_debug_info *input_debug;
2312
2313       input_debug = &ecoff_data (input_bfd)->debug_info;
2314       BFD_ASSERT (esym->ifd < input_debug->symbolic_header.ifdMax);
2315       if (input_debug->ifdmap != NULL)
2316         esym->ifd = input_debug->ifdmap[esym->ifd];
2317     }
2318
2319   return TRUE;
2320 }
2321
2322 /* Set the external symbol index.  This routine is passed to
2323    bfd_ecoff_debug_externals.  */
2324
2325 static void
2326 ecoff_set_index (asymbol *sym, bfd_size_type indx)
2327 {
2328   ecoff_set_sym_index (sym, indx);
2329 }
2330
2331 /* Write out an ECOFF file.  */
2332
2333 bfd_boolean
2334 _bfd_ecoff_write_object_contents (bfd *abfd)
2335 {
2336   const struct ecoff_backend_data * const backend = ecoff_backend (abfd);
2337   const bfd_vma round = backend->round;
2338   const bfd_size_type filhsz = bfd_coff_filhsz (abfd);
2339   const bfd_size_type aoutsz = bfd_coff_aoutsz (abfd);
2340   const bfd_size_type scnhsz = bfd_coff_scnhsz (abfd);
2341   const bfd_size_type external_hdr_size
2342     = backend->debug_swap.external_hdr_size;
2343   const bfd_size_type external_reloc_size = backend->external_reloc_size;
2344   void (* const adjust_reloc_out) (bfd *, const arelent *, struct internal_reloc *)
2345     = backend->adjust_reloc_out;
2346   void (* const swap_reloc_out) (bfd *, const struct internal_reloc *, void *)
2347     = backend->swap_reloc_out;
2348   struct ecoff_debug_info * const debug = &ecoff_data (abfd)->debug_info;
2349   HDRR * const symhdr = &debug->symbolic_header;
2350   asection *current;
2351   unsigned int count;
2352   bfd_size_type reloc_size;
2353   bfd_size_type text_size;
2354   bfd_vma text_start;
2355   bfd_boolean set_text_start;
2356   bfd_size_type data_size;
2357   bfd_vma data_start;
2358   bfd_boolean set_data_start;
2359   bfd_size_type bss_size;
2360   void * buff = NULL;
2361   void * reloc_buff = NULL;
2362   struct internal_filehdr internal_f;
2363   struct internal_aouthdr internal_a;
2364   int i;
2365
2366   /* Determine where the sections and relocs will go in the output
2367      file.  */
2368   reloc_size = ecoff_compute_reloc_file_positions (abfd);
2369
2370   count = 1;
2371   for (current = abfd->sections;
2372        current != NULL;
2373        current = current->next)
2374     {
2375       current->target_index = count;
2376       ++count;
2377     }
2378
2379   if ((abfd->flags & D_PAGED) != 0)
2380     text_size = _bfd_ecoff_sizeof_headers (abfd, NULL);
2381   else
2382     text_size = 0;
2383   text_start = 0;
2384   set_text_start = FALSE;
2385   data_size = 0;
2386   data_start = 0;
2387   set_data_start = FALSE;
2388   bss_size = 0;
2389
2390   /* Write section headers to the file.  */
2391
2392   /* Allocate buff big enough to hold a section header,
2393      file header, or a.out header.  */
2394   {
2395     bfd_size_type siz;
2396
2397     siz = scnhsz;
2398     if (siz < filhsz)
2399       siz = filhsz;
2400     if (siz < aoutsz)
2401       siz = aoutsz;
2402     buff = bfd_malloc (siz);
2403     if (buff == NULL)
2404       goto error_return;
2405   }
2406
2407   internal_f.f_nscns = 0;
2408   if (bfd_seek (abfd, (file_ptr) (filhsz + aoutsz), SEEK_SET) != 0)
2409     goto error_return;
2410
2411   for (current = abfd->sections;
2412        current != NULL;
2413        current = current->next)
2414     {
2415       struct internal_scnhdr section;
2416       bfd_vma vma;
2417
2418       ++internal_f.f_nscns;
2419
2420       strncpy (section.s_name, current->name, sizeof section.s_name);
2421
2422       /* This seems to be correct for Irix 4 shared libraries.  */
2423       vma = bfd_get_section_vma (abfd, current);
2424       if (streq (current->name, _LIB))
2425         section.s_vaddr = 0;
2426       else
2427         section.s_vaddr = vma;
2428
2429       section.s_paddr = current->lma;
2430       section.s_size = current->size;
2431
2432       /* If this section is unloadable then the scnptr will be 0.  */
2433       if ((current->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
2434         section.s_scnptr = 0;
2435       else
2436         section.s_scnptr = current->filepos;
2437       section.s_relptr = current->rel_filepos;
2438
2439       /* FIXME: the lnnoptr of the .sbss or .sdata section of an
2440          object file produced by the assembler is supposed to point to
2441          information about how much room is required by objects of
2442          various different sizes.  I think this only matters if we
2443          want the linker to compute the best size to use, or
2444          something.  I don't know what happens if the information is
2445          not present.  */
2446       if (! streq (current->name, _PDATA))
2447         section.s_lnnoptr = 0;
2448       else
2449         {
2450           /* The Alpha ECOFF .pdata section uses the lnnoptr field to
2451              hold the number of entries in the section (each entry is
2452              8 bytes).  We stored this in the line_filepos field in
2453              ecoff_compute_section_file_positions.  */
2454           section.s_lnnoptr = current->line_filepos;
2455         }
2456
2457       section.s_nreloc = current->reloc_count;
2458       section.s_nlnno = 0;
2459       section.s_flags = ecoff_sec_to_styp_flags (current->name,
2460                                                  current->flags);
2461
2462       if (bfd_coff_swap_scnhdr_out (abfd, (void *) &section, buff) == 0
2463           || bfd_bwrite (buff, scnhsz, abfd) != scnhsz)
2464         goto error_return;
2465
2466       if ((section.s_flags & STYP_TEXT) != 0
2467           || ((section.s_flags & STYP_RDATA) != 0
2468               && ecoff_data (abfd)->rdata_in_text)
2469           || section.s_flags == STYP_PDATA
2470           || (section.s_flags & STYP_DYNAMIC) != 0
2471           || (section.s_flags & STYP_LIBLIST) != 0
2472           || (section.s_flags & STYP_RELDYN) != 0
2473           || section.s_flags == STYP_CONFLIC
2474           || (section.s_flags & STYP_DYNSTR) != 0
2475           || (section.s_flags & STYP_DYNSYM) != 0
2476           || (section.s_flags & STYP_HASH) != 0
2477           || (section.s_flags & STYP_ECOFF_INIT) != 0
2478           || (section.s_flags & STYP_ECOFF_FINI) != 0
2479           || section.s_flags == STYP_RCONST)
2480         {
2481           text_size += current->size;
2482           if (! set_text_start || text_start > vma)
2483             {
2484               text_start = vma;
2485               set_text_start = TRUE;
2486             }
2487         }
2488       else if ((section.s_flags & STYP_RDATA) != 0
2489                || (section.s_flags & STYP_DATA) != 0
2490                || (section.s_flags & STYP_LITA) != 0
2491                || (section.s_flags & STYP_LIT8) != 0
2492                || (section.s_flags & STYP_LIT4) != 0
2493                || (section.s_flags & STYP_SDATA) != 0
2494                || section.s_flags == STYP_XDATA
2495                || (section.s_flags & STYP_GOT) != 0)
2496         {
2497           data_size += current->size;
2498           if (! set_data_start || data_start > vma)
2499             {
2500               data_start = vma;
2501               set_data_start = TRUE;
2502             }
2503         }
2504       else if ((section.s_flags & STYP_BSS) != 0
2505                || (section.s_flags & STYP_SBSS) != 0)
2506         bss_size += current->size;
2507       else if (section.s_flags == 0
2508                || (section.s_flags & STYP_ECOFF_LIB) != 0
2509                || section.s_flags == STYP_COMMENT)
2510         /* Do nothing.  */ ;
2511       else
2512         abort ();
2513     }
2514
2515   /* Set up the file header.  */
2516   internal_f.f_magic = ecoff_get_magic (abfd);
2517
2518   /* We will NOT put a fucking timestamp in the header here. Every
2519      time you put it back, I will come in and take it out again.  I'm
2520      sorry.  This field does not belong here.  We fill it with a 0 so
2521      it compares the same but is not a reasonable time. --
2522      gnu@cygnus.com.  */
2523   internal_f.f_timdat = 0;
2524
2525   if (bfd_get_symcount (abfd) != 0)
2526     {
2527       /* The ECOFF f_nsyms field is not actually the number of
2528          symbols, it's the size of symbolic information header.  */
2529       internal_f.f_nsyms = external_hdr_size;
2530       internal_f.f_symptr = ecoff_data (abfd)->sym_filepos;
2531     }
2532   else
2533     {
2534       internal_f.f_nsyms = 0;
2535       internal_f.f_symptr = 0;
2536     }
2537
2538   internal_f.f_opthdr = aoutsz;
2539
2540   internal_f.f_flags = F_LNNO;
2541   if (reloc_size == 0)
2542     internal_f.f_flags |= F_RELFLG;
2543   if (bfd_get_symcount (abfd) == 0)
2544     internal_f.f_flags |= F_LSYMS;
2545   if (abfd->flags & EXEC_P)
2546     internal_f.f_flags |= F_EXEC;
2547
2548   if (bfd_little_endian (abfd))
2549     internal_f.f_flags |= F_AR32WR;
2550   else
2551     internal_f.f_flags |= F_AR32W;
2552
2553   /* Set up the ``optional'' header.  */
2554   if ((abfd->flags & D_PAGED) != 0)
2555     internal_a.magic = ECOFF_AOUT_ZMAGIC;
2556   else
2557     internal_a.magic = ECOFF_AOUT_OMAGIC;
2558
2559   /* FIXME: Is this really correct?  */
2560   internal_a.vstamp = symhdr->vstamp;
2561
2562   /* At least on Ultrix, these have to be rounded to page boundaries.
2563      FIXME: Is this true on other platforms?  */
2564   if ((abfd->flags & D_PAGED) != 0)
2565     {
2566       internal_a.tsize = (text_size + round - 1) &~ (round - 1);
2567       internal_a.text_start = text_start &~ (round - 1);
2568       internal_a.dsize = (data_size + round - 1) &~ (round - 1);
2569       internal_a.data_start = data_start &~ (round - 1);
2570     }
2571   else
2572     {
2573       internal_a.tsize = text_size;
2574       internal_a.text_start = text_start;
2575       internal_a.dsize = data_size;
2576       internal_a.data_start = data_start;
2577     }
2578
2579   /* On Ultrix, the initial portions of the .sbss and .bss segments
2580      are at the end of the data section.  The bsize field in the
2581      optional header records how many bss bytes are required beyond
2582      those in the data section.  The value is not rounded to a page
2583      boundary.  */
2584   if (bss_size < internal_a.dsize - data_size)
2585     bss_size = 0;
2586   else
2587     bss_size -= internal_a.dsize - data_size;
2588   internal_a.bsize = bss_size;
2589   internal_a.bss_start = internal_a.data_start + internal_a.dsize;
2590
2591   internal_a.entry = bfd_get_start_address (abfd);
2592
2593   internal_a.gp_value = ecoff_data (abfd)->gp;
2594
2595   internal_a.gprmask = ecoff_data (abfd)->gprmask;
2596   internal_a.fprmask = ecoff_data (abfd)->fprmask;
2597   for (i = 0; i < 4; i++)
2598     internal_a.cprmask[i] = ecoff_data (abfd)->cprmask[i];
2599
2600   /* Let the backend adjust the headers if necessary.  */
2601   if (backend->adjust_headers)
2602     {
2603       if (! (*backend->adjust_headers) (abfd, &internal_f, &internal_a))
2604         goto error_return;
2605     }
2606
2607   /* Write out the file header and the optional header.  */
2608   if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0)
2609     goto error_return;
2610
2611   bfd_coff_swap_filehdr_out (abfd, (void *) &internal_f, buff);
2612   if (bfd_bwrite (buff, filhsz, abfd) != filhsz)
2613     goto error_return;
2614
2615   bfd_coff_swap_aouthdr_out (abfd, (void *) &internal_a, buff);
2616   if (bfd_bwrite (buff, aoutsz, abfd) != aoutsz)
2617     goto error_return;
2618
2619   /* Build the external symbol information.  This must be done before
2620      writing out the relocs so that we know the symbol indices.  We
2621      don't do this if this BFD was created by the backend linker,
2622      since it will have already handled the symbols and relocs.  */
2623   if (! ecoff_data (abfd)->linker)
2624     {
2625       symhdr->iextMax = 0;
2626       symhdr->issExtMax = 0;
2627       debug->external_ext = debug->external_ext_end = NULL;
2628       debug->ssext = debug->ssext_end = NULL;
2629       if (! bfd_ecoff_debug_externals (abfd, debug, &backend->debug_swap,
2630                                        (abfd->flags & EXEC_P) == 0,
2631                                        ecoff_get_extr, ecoff_set_index))
2632         goto error_return;
2633
2634       /* Write out the relocs.  */
2635       for (current = abfd->sections;
2636            current != NULL;
2637            current = current->next)
2638         {
2639           arelent **reloc_ptr_ptr;
2640           arelent **reloc_end;
2641           char *out_ptr;
2642           bfd_size_type amt;
2643
2644           if (current->reloc_count == 0)
2645             continue;
2646
2647           amt = current->reloc_count * external_reloc_size;
2648           reloc_buff = bfd_alloc (abfd, amt);
2649           if (reloc_buff == NULL)
2650             goto error_return;
2651
2652           reloc_ptr_ptr = current->orelocation;
2653           reloc_end = reloc_ptr_ptr + current->reloc_count;
2654           out_ptr = (char *) reloc_buff;
2655
2656           for (;
2657                reloc_ptr_ptr < reloc_end;
2658                reloc_ptr_ptr++, out_ptr += external_reloc_size)
2659             {
2660               arelent *reloc;
2661               asymbol *sym;
2662               struct internal_reloc in;
2663
2664               memset ((void *) &in, 0, sizeof in);
2665
2666               reloc = *reloc_ptr_ptr;
2667               sym = *reloc->sym_ptr_ptr;
2668
2669               /* If the howto field has not been initialised then skip this reloc.
2670                  This assumes that an error message has been issued elsewhere.  */
2671               if (reloc->howto == NULL)
2672                 continue;
2673
2674               in.r_vaddr = (reloc->address
2675                             + bfd_get_section_vma (abfd, current));
2676               in.r_type = reloc->howto->type;
2677
2678               if ((sym->flags & BSF_SECTION_SYM) == 0)
2679                 {
2680                   in.r_symndx = ecoff_get_sym_index (*reloc->sym_ptr_ptr);
2681                   in.r_extern = 1;
2682                 }
2683               else
2684                 {
2685                   const char *name;
2686                   unsigned int j;
2687                   static struct
2688                   {
2689                     const char * name;
2690                     long r_symndx;
2691                   }
2692                   section_symndx [] =
2693                   {
2694                     { _TEXT,   RELOC_SECTION_TEXT   },
2695                     { _RDATA,  RELOC_SECTION_RDATA  },
2696                     { _DATA,   RELOC_SECTION_DATA   },
2697                     { _SDATA,  RELOC_SECTION_SDATA  },
2698                     { _SBSS,   RELOC_SECTION_SBSS   },
2699                     { _BSS,    RELOC_SECTION_BSS    },
2700                     { _INIT,   RELOC_SECTION_INIT   },
2701                     { _LIT8,   RELOC_SECTION_LIT8   },
2702                     { _LIT4,   RELOC_SECTION_LIT4   },
2703                     { _XDATA,  RELOC_SECTION_XDATA  },
2704                     { _PDATA,  RELOC_SECTION_PDATA  },
2705                     { _FINI,   RELOC_SECTION_FINI   },
2706                     { _LITA,   RELOC_SECTION_LITA   },
2707                     { "*ABS*", RELOC_SECTION_ABS    },
2708                     { _RCONST, RELOC_SECTION_RCONST }
2709                   };
2710
2711                   name = bfd_get_section_name (abfd, bfd_get_section (sym));
2712
2713                   for (j = 0; j < ARRAY_SIZE (section_symndx); j++)
2714                     if (streq (name, section_symndx[j].name))
2715                       {
2716                         in.r_symndx = section_symndx[j].r_symndx;
2717                         break;
2718                       }
2719
2720                   if (j == ARRAY_SIZE (section_symndx))
2721                     abort ();
2722                   in.r_extern = 0;
2723                 }
2724
2725               (*adjust_reloc_out) (abfd, reloc, &in);
2726
2727               (*swap_reloc_out) (abfd, &in, (void *) out_ptr);
2728             }
2729
2730           if (bfd_seek (abfd, current->rel_filepos, SEEK_SET) != 0)
2731             goto error_return;
2732           amt = current->reloc_count * external_reloc_size;
2733           if (bfd_bwrite (reloc_buff, amt, abfd) != amt)
2734             goto error_return;
2735           bfd_release (abfd, reloc_buff);
2736           reloc_buff = NULL;
2737         }
2738
2739       /* Write out the symbolic debugging information.  */
2740       if (bfd_get_symcount (abfd) > 0)
2741         {
2742           /* Write out the debugging information.  */
2743           if (! bfd_ecoff_write_debug (abfd, debug, &backend->debug_swap,
2744                                        ecoff_data (abfd)->sym_filepos))
2745             goto error_return;
2746         }
2747     }
2748
2749   /* The .bss section of a demand paged executable must receive an
2750      entire page.  If there are symbols, the symbols will start on the
2751      next page.  If there are no symbols, we must fill out the page by
2752      hand.  */
2753   if (bfd_get_symcount (abfd) == 0
2754       && (abfd->flags & EXEC_P) != 0
2755       && (abfd->flags & D_PAGED) != 0)
2756     {
2757       char c;
2758
2759       if (bfd_seek (abfd, (file_ptr) ecoff_data (abfd)->sym_filepos - 1,
2760                     SEEK_SET) != 0)
2761         goto error_return;
2762       if (bfd_bread (&c, (bfd_size_type) 1, abfd) == 0)
2763         c = 0;
2764       if (bfd_seek (abfd, (file_ptr) ecoff_data (abfd)->sym_filepos - 1,
2765                     SEEK_SET) != 0)
2766         goto error_return;
2767       if (bfd_bwrite (&c, (bfd_size_type) 1, abfd) != 1)
2768         goto error_return;
2769     }
2770
2771   if (reloc_buff != NULL)
2772     bfd_release (abfd, reloc_buff);
2773   if (buff != NULL)
2774     free (buff);
2775   return TRUE;
2776  error_return:
2777   if (reloc_buff != NULL)
2778     bfd_release (abfd, reloc_buff);
2779   if (buff != NULL)
2780     free (buff);
2781   return FALSE;
2782 }
2783 \f
2784 /* Archive handling.  ECOFF uses what appears to be a unique type of
2785    archive header (armap).  The byte ordering of the armap and the
2786    contents are encoded in the name of the armap itself.  At least for
2787    now, we only support archives with the same byte ordering in the
2788    armap and the contents.
2789
2790    The first four bytes in the armap are the number of symbol
2791    definitions.  This is always a power of two.
2792
2793    This is followed by the symbol definitions.  Each symbol definition
2794    occupies 8 bytes.  The first four bytes are the offset from the
2795    start of the armap strings to the null-terminated string naming
2796    this symbol.  The second four bytes are the file offset to the
2797    archive member which defines this symbol.  If the second four bytes
2798    are 0, then this is not actually a symbol definition, and it should
2799    be ignored.
2800
2801    The symbols are hashed into the armap with a closed hashing scheme.
2802    See the functions below for the details of the algorithm.
2803
2804    After the symbol definitions comes four bytes holding the size of
2805    the string table, followed by the string table itself.  */
2806
2807 /* The name of an archive headers looks like this:
2808    __________E[BL]E[BL]_ (with a trailing space).
2809    The trailing space is changed to an X if the archive is changed to
2810    indicate that the armap is out of date.
2811
2812    The Alpha seems to use ________64E[BL]E[BL]_.  */
2813
2814 #define ARMAP_BIG_ENDIAN                'B'
2815 #define ARMAP_LITTLE_ENDIAN             'L'
2816 #define ARMAP_MARKER                    'E'
2817 #define ARMAP_START_LENGTH              10
2818 #define ARMAP_HEADER_MARKER_INDEX       10
2819 #define ARMAP_HEADER_ENDIAN_INDEX       11
2820 #define ARMAP_OBJECT_MARKER_INDEX       12
2821 #define ARMAP_OBJECT_ENDIAN_INDEX       13
2822 #define ARMAP_END_INDEX                 14
2823 #define ARMAP_END                       "_ "
2824
2825 /* This is a magic number used in the hashing algorithm.  */
2826 #define ARMAP_HASH_MAGIC                0x9dd68ab5
2827
2828 /* This returns the hash value to use for a string.  It also sets
2829    *REHASH to the rehash adjustment if the first slot is taken.  SIZE
2830    is the number of entries in the hash table, and HLOG is the log
2831    base 2 of SIZE.  */
2832
2833 static unsigned int
2834 ecoff_armap_hash (const char *s,
2835                   unsigned int *rehash,
2836                   unsigned int size,
2837                   unsigned int hlog)
2838 {
2839   unsigned int hash;
2840
2841   if (hlog == 0)
2842     return 0;
2843   hash = *s++;
2844   while (*s != '\0')
2845     hash = ((hash >> 27) | (hash << 5)) + *s++;
2846   hash *= ARMAP_HASH_MAGIC;
2847   *rehash = (hash & (size - 1)) | 1;
2848   return hash >> (32 - hlog);
2849 }
2850
2851 /* Read in the armap.  */
2852
2853 bfd_boolean
2854 _bfd_ecoff_slurp_armap (bfd *abfd)
2855 {
2856   char nextname[17];
2857   unsigned int i;
2858   struct areltdata *mapdata;
2859   bfd_size_type parsed_size;
2860   char *raw_armap;
2861   struct artdata *ardata;
2862   unsigned int count;
2863   char *raw_ptr;
2864   carsym *symdef_ptr;
2865   char *stringbase;
2866   bfd_size_type amt;
2867
2868   /* Get the name of the first element.  */
2869   i = bfd_bread ((void *) nextname, (bfd_size_type) 16, abfd);
2870   if (i == 0)
2871       return TRUE;
2872   if (i != 16)
2873       return FALSE;
2874
2875   if (bfd_seek (abfd, (file_ptr) -16, SEEK_CUR) != 0)
2876     return FALSE;
2877
2878   /* Irix 4.0.5F apparently can use either an ECOFF armap or a
2879      standard COFF armap.  We could move the ECOFF armap stuff into
2880      bfd_slurp_armap, but that seems inappropriate since no other
2881      target uses this format.  Instead, we check directly for a COFF
2882      armap.  */
2883   if (CONST_STRNEQ (nextname, "/               "))
2884     return bfd_slurp_armap (abfd);
2885
2886   /* See if the first element is an armap.  */
2887   if (! strneq (nextname, ecoff_backend (abfd)->armap_start, ARMAP_START_LENGTH)
2888       || nextname[ARMAP_HEADER_MARKER_INDEX] != ARMAP_MARKER
2889       || (nextname[ARMAP_HEADER_ENDIAN_INDEX] != ARMAP_BIG_ENDIAN
2890           && nextname[ARMAP_HEADER_ENDIAN_INDEX] != ARMAP_LITTLE_ENDIAN)
2891       || nextname[ARMAP_OBJECT_MARKER_INDEX] != ARMAP_MARKER
2892       || (nextname[ARMAP_OBJECT_ENDIAN_INDEX] != ARMAP_BIG_ENDIAN
2893           && nextname[ARMAP_OBJECT_ENDIAN_INDEX] != ARMAP_LITTLE_ENDIAN)
2894       || ! strneq (nextname + ARMAP_END_INDEX, ARMAP_END, sizeof ARMAP_END - 1))
2895     {
2896       bfd_has_map (abfd) = FALSE;
2897       return TRUE;
2898     }
2899
2900   /* Make sure we have the right byte ordering.  */
2901   if (((nextname[ARMAP_HEADER_ENDIAN_INDEX] == ARMAP_BIG_ENDIAN)
2902        ^ (bfd_header_big_endian (abfd)))
2903       || ((nextname[ARMAP_OBJECT_ENDIAN_INDEX] == ARMAP_BIG_ENDIAN)
2904           ^ (bfd_big_endian (abfd))))
2905     {
2906       bfd_set_error (bfd_error_wrong_format);
2907       return FALSE;
2908     }
2909
2910   /* Read in the armap.  */
2911   ardata = bfd_ardata (abfd);
2912   mapdata = (struct areltdata *) _bfd_read_ar_hdr (abfd);
2913   if (mapdata == NULL)
2914     return FALSE;
2915   parsed_size = mapdata->parsed_size;
2916   free (mapdata);
2917
2918   raw_armap = (char *) bfd_alloc (abfd, parsed_size);
2919   if (raw_armap == NULL)
2920     return FALSE;
2921
2922   if (bfd_bread ((void *) raw_armap, parsed_size, abfd) != parsed_size)
2923     {
2924       if (bfd_get_error () != bfd_error_system_call)
2925         bfd_set_error (bfd_error_malformed_archive);
2926       bfd_release (abfd, (void *) raw_armap);
2927       return FALSE;
2928     }
2929
2930   ardata->tdata = (void *) raw_armap;
2931
2932   count = H_GET_32 (abfd, raw_armap);
2933
2934   ardata->symdef_count = 0;
2935   ardata->cache = NULL;
2936
2937   /* This code used to overlay the symdefs over the raw archive data,
2938      but that doesn't work on a 64 bit host.  */
2939   stringbase = raw_armap + count * 8 + 8;
2940
2941 #ifdef CHECK_ARMAP_HASH
2942   {
2943     unsigned int hlog;
2944
2945     /* Double check that I have the hashing algorithm right by making
2946        sure that every symbol can be looked up successfully.  */
2947     hlog = 0;
2948     for (i = 1; i < count; i <<= 1)
2949       hlog++;
2950     BFD_ASSERT (i == count);
2951
2952     raw_ptr = raw_armap + 4;
2953     for (i = 0; i < count; i++, raw_ptr += 8)
2954       {
2955         unsigned int name_offset, file_offset;
2956         unsigned int hash, rehash, srch;
2957
2958         name_offset = H_GET_32 (abfd, raw_ptr);
2959         file_offset = H_GET_32 (abfd, (raw_ptr + 4));
2960         if (file_offset == 0)
2961           continue;
2962         hash = ecoff_armap_hash (stringbase + name_offset, &rehash, count,
2963                                  hlog);
2964         if (hash == i)
2965           continue;
2966
2967         /* See if we can rehash to this location.  */
2968         for (srch = (hash + rehash) & (count - 1);
2969              srch != hash && srch != i;
2970              srch = (srch + rehash) & (count - 1))
2971           BFD_ASSERT (H_GET_32 (abfd, (raw_armap + 8 + srch * 8)) != 0);
2972         BFD_ASSERT (srch == i);
2973       }
2974   }
2975
2976 #endif /* CHECK_ARMAP_HASH */
2977
2978   raw_ptr = raw_armap + 4;
2979   for (i = 0; i < count; i++, raw_ptr += 8)
2980     if (H_GET_32 (abfd, (raw_ptr + 4)) != 0)
2981       ++ardata->symdef_count;
2982
2983   amt = ardata->symdef_count;
2984   amt *= sizeof (carsym);
2985   symdef_ptr = (carsym *) bfd_alloc (abfd, amt);
2986   if (!symdef_ptr)
2987     return FALSE;
2988
2989   ardata->symdefs = symdef_ptr;
2990
2991   raw_ptr = raw_armap + 4;
2992   for (i = 0; i < count; i++, raw_ptr += 8)
2993     {
2994       unsigned int name_offset, file_offset;
2995
2996       file_offset = H_GET_32 (abfd, (raw_ptr + 4));
2997       if (file_offset == 0)
2998         continue;
2999       name_offset = H_GET_32 (abfd, raw_ptr);
3000       symdef_ptr->name = stringbase + name_offset;
3001       symdef_ptr->file_offset = file_offset;
3002       ++symdef_ptr;
3003     }
3004
3005   ardata->first_file_filepos = bfd_tell (abfd);
3006   /* Pad to an even boundary.  */
3007   ardata->first_file_filepos += ardata->first_file_filepos % 2;
3008
3009   bfd_has_map (abfd) = TRUE;
3010
3011   return TRUE;
3012 }
3013
3014 /* Write out an armap.  */
3015
3016 bfd_boolean
3017 _bfd_ecoff_write_armap (bfd *abfd,
3018                         unsigned int elength,
3019                         struct orl *map,
3020                         unsigned int orl_count,
3021                         int stridx)
3022 {
3023   unsigned int hashsize, hashlog;
3024   bfd_size_type symdefsize;
3025   int padit;
3026   unsigned int stringsize;
3027   unsigned int mapsize;
3028   file_ptr firstreal;
3029   struct ar_hdr hdr;
3030   struct stat statbuf;
3031   unsigned int i;
3032   bfd_byte temp[4];
3033   bfd_byte *hashtable;
3034   bfd *current;
3035   bfd *last_elt;
3036
3037   /* Ultrix appears to use as a hash table size the least power of two
3038      greater than twice the number of entries.  */
3039   for (hashlog = 0; ((unsigned int) 1 << hashlog) <= 2 * orl_count; hashlog++)
3040     ;
3041   hashsize = 1 << hashlog;
3042
3043   symdefsize = hashsize * 8;
3044   padit = stridx % 2;
3045   stringsize = stridx + padit;
3046
3047   /* Include 8 bytes to store symdefsize and stringsize in output.  */
3048   mapsize = symdefsize + stringsize + 8;
3049
3050   firstreal = SARMAG + sizeof (struct ar_hdr) + mapsize + elength;
3051
3052   memset ((void *) &hdr, 0, sizeof hdr);
3053
3054   /* Work out the ECOFF armap name.  */
3055   strcpy (hdr.ar_name, ecoff_backend (abfd)->armap_start);
3056   hdr.ar_name[ARMAP_HEADER_MARKER_INDEX] = ARMAP_MARKER;
3057   hdr.ar_name[ARMAP_HEADER_ENDIAN_INDEX] =
3058     (bfd_header_big_endian (abfd)
3059      ? ARMAP_BIG_ENDIAN
3060      : ARMAP_LITTLE_ENDIAN);
3061   hdr.ar_name[ARMAP_OBJECT_MARKER_INDEX] = ARMAP_MARKER;
3062   hdr.ar_name[ARMAP_OBJECT_ENDIAN_INDEX] =
3063     bfd_big_endian (abfd) ? ARMAP_BIG_ENDIAN : ARMAP_LITTLE_ENDIAN;
3064   memcpy (hdr.ar_name + ARMAP_END_INDEX, ARMAP_END, sizeof ARMAP_END - 1);
3065
3066   /* Write the timestamp of the archive header to be just a little bit
3067      later than the timestamp of the file, otherwise the linker will
3068      complain that the index is out of date.  Actually, the Ultrix
3069      linker just checks the archive name; the GNU linker may check the
3070      date.  */
3071   stat (abfd->filename, &statbuf);
3072   _bfd_ar_spacepad (hdr.ar_date, sizeof (hdr.ar_date), "%ld",
3073                     (long) (statbuf.st_mtime + 60));
3074
3075   /* The DECstation uses zeroes for the uid, gid and mode of the
3076      armap.  */
3077   hdr.ar_uid[0] = '0';
3078   hdr.ar_gid[0] = '0';
3079   /* Building gcc ends up extracting the armap as a file - twice.  */
3080   hdr.ar_mode[0] = '6';
3081   hdr.ar_mode[1] = '4';
3082   hdr.ar_mode[2] = '4';
3083
3084   _bfd_ar_spacepad (hdr.ar_size, sizeof (hdr.ar_size), "%-10ld", mapsize);
3085
3086   hdr.ar_fmag[0] = '`';
3087   hdr.ar_fmag[1] = '\012';
3088
3089   /* Turn all null bytes in the header into spaces.  */
3090   for (i = 0; i < sizeof (struct ar_hdr); i++)
3091    if (((char *) (&hdr))[i] == '\0')
3092      (((char *) (&hdr))[i]) = ' ';
3093
3094   if (bfd_bwrite ((void *) &hdr, (bfd_size_type) sizeof (struct ar_hdr), abfd)
3095       != sizeof (struct ar_hdr))
3096     return FALSE;
3097
3098   H_PUT_32 (abfd, hashsize, temp);
3099   if (bfd_bwrite ((void *) temp, (bfd_size_type) 4, abfd) != 4)
3100     return FALSE;
3101
3102   hashtable = (bfd_byte *) bfd_zalloc (abfd, symdefsize);
3103   if (!hashtable)
3104     return FALSE;
3105
3106   current = abfd->archive_head;
3107   last_elt = current;
3108   for (i = 0; i < orl_count; i++)
3109     {
3110       unsigned int hash, rehash = 0;
3111
3112       /* Advance firstreal to the file position of this archive
3113          element.  */
3114       if (map[i].u.abfd != last_elt)
3115         {
3116           do
3117             {
3118               firstreal += arelt_size (current) + sizeof (struct ar_hdr);
3119               firstreal += firstreal % 2;
3120               current = current->archive_next;
3121             }
3122           while (current != map[i].u.abfd);
3123         }
3124
3125       last_elt = current;
3126
3127       hash = ecoff_armap_hash (*map[i].name, &rehash, hashsize, hashlog);
3128       if (H_GET_32 (abfd, (hashtable + (hash * 8) + 4)) != 0)
3129         {
3130           unsigned int srch;
3131
3132           /* The desired slot is already taken.  */
3133           for (srch = (hash + rehash) & (hashsize - 1);
3134                srch != hash;
3135                srch = (srch + rehash) & (hashsize - 1))
3136             if (H_GET_32 (abfd, (hashtable + (srch * 8) + 4)) == 0)
3137               break;
3138
3139           BFD_ASSERT (srch != hash);
3140
3141           hash = srch;
3142         }
3143
3144       H_PUT_32 (abfd, map[i].namidx, (hashtable + hash * 8));
3145       H_PUT_32 (abfd, firstreal, (hashtable + hash * 8 + 4));
3146     }
3147
3148   if (bfd_bwrite ((void *) hashtable, symdefsize, abfd) != symdefsize)
3149     return FALSE;
3150
3151   bfd_release (abfd, hashtable);
3152
3153   /* Now write the strings.  */
3154   H_PUT_32 (abfd, stringsize, temp);
3155   if (bfd_bwrite ((void *) temp, (bfd_size_type) 4, abfd) != 4)
3156     return FALSE;
3157   for (i = 0; i < orl_count; i++)
3158     {
3159       bfd_size_type len;
3160
3161       len = strlen (*map[i].name) + 1;
3162       if (bfd_bwrite ((void *) (*map[i].name), len, abfd) != len)
3163         return FALSE;
3164     }
3165
3166   /* The spec sez this should be a newline.  But in order to be
3167      bug-compatible for DECstation ar we use a null.  */
3168   if (padit)
3169     {
3170       if (bfd_bwrite ("", (bfd_size_type) 1, abfd) != 1)
3171         return FALSE;
3172     }
3173
3174   return TRUE;
3175 }
3176 \f
3177 /* ECOFF linker code.  */
3178
3179 /* Routine to create an entry in an ECOFF link hash table.  */
3180
3181 static struct bfd_hash_entry *
3182 ecoff_link_hash_newfunc (struct bfd_hash_entry *entry,
3183                          struct bfd_hash_table *table,
3184                          const char *string)
3185 {
3186   struct ecoff_link_hash_entry *ret = (struct ecoff_link_hash_entry *) entry;
3187
3188   /* Allocate the structure if it has not already been allocated by a
3189      subclass.  */
3190   if (ret == NULL)
3191     ret = ((struct ecoff_link_hash_entry *)
3192            bfd_hash_allocate (table, sizeof (struct ecoff_link_hash_entry)));
3193   if (ret == NULL)
3194     return NULL;
3195
3196   /* Call the allocation method of the superclass.  */
3197   ret = ((struct ecoff_link_hash_entry *)
3198          _bfd_link_hash_newfunc ((struct bfd_hash_entry *) ret,
3199                                  table, string));
3200
3201   if (ret)
3202     {
3203       /* Set local fields.  */
3204       ret->indx = -1;
3205       ret->abfd = NULL;
3206       ret->written = 0;
3207       ret->small = 0;
3208     }
3209   memset ((void *) &ret->esym, 0, sizeof ret->esym);
3210
3211   return (struct bfd_hash_entry *) ret;
3212 }
3213
3214 /* Create an ECOFF link hash table.  */
3215
3216 struct bfd_link_hash_table *
3217 _bfd_ecoff_bfd_link_hash_table_create (bfd *abfd)
3218 {
3219   struct ecoff_link_hash_table *ret;
3220   bfd_size_type amt = sizeof (struct ecoff_link_hash_table);
3221
3222   ret = (struct ecoff_link_hash_table *) bfd_malloc (amt);
3223   if (ret == NULL)
3224     return NULL;
3225   if (!_bfd_link_hash_table_init (&ret->root, abfd,
3226                                   ecoff_link_hash_newfunc,
3227                                   sizeof (struct ecoff_link_hash_entry)))
3228     {
3229       free (ret);
3230       return NULL;
3231     }
3232   return &ret->root;
3233 }
3234
3235 /* Look up an entry in an ECOFF link hash table.  */
3236
3237 #define ecoff_link_hash_lookup(table, string, create, copy, follow) \
3238   ((struct ecoff_link_hash_entry *) \
3239    bfd_link_hash_lookup (&(table)->root, (string), (create), (copy), (follow)))
3240
3241 /* Get the ECOFF link hash table from the info structure.  This is
3242    just a cast.  */
3243
3244 #define ecoff_hash_table(p) ((struct ecoff_link_hash_table *) ((p)->hash))
3245
3246 /* Add the external symbols of an object file to the global linker
3247    hash table.  The external symbols and strings we are passed are
3248    just allocated on the stack, and will be discarded.  We must
3249    explicitly save any information we may need later on in the link.
3250    We do not want to read the external symbol information again.  */
3251
3252 static bfd_boolean
3253 ecoff_link_add_externals (bfd *abfd,
3254                           struct bfd_link_info *info,
3255                           void * external_ext,
3256                           char *ssext)
3257 {
3258   const struct ecoff_backend_data * const backend = ecoff_backend (abfd);
3259   void (* const swap_ext_in) (bfd *, void *, EXTR *)
3260     = backend->debug_swap.swap_ext_in;
3261   bfd_size_type external_ext_size = backend->debug_swap.external_ext_size;
3262   unsigned long ext_count;
3263   struct bfd_link_hash_entry **sym_hash;
3264   char *ext_ptr;
3265   char *ext_end;
3266   bfd_size_type amt;
3267
3268   ext_count = ecoff_data (abfd)->debug_info.symbolic_header.iextMax;
3269
3270   amt = ext_count;
3271   amt *= sizeof (struct bfd_link_hash_entry *);
3272   sym_hash = (struct bfd_link_hash_entry **) bfd_alloc (abfd, amt);
3273   if (!sym_hash)
3274     return FALSE;
3275   ecoff_data (abfd)->sym_hashes = (struct ecoff_link_hash_entry **) sym_hash;
3276
3277   ext_ptr = (char *) external_ext;
3278   ext_end = ext_ptr + ext_count * external_ext_size;
3279   for (; ext_ptr < ext_end; ext_ptr += external_ext_size, sym_hash++)
3280     {
3281       EXTR esym;
3282       bfd_boolean skip;
3283       bfd_vma value;
3284       asection *section;
3285       const char *name;
3286       struct ecoff_link_hash_entry *h;
3287
3288       *sym_hash = NULL;
3289
3290       (*swap_ext_in) (abfd, (void *) ext_ptr, &esym);
3291
3292       /* Skip debugging symbols.  */
3293       skip = FALSE;
3294       switch (esym.asym.st)
3295         {
3296         case stGlobal:
3297         case stStatic:
3298         case stLabel:
3299         case stProc:
3300         case stStaticProc:
3301           break;
3302         default:
3303           skip = TRUE;
3304           break;
3305         }
3306
3307       if (skip)
3308         continue;
3309
3310       /* Get the information for this symbol.  */
3311       value = esym.asym.value;
3312       switch (esym.asym.sc)
3313         {
3314         default:
3315         case scNil:
3316         case scRegister:
3317         case scCdbLocal:
3318         case scBits:
3319         case scCdbSystem:
3320         case scRegImage:
3321         case scInfo:
3322         case scUserStruct:
3323         case scVar:
3324         case scVarRegister:
3325         case scVariant:
3326         case scBasedVar:
3327         case scXData:
3328         case scPData:
3329           section = NULL;
3330           break;
3331         case scText:
3332           section = bfd_make_section_old_way (abfd, _TEXT);
3333           value -= section->vma;
3334           break;
3335         case scData:
3336           section = bfd_make_section_old_way (abfd, _DATA);
3337           value -= section->vma;
3338           break;
3339         case scBss:
3340           section = bfd_make_section_old_way (abfd, _BSS);
3341           value -= section->vma;
3342           break;
3343         case scAbs:
3344           section = bfd_abs_section_ptr;
3345           break;
3346         case scUndefined:
3347           section = bfd_und_section_ptr;
3348           break;
3349         case scSData:
3350           section = bfd_make_section_old_way (abfd, _SDATA);
3351           value -= section->vma;
3352           break;
3353         case scSBss:
3354           section = bfd_make_section_old_way (abfd, _SBSS);
3355           value -= section->vma;
3356           break;
3357         case scRData:
3358           section = bfd_make_section_old_way (abfd, _RDATA);
3359           value -= section->vma;
3360           break;
3361         case scCommon:
3362           if (value > ecoff_data (abfd)->gp_size)
3363             {
3364               section = bfd_com_section_ptr;
3365               break;
3366             }
3367           /* Fall through.  */
3368         case scSCommon:
3369           if (ecoff_scom_section.name == NULL)
3370             {
3371               /* Initialize the small common section.  */
3372               ecoff_scom_section.name = SCOMMON;
3373               ecoff_scom_section.flags = SEC_IS_COMMON;
3374               ecoff_scom_section.output_section = &ecoff_scom_section;
3375               ecoff_scom_section.symbol = &ecoff_scom_symbol;
3376               ecoff_scom_section.symbol_ptr_ptr = &ecoff_scom_symbol_ptr;
3377               ecoff_scom_symbol.name = SCOMMON;
3378               ecoff_scom_symbol.flags = BSF_SECTION_SYM;
3379               ecoff_scom_symbol.section = &ecoff_scom_section;
3380               ecoff_scom_symbol_ptr = &ecoff_scom_symbol;
3381             }
3382           section = &ecoff_scom_section;
3383           break;
3384         case scSUndefined:
3385           section = bfd_und_section_ptr;
3386           break;
3387         case scInit:
3388           section = bfd_make_section_old_way (abfd, _INIT);
3389           value -= section->vma;
3390           break;
3391         case scFini:
3392           section = bfd_make_section_old_way (abfd, _FINI);
3393           value -= section->vma;
3394           break;
3395         case scRConst:
3396           section = bfd_make_section_old_way (abfd, _RCONST);
3397           value -= section->vma;
3398           break;
3399         }
3400
3401       if (section == NULL)
3402         continue;
3403
3404       name = ssext + esym.asym.iss;
3405
3406       if (! (_bfd_generic_link_add_one_symbol
3407              (info, abfd, name,
3408               (flagword) (esym.weakext ? BSF_WEAK : BSF_GLOBAL),
3409               section, value, NULL, TRUE, TRUE, sym_hash)))
3410         return FALSE;
3411
3412       h = (struct ecoff_link_hash_entry *) *sym_hash;
3413
3414       /* If we are building an ECOFF hash table, save the external
3415          symbol information.  */
3416       if (bfd_get_flavour (info->output_bfd) == bfd_get_flavour (abfd))
3417         {
3418           if (h->abfd == NULL
3419               || (! bfd_is_und_section (section)
3420                   && (! bfd_is_com_section (section)
3421                       || (h->root.type != bfd_link_hash_defined
3422                           && h->root.type != bfd_link_hash_defweak))))
3423             {
3424               h->abfd = abfd;
3425               h->esym = esym;
3426             }
3427
3428           /* Remember whether this symbol was small undefined.  */
3429           if (esym.asym.sc == scSUndefined)
3430             h->small = 1;
3431
3432           /* If this symbol was ever small undefined, it needs to wind
3433              up in a GP relative section.  We can't control the
3434              section of a defined symbol, but we can control the
3435              section of a common symbol.  This case is actually needed
3436              on Ultrix 4.2 to handle the symbol cred in -lckrb.  */
3437           if (h->small
3438               && h->root.type == bfd_link_hash_common
3439               && streq (h->root.u.c.p->section->name, SCOMMON))
3440             {
3441               h->root.u.c.p->section = bfd_make_section_old_way (abfd,
3442                                                                  SCOMMON);
3443               h->root.u.c.p->section->flags = SEC_ALLOC;
3444               if (h->esym.asym.sc == scCommon)
3445                 h->esym.asym.sc = scSCommon;
3446             }
3447         }
3448     }
3449
3450   return TRUE;
3451 }
3452
3453 /* Add symbols from an ECOFF object file to the global linker hash
3454    table.  */
3455
3456 static bfd_boolean
3457 ecoff_link_add_object_symbols (bfd *abfd, struct bfd_link_info *info)
3458 {
3459   HDRR *symhdr;
3460   bfd_size_type external_ext_size;
3461   void * external_ext = NULL;
3462   bfd_size_type esize;
3463   char *ssext = NULL;
3464   bfd_boolean result;
3465
3466   if (! ecoff_slurp_symbolic_header (abfd))
3467     return FALSE;
3468
3469   /* If there are no symbols, we don't want it.  */
3470   if (bfd_get_symcount (abfd) == 0)
3471     return TRUE;
3472
3473   symhdr = &ecoff_data (abfd)->debug_info.symbolic_header;
3474
3475   /* Read in the external symbols and external strings.  */
3476   external_ext_size = ecoff_backend (abfd)->debug_swap.external_ext_size;
3477   esize = symhdr->iextMax * external_ext_size;
3478   external_ext = bfd_malloc (esize);
3479   if (external_ext == NULL && esize != 0)
3480     goto error_return;
3481
3482   if (bfd_seek (abfd, (file_ptr) symhdr->cbExtOffset, SEEK_SET) != 0
3483       || bfd_bread (external_ext, esize, abfd) != esize)
3484     goto error_return;
3485
3486   ssext = (char *) bfd_malloc ((bfd_size_type) symhdr->issExtMax);
3487   if (ssext == NULL && symhdr->issExtMax != 0)
3488     goto error_return;
3489
3490   if (bfd_seek (abfd, (file_ptr) symhdr->cbSsExtOffset, SEEK_SET) != 0
3491       || (bfd_bread (ssext, (bfd_size_type) symhdr->issExtMax, abfd)
3492           != (bfd_size_type) symhdr->issExtMax))
3493     goto error_return;
3494
3495   result = ecoff_link_add_externals (abfd, info, external_ext, ssext);
3496
3497   if (ssext != NULL)
3498     free (ssext);
3499   if (external_ext != NULL)
3500     free (external_ext);
3501   return result;
3502
3503  error_return:
3504   if (ssext != NULL)
3505     free (ssext);
3506   if (external_ext != NULL)
3507     free (external_ext);
3508   return FALSE;
3509 }
3510
3511 /* This is called if we used _bfd_generic_link_add_archive_symbols
3512    because we were not dealing with an ECOFF archive.  */
3513
3514 static bfd_boolean
3515 ecoff_link_check_archive_element (bfd *abfd,
3516                                   struct bfd_link_info *info,
3517                                   struct bfd_link_hash_entry *h,
3518                                   const char *name,
3519                                   bfd_boolean *pneeded)
3520 {
3521   *pneeded = FALSE;
3522
3523   /* Unlike the generic linker, we do not pull in elements because
3524      of common symbols.  */
3525   if (h->type != bfd_link_hash_undefined)
3526     return TRUE;
3527
3528   /* Include this element.  */
3529   if (!(*info->callbacks->add_archive_element) (info, abfd, name, &abfd))
3530     return FALSE;
3531   *pneeded = TRUE;
3532
3533   return ecoff_link_add_object_symbols (abfd, info);
3534 }
3535
3536 /* Add the symbols from an archive file to the global hash table.
3537    This looks through the undefined symbols, looks each one up in the
3538    archive hash table, and adds any associated object file.  We do not
3539    use _bfd_generic_link_add_archive_symbols because ECOFF archives
3540    already have a hash table, so there is no reason to construct
3541    another one.  */
3542
3543 static bfd_boolean
3544 ecoff_link_add_archive_symbols (bfd *abfd, struct bfd_link_info *info)
3545 {
3546   const struct ecoff_backend_data * const backend = ecoff_backend (abfd);
3547   const bfd_byte *raw_armap;
3548   struct bfd_link_hash_entry **pundef;
3549   unsigned int armap_count;
3550   unsigned int armap_log;
3551   unsigned int i;
3552   const bfd_byte *hashtable;
3553   const char *stringbase;
3554
3555   if (! bfd_has_map (abfd))
3556     {
3557       /* An empty archive is a special case.  */
3558       if (bfd_openr_next_archived_file (abfd, NULL) == NULL)
3559         return TRUE;
3560       bfd_set_error (bfd_error_no_armap);
3561       return FALSE;
3562     }
3563
3564   /* If we don't have any raw data for this archive, as can happen on
3565      Irix 4.0.5F, we call the generic routine.
3566      FIXME: We should be more clever about this, since someday tdata
3567      may get to something for a generic archive.  */
3568   raw_armap = (const bfd_byte *) bfd_ardata (abfd)->tdata;
3569   if (raw_armap == NULL)
3570     return (_bfd_generic_link_add_archive_symbols
3571             (abfd, info, ecoff_link_check_archive_element));
3572
3573   armap_count = H_GET_32 (abfd, raw_armap);
3574
3575   armap_log = 0;
3576   for (i = 1; i < armap_count; i <<= 1)
3577     armap_log++;
3578   BFD_ASSERT (i == armap_count);
3579
3580   hashtable = raw_armap + 4;
3581   stringbase = (const char *) raw_armap + armap_count * 8 + 8;
3582
3583   /* Look through the list of undefined symbols.  */
3584   pundef = &info->hash->undefs;
3585   while (*pundef != NULL)
3586     {
3587       struct bfd_link_hash_entry *h;
3588       unsigned int hash, rehash = 0;
3589       unsigned int file_offset;
3590       const char *name;
3591       bfd *element;
3592
3593       h = *pundef;
3594
3595       /* When a symbol is defined, it is not necessarily removed from
3596          the list.  */
3597       if (h->type != bfd_link_hash_undefined
3598           && h->type != bfd_link_hash_common)
3599         {
3600           /* Remove this entry from the list, for general cleanliness
3601              and because we are going to look through the list again
3602              if we search any more libraries.  We can't remove the
3603              entry if it is the tail, because that would lose any
3604              entries we add to the list later on.  */
3605           if (*pundef != info->hash->undefs_tail)
3606             *pundef = (*pundef)->u.undef.next;
3607           else
3608             pundef = &(*pundef)->u.undef.next;
3609           continue;
3610         }
3611
3612       /* Native ECOFF linkers do not pull in archive elements merely
3613          to satisfy common definitions, so neither do we.  We leave
3614          them on the list, though, in case we are linking against some
3615          other object format.  */
3616       if (h->type != bfd_link_hash_undefined)
3617         {
3618           pundef = &(*pundef)->u.undef.next;
3619           continue;
3620         }
3621
3622       /* Look for this symbol in the archive hash table.  */
3623       hash = ecoff_armap_hash (h->root.string, &rehash, armap_count,
3624                                armap_log);
3625
3626       file_offset = H_GET_32 (abfd, hashtable + (hash * 8) + 4);
3627       if (file_offset == 0)
3628         {
3629           /* Nothing in this slot.  */
3630           pundef = &(*pundef)->u.undef.next;
3631           continue;
3632         }
3633
3634       name = stringbase + H_GET_32 (abfd, hashtable + (hash * 8));
3635       if (name[0] != h->root.string[0]
3636           || ! streq (name, h->root.string))
3637         {
3638           unsigned int srch;
3639           bfd_boolean found;
3640
3641           /* That was the wrong symbol.  Try rehashing.  */
3642           found = FALSE;
3643           for (srch = (hash + rehash) & (armap_count - 1);
3644                srch != hash;
3645                srch = (srch + rehash) & (armap_count - 1))
3646             {
3647               file_offset = H_GET_32 (abfd, hashtable + (srch * 8) + 4);
3648               if (file_offset == 0)
3649                 break;
3650               name = stringbase + H_GET_32 (abfd, hashtable + (srch * 8));
3651               if (name[0] == h->root.string[0]
3652                   && streq (name, h->root.string))
3653                 {
3654                   found = TRUE;
3655                   break;
3656                 }
3657             }
3658
3659           if (! found)
3660             {
3661               pundef = &(*pundef)->u.undef.next;
3662               continue;
3663             }
3664
3665           hash = srch;
3666         }
3667
3668       element = (*backend->get_elt_at_filepos) (abfd, (file_ptr) file_offset);
3669       if (element == NULL)
3670         return FALSE;
3671
3672       if (! bfd_check_format (element, bfd_object))
3673         return FALSE;
3674
3675       /* Unlike the generic linker, we know that this element provides
3676          a definition for an undefined symbol and we know that we want
3677          to include it.  We don't need to check anything.  */
3678       if (!(*info->callbacks
3679             ->add_archive_element) (info, element, name, &element))
3680         return FALSE;
3681       if (! ecoff_link_add_object_symbols (element, info))
3682         return FALSE;
3683
3684       pundef = &(*pundef)->u.undef.next;
3685     }
3686
3687   return TRUE;
3688 }
3689
3690 /* Given an ECOFF BFD, add symbols to the global hash table as
3691    appropriate.  */
3692
3693 bfd_boolean
3694 _bfd_ecoff_bfd_link_add_symbols (bfd *abfd, struct bfd_link_info *info)
3695 {
3696   switch (bfd_get_format (abfd))
3697     {
3698     case bfd_object:
3699       return ecoff_link_add_object_symbols (abfd, info);
3700     case bfd_archive:
3701       return ecoff_link_add_archive_symbols (abfd, info);
3702     default:
3703       bfd_set_error (bfd_error_wrong_format);
3704       return FALSE;
3705     }
3706 }
3707
3708 \f
3709 /* ECOFF final link routines.  */
3710
3711 /* Structure used to pass information to ecoff_link_write_external.  */
3712
3713 struct extsym_info
3714 {
3715   bfd *abfd;
3716   struct bfd_link_info *info;
3717 };
3718
3719 /* Accumulate the debugging information for an input BFD into the
3720    output BFD.  This must read in the symbolic information of the
3721    input BFD.  */
3722
3723 static bfd_boolean
3724 ecoff_final_link_debug_accumulate (bfd *output_bfd,
3725                                    bfd *input_bfd,
3726                                    struct bfd_link_info *info,
3727                                    void * handle)
3728 {
3729   struct ecoff_debug_info * const debug = &ecoff_data (input_bfd)->debug_info;
3730   const struct ecoff_debug_swap * const swap =
3731     &ecoff_backend (input_bfd)->debug_swap;
3732   HDRR *symhdr = &debug->symbolic_header;
3733   bfd_boolean ret;
3734
3735 #define READ(ptr, offset, count, size, type)                             \
3736   if (symhdr->count == 0)                                                \
3737     debug->ptr = NULL;                                                   \
3738   else                                                                   \
3739     {                                                                    \
3740       bfd_size_type amt = (bfd_size_type) size * symhdr->count;          \
3741       debug->ptr = (type) bfd_malloc (amt);                              \
3742       if (debug->ptr == NULL)                                            \
3743         {                                                                \
3744           ret = FALSE;                                                   \
3745           goto return_something;                                         \
3746         }                                                                \
3747       if (bfd_seek (input_bfd, (file_ptr) symhdr->offset, SEEK_SET) != 0 \
3748           || bfd_bread (debug->ptr, amt, input_bfd) != amt)              \
3749         {                                                                \
3750           ret = FALSE;                                                   \
3751           goto return_something;                                         \
3752         }                                                                \
3753     }
3754
3755   /* If raw_syments is not NULL, then the data was already by read by
3756      _bfd_ecoff_slurp_symbolic_info.  */
3757   if (ecoff_data (input_bfd)->raw_syments == NULL)
3758     {
3759       READ (line, cbLineOffset, cbLine, sizeof (unsigned char),
3760             unsigned char *);
3761       READ (external_dnr, cbDnOffset, idnMax, swap->external_dnr_size, void *);
3762       READ (external_pdr, cbPdOffset, ipdMax, swap->external_pdr_size, void *);
3763       READ (external_sym, cbSymOffset, isymMax, swap->external_sym_size, void *);
3764       READ (external_opt, cbOptOffset, ioptMax, swap->external_opt_size, void *);
3765       READ (external_aux, cbAuxOffset, iauxMax, sizeof (union aux_ext),
3766             union aux_ext *);
3767       READ (ss, cbSsOffset, issMax, sizeof (char), char *);
3768       READ (external_fdr, cbFdOffset, ifdMax, swap->external_fdr_size, void *);
3769       READ (external_rfd, cbRfdOffset, crfd, swap->external_rfd_size, void *);
3770     }
3771 #undef READ
3772
3773   /* We do not read the external strings or the external symbols.  */
3774
3775   ret = (bfd_ecoff_debug_accumulate
3776          (handle, output_bfd, &ecoff_data (output_bfd)->debug_info,
3777           &ecoff_backend (output_bfd)->debug_swap,
3778           input_bfd, debug, swap, info));
3779
3780  return_something:
3781   if (ecoff_data (input_bfd)->raw_syments == NULL)
3782     {
3783       if (debug->line != NULL)
3784         free (debug->line);
3785       if (debug->external_dnr != NULL)
3786         free (debug->external_dnr);
3787       if (debug->external_pdr != NULL)
3788         free (debug->external_pdr);
3789       if (debug->external_sym != NULL)
3790         free (debug->external_sym);
3791       if (debug->external_opt != NULL)
3792         free (debug->external_opt);
3793       if (debug->external_aux != NULL)
3794         free (debug->external_aux);
3795       if (debug->ss != NULL)
3796         free (debug->ss);
3797       if (debug->external_fdr != NULL)
3798         free (debug->external_fdr);
3799       if (debug->external_rfd != NULL)
3800         free (debug->external_rfd);
3801
3802       /* Make sure we don't accidentally follow one of these pointers
3803          into freed memory.  */
3804       debug->line = NULL;
3805       debug->external_dnr = NULL;
3806       debug->external_pdr = NULL;
3807       debug->external_sym = NULL;
3808       debug->external_opt = NULL;
3809       debug->external_aux = NULL;
3810       debug->ss = NULL;
3811       debug->external_fdr = NULL;
3812       debug->external_rfd = NULL;
3813     }
3814
3815   return ret;
3816 }
3817
3818 /* Relocate and write an ECOFF section into an ECOFF output file.  */
3819
3820 static bfd_boolean
3821 ecoff_indirect_link_order (bfd *output_bfd,
3822                            struct bfd_link_info *info,
3823                            asection *output_section,
3824                            struct bfd_link_order *link_order)
3825 {
3826   asection *input_section;
3827   bfd *input_bfd;
3828   bfd_byte *contents = NULL;
3829   bfd_size_type external_reloc_size;
3830   bfd_size_type external_relocs_size;
3831   void * external_relocs = NULL;
3832
3833   BFD_ASSERT ((output_section->flags & SEC_HAS_CONTENTS) != 0);
3834
3835   input_section = link_order->u.indirect.section;
3836   input_bfd = input_section->owner;
3837   if (input_section->size == 0)
3838     return TRUE;
3839
3840   BFD_ASSERT (input_section->output_section == output_section);
3841   BFD_ASSERT (input_section->output_offset == link_order->offset);
3842   BFD_ASSERT (input_section->size == link_order->size);
3843
3844   /* Get the section contents.  */
3845   if (!bfd_malloc_and_get_section (input_bfd, input_section, &contents))
3846     goto error_return;
3847
3848   /* Get the relocs.  If we are relaxing MIPS code, they will already
3849      have been read in.  Otherwise, we read them in now.  */
3850   external_reloc_size = ecoff_backend (input_bfd)->external_reloc_size;
3851   external_relocs_size = external_reloc_size * input_section->reloc_count;
3852
3853   external_relocs = bfd_malloc (external_relocs_size);
3854   if (external_relocs == NULL && external_relocs_size != 0)
3855     goto error_return;
3856
3857   if (bfd_seek (input_bfd, input_section->rel_filepos, SEEK_SET) != 0
3858       || (bfd_bread (external_relocs, external_relocs_size, input_bfd)
3859           != external_relocs_size))
3860     goto error_return;
3861
3862   /* Relocate the section contents.  */
3863   if (! ((*ecoff_backend (input_bfd)->relocate_section)
3864          (output_bfd, info, input_bfd, input_section, contents,
3865           external_relocs)))
3866     goto error_return;
3867
3868   /* Write out the relocated section.  */
3869   if (! bfd_set_section_contents (output_bfd,
3870                                   output_section,
3871                                   contents,
3872                                   input_section->output_offset,
3873                                   input_section->size))
3874     goto error_return;
3875
3876   /* If we are producing relocatable output, the relocs were
3877      modified, and we write them out now.  We use the reloc_count
3878      field of output_section to keep track of the number of relocs we
3879      have output so far.  */
3880   if (info->relocatable)
3881     {
3882       file_ptr pos = (output_section->rel_filepos
3883                       + output_section->reloc_count * external_reloc_size);
3884       if (bfd_seek (output_bfd, pos, SEEK_SET) != 0
3885           || (bfd_bwrite (external_relocs, external_relocs_size, output_bfd)
3886               != external_relocs_size))
3887         goto error_return;
3888       output_section->reloc_count += input_section->reloc_count;
3889     }
3890
3891   if (contents != NULL)
3892     free (contents);
3893   if (external_relocs != NULL)
3894     free (external_relocs);
3895   return TRUE;
3896
3897  error_return:
3898   if (contents != NULL)
3899     free (contents);
3900   if (external_relocs != NULL)
3901     free (external_relocs);
3902   return FALSE;
3903 }
3904
3905 /* Generate a reloc when linking an ECOFF file.  This is a reloc
3906    requested by the linker, and does come from any input file.  This
3907    is used to build constructor and destructor tables when linking
3908    with -Ur.  */
3909
3910 static bfd_boolean
3911 ecoff_reloc_link_order (bfd *output_bfd,
3912                         struct bfd_link_info *info,
3913                         asection *output_section,
3914                         struct bfd_link_order *link_order)
3915 {
3916   enum bfd_link_order_type type;
3917   asection *section;
3918   bfd_vma addend;
3919   arelent rel;
3920   struct internal_reloc in;
3921   bfd_size_type external_reloc_size;
3922   bfd_byte *rbuf;
3923   bfd_boolean ok;
3924   file_ptr pos;
3925
3926   type = link_order->type;
3927   section = NULL;
3928   addend = link_order->u.reloc.p->addend;
3929
3930   /* We set up an arelent to pass to the backend adjust_reloc_out
3931      routine.  */
3932   rel.address = link_order->offset;
3933
3934   rel.howto = bfd_reloc_type_lookup (output_bfd, link_order->u.reloc.p->reloc);
3935   if (rel.howto == 0)
3936     {
3937       bfd_set_error (bfd_error_bad_value);
3938       return FALSE;
3939     }
3940
3941   if (type == bfd_section_reloc_link_order)
3942     {
3943       section = link_order->u.reloc.p->u.section;
3944       rel.sym_ptr_ptr = section->symbol_ptr_ptr;
3945     }
3946   else
3947     {
3948       struct bfd_link_hash_entry *h;
3949
3950       /* Treat a reloc against a defined symbol as though it were
3951          actually against the section.  */
3952       h = bfd_wrapped_link_hash_lookup (output_bfd, info,
3953                                         link_order->u.reloc.p->u.name,
3954                                         FALSE, FALSE, FALSE);
3955       if (h != NULL
3956           && (h->type == bfd_link_hash_defined
3957               || h->type == bfd_link_hash_defweak))
3958         {
3959           type = bfd_section_reloc_link_order;
3960           section = h->u.def.section->output_section;
3961           /* It seems that we ought to add the symbol value to the
3962              addend here, but in practice it has already been added
3963              because it was passed to constructor_callback.  */
3964           addend += section->vma + h->u.def.section->output_offset;
3965         }
3966       else
3967         {
3968           /* We can't set up a reloc against a symbol correctly,
3969              because we have no asymbol structure.  Currently no
3970              adjust_reloc_out routine cares.  */
3971           rel.sym_ptr_ptr = NULL;
3972         }
3973     }
3974
3975   /* All ECOFF relocs are in-place.  Put the addend into the object
3976      file.  */
3977
3978   BFD_ASSERT (rel.howto->partial_inplace);
3979   if (addend != 0)
3980     {
3981       bfd_size_type size;
3982       bfd_reloc_status_type rstat;
3983       bfd_byte *buf;
3984
3985       size = bfd_get_reloc_size (rel.howto);
3986       buf = (bfd_byte *) bfd_zmalloc (size);
3987       if (buf == NULL)
3988         return FALSE;
3989       rstat = _bfd_relocate_contents (rel.howto, output_bfd,
3990                                       (bfd_vma) addend, buf);
3991       switch (rstat)
3992         {
3993         case bfd_reloc_ok:
3994           break;
3995         default:
3996         case bfd_reloc_outofrange:
3997           abort ();
3998         case bfd_reloc_overflow:
3999           if (! ((*info->callbacks->reloc_overflow)
4000                  (info, NULL,
4001                   (link_order->type == bfd_section_reloc_link_order
4002                    ? bfd_section_name (output_bfd, section)
4003                    : link_order->u.reloc.p->u.name),
4004                   rel.howto->name, addend, NULL,
4005                   NULL, (bfd_vma) 0)))
4006             {
4007               free (buf);
4008               return FALSE;
4009             }
4010           break;
4011         }
4012       ok = bfd_set_section_contents (output_bfd, output_section, (void *) buf,
4013                                      (file_ptr) link_order->offset, size);
4014       free (buf);
4015       if (! ok)
4016         return FALSE;
4017     }
4018
4019   rel.addend = 0;
4020
4021   /* Move the information into an internal_reloc structure.  */
4022   in.r_vaddr = (rel.address
4023                 + bfd_get_section_vma (output_bfd, output_section));
4024   in.r_type = rel.howto->type;
4025
4026   if (type == bfd_symbol_reloc_link_order)
4027     {
4028       struct ecoff_link_hash_entry *h;
4029
4030       h = ((struct ecoff_link_hash_entry *)
4031            bfd_wrapped_link_hash_lookup (output_bfd, info,
4032                                          link_order->u.reloc.p->u.name,
4033                                          FALSE, FALSE, TRUE));
4034       if (h != NULL
4035           && h->indx != -1)
4036         in.r_symndx = h->indx;
4037       else
4038         {
4039           if (! ((*info->callbacks->unattached_reloc)
4040                  (info, link_order->u.reloc.p->u.name, NULL,
4041                   NULL, (bfd_vma) 0)))
4042             return FALSE;
4043           in.r_symndx = 0;
4044         }
4045       in.r_extern = 1;
4046     }
4047   else
4048     {
4049       const char *name;
4050       unsigned int i;
4051       static struct
4052       {
4053         const char * name;
4054         long r_symndx;
4055       }
4056       section_symndx [] =
4057       {
4058         { _TEXT,   RELOC_SECTION_TEXT   },
4059         { _RDATA,  RELOC_SECTION_RDATA  },
4060         { _DATA,   RELOC_SECTION_DATA   },
4061         { _SDATA,  RELOC_SECTION_SDATA  },
4062         { _SBSS,   RELOC_SECTION_SBSS   },
4063         { _BSS,    RELOC_SECTION_BSS    },
4064         { _INIT,   RELOC_SECTION_INIT   },
4065         { _LIT8,   RELOC_SECTION_LIT8   },
4066         { _LIT4,   RELOC_SECTION_LIT4   },
4067         { _XDATA,  RELOC_SECTION_XDATA  },
4068         { _PDATA,  RELOC_SECTION_PDATA  },
4069         { _FINI,   RELOC_SECTION_FINI   },
4070         { _LITA,   RELOC_SECTION_LITA   },
4071         { "*ABS*", RELOC_SECTION_ABS    },
4072         { _RCONST, RELOC_SECTION_RCONST }
4073       };
4074
4075       name = bfd_get_section_name (output_bfd, section);
4076
4077       for (i = 0; i < ARRAY_SIZE (section_symndx); i++)
4078         if (streq (name, section_symndx[i].name))
4079           {
4080             in.r_symndx = section_symndx[i].r_symndx;
4081             break;
4082           }
4083
4084       if (i == ARRAY_SIZE (section_symndx))
4085         abort ();
4086
4087       in.r_extern = 0;
4088     }
4089
4090   /* Let the BFD backend adjust the reloc.  */
4091   (*ecoff_backend (output_bfd)->adjust_reloc_out) (output_bfd, &rel, &in);
4092
4093   /* Get some memory and swap out the reloc.  */
4094   external_reloc_size = ecoff_backend (output_bfd)->external_reloc_size;
4095   rbuf = (bfd_byte *) bfd_malloc (external_reloc_size);
4096   if (rbuf == NULL)
4097     return FALSE;
4098
4099   (*ecoff_backend (output_bfd)->swap_reloc_out) (output_bfd, &in, (void *) rbuf);
4100
4101   pos = (output_section->rel_filepos
4102          + output_section->reloc_count * external_reloc_size);
4103   ok = (bfd_seek (output_bfd, pos, SEEK_SET) == 0
4104         && (bfd_bwrite ((void *) rbuf, external_reloc_size, output_bfd)
4105             == external_reloc_size));
4106
4107   if (ok)
4108     ++output_section->reloc_count;
4109
4110   free (rbuf);
4111
4112   return ok;
4113 }
4114
4115 /* Put out information for an external symbol.  These come only from
4116    the hash table.  */
4117
4118 static bfd_boolean
4119 ecoff_link_write_external (struct bfd_hash_entry *bh, void * data)
4120 {
4121   struct ecoff_link_hash_entry *h = (struct ecoff_link_hash_entry *) bh;
4122   struct extsym_info *einfo = (struct extsym_info *) data;
4123   bfd *output_bfd = einfo->abfd;
4124   bfd_boolean strip;
4125
4126   if (h->root.type == bfd_link_hash_warning)
4127     {
4128       h = (struct ecoff_link_hash_entry *) h->root.u.i.link;
4129       if (h->root.type == bfd_link_hash_new)
4130         return TRUE;
4131     }
4132
4133   /* We need to check if this symbol is being stripped.  */
4134   if (h->root.type == bfd_link_hash_undefined
4135       || h->root.type == bfd_link_hash_undefweak)
4136     strip = FALSE;
4137   else if (einfo->info->strip == strip_all
4138            || (einfo->info->strip == strip_some
4139                && bfd_hash_lookup (einfo->info->keep_hash,
4140                                    h->root.root.string,
4141                                    FALSE, FALSE) == NULL))
4142     strip = TRUE;
4143   else
4144     strip = FALSE;
4145
4146   if (strip || h->written)
4147     return TRUE;
4148
4149   if (h->abfd == NULL)
4150     {
4151       h->esym.jmptbl = 0;
4152       h->esym.cobol_main = 0;
4153       h->esym.weakext = 0;
4154       h->esym.reserved = 0;
4155       h->esym.ifd = ifdNil;
4156       h->esym.asym.value = 0;
4157       h->esym.asym.st = stGlobal;
4158
4159       if (h->root.type != bfd_link_hash_defined
4160           && h->root.type != bfd_link_hash_defweak)
4161         h->esym.asym.sc = scAbs;
4162       else
4163         {
4164           asection *output_section;
4165           const char *name;
4166           unsigned int i;
4167           static struct
4168           {
4169             const char * name;
4170             int sc;
4171           }
4172           section_storage_classes [] =
4173           {
4174             { _TEXT,   scText   },
4175             { _DATA,   scData   },
4176             { _SDATA,  scSData  },
4177             { _RDATA,  scRData  },
4178             { _BSS,    scBss    },
4179             { _SBSS,   scSBss   },
4180             { _INIT,   scInit   },
4181             { _FINI,   scFini   },
4182             { _PDATA,  scPData  },
4183             { _XDATA,  scXData  },
4184             { _RCONST, scRConst }
4185           };
4186
4187           output_section = h->root.u.def.section->output_section;
4188           name = bfd_section_name (output_section->owner, output_section);
4189
4190           for (i = 0; i < ARRAY_SIZE (section_storage_classes); i++)
4191             if (streq (name, section_storage_classes[i].name))
4192               {
4193                 h->esym.asym.sc = section_storage_classes[i].sc;
4194                 break;
4195               }
4196
4197           if (i == ARRAY_SIZE (section_storage_classes))
4198             h->esym.asym.sc = scAbs;
4199         }
4200
4201       h->esym.asym.reserved = 0;
4202       h->esym.asym.index = indexNil;
4203     }
4204   else if (h->esym.ifd != -1)
4205     {
4206       struct ecoff_debug_info *debug;
4207
4208       /* Adjust the FDR index for the symbol by that used for the
4209          input BFD.  */
4210       debug = &ecoff_data (h->abfd)->debug_info;
4211       BFD_ASSERT (h->esym.ifd >= 0
4212                   && h->esym.ifd < debug->symbolic_header.ifdMax);
4213       h->esym.ifd = debug->ifdmap[h->esym.ifd];
4214     }
4215
4216   switch (h->root.type)
4217     {
4218     default:
4219     case bfd_link_hash_warning:
4220     case bfd_link_hash_new:
4221       abort ();
4222     case bfd_link_hash_undefined:
4223     case bfd_link_hash_undefweak:
4224       if (h->esym.asym.sc != scUndefined
4225           && h->esym.asym.sc != scSUndefined)
4226         h->esym.asym.sc = scUndefined;
4227       break;
4228     case bfd_link_hash_defined:
4229     case bfd_link_hash_defweak:
4230       if (h->esym.asym.sc == scUndefined
4231           || h->esym.asym.sc == scSUndefined)
4232         h->esym.asym.sc = scAbs;
4233       else if (h->esym.asym.sc == scCommon)
4234         h->esym.asym.sc = scBss;
4235       else if (h->esym.asym.sc == scSCommon)
4236         h->esym.asym.sc = scSBss;
4237       h->esym.asym.value = (h->root.u.def.value
4238                             + h->root.u.def.section->output_section->vma
4239                             + h->root.u.def.section->output_offset);
4240       break;
4241     case bfd_link_hash_common:
4242       if (h->esym.asym.sc != scCommon
4243           && h->esym.asym.sc != scSCommon)
4244         h->esym.asym.sc = scCommon;
4245       h->esym.asym.value = h->root.u.c.size;
4246       break;
4247     case bfd_link_hash_indirect:
4248       /* We ignore these symbols, since the indirected symbol is
4249          already in the hash table.  */
4250       return TRUE;
4251     }
4252
4253   /* bfd_ecoff_debug_one_external uses iextMax to keep track of the
4254      symbol number.  */
4255   h->indx = ecoff_data (output_bfd)->debug_info.symbolic_header.iextMax;
4256   h->written = 1;
4257
4258   return (bfd_ecoff_debug_one_external
4259           (output_bfd, &ecoff_data (output_bfd)->debug_info,
4260            &ecoff_backend (output_bfd)->debug_swap, h->root.root.string,
4261            &h->esym));
4262 }
4263
4264 /* ECOFF final link routine.  This looks through all the input BFDs
4265    and gathers together all the debugging information, and then
4266    processes all the link order information.  This may cause it to
4267    close and reopen some input BFDs; I'll see how bad this is.  */
4268
4269 bfd_boolean
4270 _bfd_ecoff_bfd_final_link (bfd *abfd, struct bfd_link_info *info)
4271 {
4272   const struct ecoff_backend_data * const backend = ecoff_backend (abfd);
4273   struct ecoff_debug_info * const debug = &ecoff_data (abfd)->debug_info;
4274   HDRR *symhdr;
4275   void * handle;
4276   bfd *input_bfd;
4277   asection *o;
4278   struct bfd_link_order *p;
4279   struct extsym_info einfo;
4280
4281   /* We accumulate the debugging information counts in the symbolic
4282      header.  */
4283   symhdr = &debug->symbolic_header;
4284   symhdr->vstamp = 0;
4285   symhdr->ilineMax = 0;
4286   symhdr->cbLine = 0;
4287   symhdr->idnMax = 0;
4288   symhdr->ipdMax = 0;
4289   symhdr->isymMax = 0;
4290   symhdr->ioptMax = 0;
4291   symhdr->iauxMax = 0;
4292   symhdr->issMax = 0;
4293   symhdr->issExtMax = 0;
4294   symhdr->ifdMax = 0;
4295   symhdr->crfd = 0;
4296   symhdr->iextMax = 0;
4297
4298   /* We accumulate the debugging information itself in the debug_info
4299      structure.  */
4300   debug->line = NULL;
4301   debug->external_dnr = NULL;
4302   debug->external_pdr = NULL;
4303   debug->external_sym = NULL;
4304   debug->external_opt = NULL;
4305   debug->external_aux = NULL;
4306   debug->ss = NULL;
4307   debug->ssext = debug->ssext_end = NULL;
4308   debug->external_fdr = NULL;
4309   debug->external_rfd = NULL;
4310   debug->external_ext = debug->external_ext_end = NULL;
4311
4312   handle = bfd_ecoff_debug_init (abfd, debug, &backend->debug_swap, info);
4313   if (handle == NULL)
4314     return FALSE;
4315
4316   /* Accumulate the debugging symbols from each input BFD.  */
4317   for (input_bfd = info->input_bfds;
4318        input_bfd != NULL;
4319        input_bfd = input_bfd->link.next)
4320     {
4321       bfd_boolean ret;
4322
4323       if (bfd_get_flavour (input_bfd) == bfd_target_ecoff_flavour)
4324         {
4325           /* Arbitrarily set the symbolic header vstamp to the vstamp
4326              of the first object file in the link.  */
4327           if (symhdr->vstamp == 0)
4328             symhdr->vstamp
4329               = ecoff_data (input_bfd)->debug_info.symbolic_header.vstamp;
4330           ret = ecoff_final_link_debug_accumulate (abfd, input_bfd, info,
4331                                                    handle);
4332         }
4333       else
4334         ret = bfd_ecoff_debug_accumulate_other (handle, abfd,
4335                                                 debug, &backend->debug_swap,
4336                                                 input_bfd, info);
4337       if (! ret)
4338         return FALSE;
4339
4340       /* Combine the register masks.  */
4341       ecoff_data (abfd)->gprmask |= ecoff_data (input_bfd)->gprmask;
4342       ecoff_data (abfd)->fprmask |= ecoff_data (input_bfd)->fprmask;
4343       ecoff_data (abfd)->cprmask[0] |= ecoff_data (input_bfd)->cprmask[0];
4344       ecoff_data (abfd)->cprmask[1] |= ecoff_data (input_bfd)->cprmask[1];
4345       ecoff_data (abfd)->cprmask[2] |= ecoff_data (input_bfd)->cprmask[2];
4346       ecoff_data (abfd)->cprmask[3] |= ecoff_data (input_bfd)->cprmask[3];
4347     }
4348
4349   /* Write out the external symbols.  */
4350   einfo.abfd = abfd;
4351   einfo.info = info;
4352   bfd_hash_traverse (&info->hash->table, ecoff_link_write_external, &einfo);
4353
4354   if (info->relocatable)
4355     {
4356       /* We need to make a pass over the link_orders to count up the
4357          number of relocations we will need to output, so that we know
4358          how much space they will take up.  */
4359       for (o = abfd->sections; o != NULL; o = o->next)
4360         {
4361           o->reloc_count = 0;
4362           for (p = o->map_head.link_order;
4363                p != NULL;
4364                p = p->next)
4365             if (p->type == bfd_indirect_link_order)
4366               o->reloc_count += p->u.indirect.section->reloc_count;
4367             else if (p->type == bfd_section_reloc_link_order
4368                      || p->type == bfd_symbol_reloc_link_order)
4369               ++o->reloc_count;
4370         }
4371     }
4372
4373   /* Compute the reloc and symbol file positions.  */
4374   ecoff_compute_reloc_file_positions (abfd);
4375
4376   /* Write out the debugging information.  */
4377   if (! bfd_ecoff_write_accumulated_debug (handle, abfd, debug,
4378                                            &backend->debug_swap, info,
4379                                            ecoff_data (abfd)->sym_filepos))
4380     return FALSE;
4381
4382   bfd_ecoff_debug_free (handle, abfd, debug, &backend->debug_swap, info);
4383
4384   if (info->relocatable)
4385     {
4386       /* Now reset the reloc_count field of the sections in the output
4387          BFD to 0, so that we can use them to keep track of how many
4388          relocs we have output thus far.  */
4389       for (o = abfd->sections; o != NULL; o = o->next)
4390         o->reloc_count = 0;
4391     }
4392
4393   /* Get a value for the GP register.  */
4394   if (ecoff_data (abfd)->gp == 0)
4395     {
4396       struct bfd_link_hash_entry *h;
4397
4398       h = bfd_link_hash_lookup (info->hash, "_gp", FALSE, FALSE, TRUE);
4399       if (h != NULL
4400           && h->type == bfd_link_hash_defined)
4401         ecoff_data (abfd)->gp = (h->u.def.value
4402                                  + h->u.def.section->output_section->vma
4403                                  + h->u.def.section->output_offset);
4404       else if (info->relocatable)
4405         {
4406           bfd_vma lo;
4407
4408           /* Make up a value.  */
4409           lo = (bfd_vma) -1;
4410           for (o = abfd->sections; o != NULL; o = o->next)
4411             {
4412               if (o->vma < lo
4413                   && (streq (o->name, _SBSS)
4414                       || streq (o->name, _SDATA)
4415                       || streq (o->name, _LIT4)
4416                       || streq (o->name, _LIT8)
4417                       || streq (o->name, _LITA)))
4418                 lo = o->vma;
4419             }
4420           ecoff_data (abfd)->gp = lo + 0x8000;
4421         }
4422       else
4423         {
4424           /* If the relocate_section function needs to do a reloc
4425              involving the GP value, it should make a reloc_dangerous
4426              callback to warn that GP is not defined.  */
4427         }
4428     }
4429
4430   for (o = abfd->sections; o != NULL; o = o->next)
4431     {
4432       for (p = o->map_head.link_order;
4433            p != NULL;
4434            p = p->next)
4435         {
4436           if (p->type == bfd_indirect_link_order
4437               && (bfd_get_flavour (p->u.indirect.section->owner)
4438                   == bfd_target_ecoff_flavour))
4439             {
4440               if (! ecoff_indirect_link_order (abfd, info, o, p))
4441                 return FALSE;
4442             }
4443           else if (p->type == bfd_section_reloc_link_order
4444                    || p->type == bfd_symbol_reloc_link_order)
4445             {
4446               if (! ecoff_reloc_link_order (abfd, info, o, p))
4447                 return FALSE;
4448             }
4449           else
4450             {
4451               if (! _bfd_default_link_order (abfd, info, o, p))
4452                 return FALSE;
4453             }
4454         }
4455     }
4456
4457   bfd_get_symcount (abfd) = symhdr->iextMax + symhdr->isymMax;
4458
4459   ecoff_data (abfd)->linker = TRUE;
4460
4461   return TRUE;
4462 }