Fixes a problem recognizing libraries created by Visual Studio.
[external/binutils.git] / bfd / coffgen.c
1 /* Support for the generic parts of COFF, for BFD.
2    Copyright (C) 1990-2015 Free Software Foundation, Inc.
3    Written by Cygnus Support.
4
5    This file is part of BFD, the Binary File Descriptor library.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
20    MA 02110-1301, USA.  */
21
22 /* Most of this hacked by  Steve Chamberlain, sac@cygnus.com.
23    Split out of coffcode.h by Ian Taylor, ian@cygnus.com.  */
24
25 /* This file contains COFF code that is not dependent on any
26    particular COFF target.  There is only one version of this file in
27    libbfd.a, so no target specific code may be put in here.  Or, to
28    put it another way,
29
30    ********** DO NOT PUT TARGET SPECIFIC CODE IN THIS FILE **********
31
32    If you need to add some target specific behaviour, add a new hook
33    function to bfd_coff_backend_data.
34
35    Some of these functions are also called by the ECOFF routines.
36    Those functions may not use any COFF specific information, such as
37    coff_data (abfd).  */
38
39 #include "sysdep.h"
40 #include "bfd.h"
41 #include "libbfd.h"
42 #include "coff/internal.h"
43 #include "libcoff.h"
44
45 /* Take a section header read from a coff file (in HOST byte order),
46    and make a BFD "section" out of it.  This is used by ECOFF.  */
47
48 static bfd_boolean
49 make_a_section_from_file (bfd *abfd,
50                           struct internal_scnhdr *hdr,
51                           unsigned int target_index)
52 {
53   asection *return_section;
54   char *name;
55   bfd_boolean result = TRUE;
56   flagword flags;
57
58   name = NULL;
59
60   /* Handle long section names as in PE.  On reading, we want to
61     accept long names if the format permits them at all, regardless
62     of the current state of the flag that dictates if we would generate
63     them in outputs; this construct checks if that is the case by
64     attempting to set the flag, without changing its state; the call
65     will fail for formats that do not support long names at all.  */
66   if (bfd_coff_set_long_section_names (abfd, bfd_coff_long_section_names (abfd))
67       && hdr->s_name[0] == '/')
68     {
69       char buf[SCNNMLEN];
70       long strindex;
71       char *p;
72       const char *strings;
73
74       /* Flag that this BFD uses long names, even though the format might
75          expect them to be off by default.  This won't directly affect the
76          format of any output BFD created from this one, but the information
77          can be used to decide what to do.  */
78       bfd_coff_set_long_section_names (abfd, TRUE);
79       memcpy (buf, hdr->s_name + 1, SCNNMLEN - 1);
80       buf[SCNNMLEN - 1] = '\0';
81       strindex = strtol (buf, &p, 10);
82       if (*p == '\0' && strindex >= 0)
83         {
84           strings = _bfd_coff_read_string_table (abfd);
85           if (strings == NULL)
86             return FALSE;
87           if ((bfd_size_type)(strindex + 2) >= obj_coff_strings_len (abfd))
88             return FALSE;
89           strings += strindex;
90           name = (char *) bfd_alloc (abfd,
91                                      (bfd_size_type) strlen (strings) + 1 + 1);
92           if (name == NULL)
93             return FALSE;
94           strcpy (name, strings);
95         }
96     }
97
98   if (name == NULL)
99     {
100       /* Assorted wastage to null-terminate the name, thanks AT&T! */
101       name = (char *) bfd_alloc (abfd,
102                                  (bfd_size_type) sizeof (hdr->s_name) + 1 + 1);
103       if (name == NULL)
104         return FALSE;
105       strncpy (name, (char *) &hdr->s_name[0], sizeof (hdr->s_name));
106       name[sizeof (hdr->s_name)] = 0;
107     }
108
109   return_section = bfd_make_section_anyway (abfd, name);
110   if (return_section == NULL)
111     return FALSE;
112
113   return_section->vma = hdr->s_vaddr;
114   return_section->lma = hdr->s_paddr;
115   return_section->size = hdr->s_size;
116   return_section->filepos = hdr->s_scnptr;
117   return_section->rel_filepos = hdr->s_relptr;
118   return_section->reloc_count = hdr->s_nreloc;
119
120   bfd_coff_set_alignment_hook (abfd, return_section, hdr);
121
122   return_section->line_filepos = hdr->s_lnnoptr;
123
124   return_section->lineno_count = hdr->s_nlnno;
125   return_section->userdata = NULL;
126   return_section->next = NULL;
127   return_section->target_index = target_index;
128
129   if (! bfd_coff_styp_to_sec_flags_hook (abfd, hdr, name, return_section,
130                                          & flags))
131     result = FALSE;
132
133   return_section->flags = flags;
134
135   /* At least on i386-coff, the line number count for a shared library
136      section must be ignored.  */
137   if ((return_section->flags & SEC_COFF_SHARED_LIBRARY) != 0)
138     return_section->lineno_count = 0;
139
140   if (hdr->s_nreloc != 0)
141     return_section->flags |= SEC_RELOC;
142   /* FIXME: should this check 'hdr->s_size > 0'.  */
143   if (hdr->s_scnptr != 0)
144     return_section->flags |= SEC_HAS_CONTENTS;
145
146   /* Compress/decompress DWARF debug sections with names: .debug_* and
147      .zdebug_*, after the section flags is set.  */
148   if ((flags & SEC_DEBUGGING)
149       && strlen (name) > 7
150       && ((name[1] == 'd' && name[6] == '_')
151           || (strlen (name) > 8 && name[1] == 'z' && name[7] == '_')))
152     {
153       enum { nothing, compress, decompress } action = nothing;
154       char *new_name = NULL;
155
156       if (bfd_is_section_compressed (abfd, return_section))
157         {
158           /* Compressed section.  Check if we should decompress.  */
159           if ((abfd->flags & BFD_DECOMPRESS))
160             action = decompress;
161         }
162       else if (!bfd_is_section_compressed (abfd, return_section))
163         {
164           /* Normal section.  Check if we should compress.  */
165           if ((abfd->flags & BFD_COMPRESS) && return_section->size != 0)
166             action = compress;
167         }
168
169       switch (action)
170         {
171         case nothing:
172           break;
173         case compress:
174           if (!bfd_init_section_compress_status (abfd, return_section))
175             {
176               (*_bfd_error_handler)
177                 (_("%B: unable to initialize compress status for section %s"),
178                  abfd, name);
179               return FALSE;
180             }
181           if (name[1] != 'z')
182             {
183               unsigned int len = strlen (name);
184
185               new_name = bfd_alloc (abfd, len + 2);
186               if (new_name == NULL)
187                 return FALSE;
188               new_name[0] = '.';
189               new_name[1] = 'z';
190               memcpy (new_name + 2, name + 1, len);
191             }
192           break;
193         case decompress:
194           if (!bfd_init_section_decompress_status (abfd, return_section))
195             {
196               (*_bfd_error_handler)
197                 (_("%B: unable to initialize decompress status for section %s"),
198                  abfd, name);
199               return FALSE;
200             }
201           if (name[1] == 'z')
202             {
203               unsigned int len = strlen (name);
204
205               new_name = bfd_alloc (abfd, len);
206               if (new_name == NULL)
207                 return FALSE;
208               new_name[0] = '.';
209               memcpy (new_name + 1, name + 2, len - 1);
210             }
211           break;
212         }
213       if (new_name != NULL)
214         bfd_rename_section (abfd, return_section, new_name);
215     }
216
217   return result;
218 }
219
220 /* Read in a COFF object and make it into a BFD.  This is used by
221    ECOFF as well.  */
222 const bfd_target *
223 coff_real_object_p (bfd *,
224                     unsigned,
225                     struct internal_filehdr *,
226                     struct internal_aouthdr *);
227 const bfd_target *
228 coff_real_object_p (bfd *abfd,
229                     unsigned nscns,
230                     struct internal_filehdr *internal_f,
231                     struct internal_aouthdr *internal_a)
232 {
233   flagword oflags = abfd->flags;
234   bfd_vma ostart = bfd_get_start_address (abfd);
235   void * tdata;
236   void * tdata_save;
237   bfd_size_type readsize;       /* Length of file_info.  */
238   unsigned int scnhsz;
239   char *external_sections;
240
241   if (!(internal_f->f_flags & F_RELFLG))
242     abfd->flags |= HAS_RELOC;
243   if ((internal_f->f_flags & F_EXEC))
244     abfd->flags |= EXEC_P;
245   if (!(internal_f->f_flags & F_LNNO))
246     abfd->flags |= HAS_LINENO;
247   if (!(internal_f->f_flags & F_LSYMS))
248     abfd->flags |= HAS_LOCALS;
249
250   /* FIXME: How can we set D_PAGED correctly?  */
251   if ((internal_f->f_flags & F_EXEC) != 0)
252     abfd->flags |= D_PAGED;
253
254   bfd_get_symcount (abfd) = internal_f->f_nsyms;
255   if (internal_f->f_nsyms)
256     abfd->flags |= HAS_SYMS;
257
258   if (internal_a != (struct internal_aouthdr *) NULL)
259     bfd_get_start_address (abfd) = internal_a->entry;
260   else
261     bfd_get_start_address (abfd) = 0;
262
263   /* Set up the tdata area.  ECOFF uses its own routine, and overrides
264      abfd->flags.  */
265   tdata_save = abfd->tdata.any;
266   tdata = bfd_coff_mkobject_hook (abfd, (void *) internal_f, (void *) internal_a);
267   if (tdata == NULL)
268     goto fail2;
269
270   scnhsz = bfd_coff_scnhsz (abfd);
271   readsize = (bfd_size_type) nscns * scnhsz;
272   external_sections = (char *) bfd_alloc (abfd, readsize);
273   if (!external_sections)
274     goto fail;
275
276   if (bfd_bread ((void *) external_sections, readsize, abfd) != readsize)
277     goto fail;
278
279   /* Set the arch/mach *before* swapping in sections; section header swapping
280      may depend on arch/mach info.  */
281   if (! bfd_coff_set_arch_mach_hook (abfd, (void *) internal_f))
282     goto fail;
283
284   /* Now copy data as required; construct all asections etc.  */
285   if (nscns != 0)
286     {
287       unsigned int i;
288       for (i = 0; i < nscns; i++)
289         {
290           struct internal_scnhdr tmp;
291           bfd_coff_swap_scnhdr_in (abfd,
292                                    (void *) (external_sections + i * scnhsz),
293                                    (void *) & tmp);
294           if (! make_a_section_from_file (abfd, &tmp, i + 1))
295             goto fail;
296         }
297     }
298
299   return abfd->xvec;
300
301  fail:
302   bfd_release (abfd, tdata);
303  fail2:
304   abfd->tdata.any = tdata_save;
305   abfd->flags = oflags;
306   bfd_get_start_address (abfd) = ostart;
307   return (const bfd_target *) NULL;
308 }
309
310 /* Turn a COFF file into a BFD, but fail with bfd_error_wrong_format if it is
311    not a COFF file.  This is also used by ECOFF.  */
312
313 const bfd_target *
314 coff_object_p (bfd *abfd)
315 {
316   bfd_size_type filhsz;
317   bfd_size_type aoutsz;
318   unsigned int nscns;
319   void * filehdr;
320   struct internal_filehdr internal_f;
321   struct internal_aouthdr internal_a;
322
323   /* Figure out how much to read.  */
324   filhsz = bfd_coff_filhsz (abfd);
325   aoutsz = bfd_coff_aoutsz (abfd);
326
327   filehdr = bfd_alloc (abfd, filhsz);
328   if (filehdr == NULL)
329     return NULL;
330   if (bfd_bread (filehdr, filhsz, abfd) != filhsz)
331     {
332       if (bfd_get_error () != bfd_error_system_call)
333         bfd_set_error (bfd_error_wrong_format);
334       bfd_release (abfd, filehdr);
335       return NULL;
336     }
337   bfd_coff_swap_filehdr_in (abfd, filehdr, &internal_f);
338   bfd_release (abfd, filehdr);
339
340   /* The XCOFF format has two sizes for the f_opthdr.  SMALL_AOUTSZ
341      (less than aoutsz) used in object files and AOUTSZ (equal to
342      aoutsz) in executables.  The bfd_coff_swap_aouthdr_in function
343      expects this header to be aoutsz bytes in length, so we use that
344      value in the call to bfd_alloc below.  But we must be careful to
345      only read in f_opthdr bytes in the call to bfd_bread.  We should
346      also attempt to catch corrupt or non-COFF binaries with a strange
347      value for f_opthdr.  */
348   if (! bfd_coff_bad_format_hook (abfd, &internal_f)
349       || internal_f.f_opthdr > aoutsz)
350     {
351       bfd_set_error (bfd_error_wrong_format);
352       return NULL;
353     }
354   nscns = internal_f.f_nscns;
355
356   if (internal_f.f_opthdr)
357     {
358       void * opthdr;
359
360       opthdr = bfd_alloc (abfd, aoutsz);
361       if (opthdr == NULL)
362         return NULL;
363       if (bfd_bread (opthdr, (bfd_size_type) internal_f.f_opthdr, abfd)
364           != internal_f.f_opthdr)
365         {
366           bfd_release (abfd, opthdr);
367           return NULL;
368         }
369       /* PR 17512: file: 11056-1136-0.004.  */
370       if (internal_f.f_opthdr < aoutsz)
371         memset (((char *) opthdr) + internal_f.f_opthdr, 0, aoutsz - internal_f.f_opthdr);
372
373       bfd_coff_swap_aouthdr_in (abfd, opthdr, (void *) &internal_a);
374       bfd_release (abfd, opthdr);
375     }
376
377   return coff_real_object_p (abfd, nscns, &internal_f,
378                              (internal_f.f_opthdr != 0
379                               ? &internal_a
380                               : (struct internal_aouthdr *) NULL));
381 }
382
383 /* Get the BFD section from a COFF symbol section number.  */
384
385 asection *
386 coff_section_from_bfd_index (bfd *abfd, int section_index)
387 {
388   struct bfd_section *answer = abfd->sections;
389
390   if (section_index == N_ABS)
391     return bfd_abs_section_ptr;
392   if (section_index == N_UNDEF)
393     return bfd_und_section_ptr;
394   if (section_index == N_DEBUG)
395     return bfd_abs_section_ptr;
396
397   while (answer)
398     {
399       if (answer->target_index == section_index)
400         return answer;
401       answer = answer->next;
402     }
403
404   /* We should not reach this point, but the SCO 3.2v4 /lib/libc_s.a
405      has a bad symbol table in biglitpow.o.  */
406   return bfd_und_section_ptr;
407 }
408
409 /* Get the upper bound of a COFF symbol table.  */
410
411 long
412 coff_get_symtab_upper_bound (bfd *abfd)
413 {
414   if (!bfd_coff_slurp_symbol_table (abfd))
415     return -1;
416
417   return (bfd_get_symcount (abfd) + 1) * (sizeof (coff_symbol_type *));
418 }
419
420 /* Canonicalize a COFF symbol table.  */
421
422 long
423 coff_canonicalize_symtab (bfd *abfd, asymbol **alocation)
424 {
425   unsigned int counter;
426   coff_symbol_type *symbase;
427   coff_symbol_type **location = (coff_symbol_type **) alocation;
428
429   if (!bfd_coff_slurp_symbol_table (abfd))
430     return -1;
431
432   symbase = obj_symbols (abfd);
433   counter = bfd_get_symcount (abfd);
434   while (counter-- > 0)
435     *location++ = symbase++;
436
437   *location = NULL;
438
439   return bfd_get_symcount (abfd);
440 }
441
442 /* Get the name of a symbol.  The caller must pass in a buffer of size
443    >= SYMNMLEN + 1.  */
444
445 const char *
446 _bfd_coff_internal_syment_name (bfd *abfd,
447                                 const struct internal_syment *sym,
448                                 char *buf)
449 {
450   /* FIXME: It's not clear this will work correctly if sizeof
451      (_n_zeroes) != 4.  */
452   if (sym->_n._n_n._n_zeroes != 0
453       || sym->_n._n_n._n_offset == 0)
454     {
455       memcpy (buf, sym->_n._n_name, SYMNMLEN);
456       buf[SYMNMLEN] = '\0';
457       return buf;
458     }
459   else
460     {
461       const char *strings;
462
463       BFD_ASSERT (sym->_n._n_n._n_offset >= STRING_SIZE_SIZE);
464       strings = obj_coff_strings (abfd);
465       if (strings == NULL)
466         {
467           strings = _bfd_coff_read_string_table (abfd);
468           if (strings == NULL)
469             return NULL;
470         }
471       /* PR 17910: Only check for string overflow if the length has been set.
472          Some DLLs, eg those produced by Visual Studio, may not set the length field.  */
473       if (obj_coff_strings_len (abfd) > 0
474           && sym->_n._n_n._n_offset >= obj_coff_strings_len (abfd))
475         return NULL;
476       return strings + sym->_n._n_n._n_offset;
477     }
478 }
479
480 /* Read in and swap the relocs.  This returns a buffer holding the
481    relocs for section SEC in file ABFD.  If CACHE is TRUE and
482    INTERNAL_RELOCS is NULL, the relocs read in will be saved in case
483    the function is called again.  If EXTERNAL_RELOCS is not NULL, it
484    is a buffer large enough to hold the unswapped relocs.  If
485    INTERNAL_RELOCS is not NULL, it is a buffer large enough to hold
486    the swapped relocs.  If REQUIRE_INTERNAL is TRUE, then the return
487    value must be INTERNAL_RELOCS.  The function returns NULL on error.  */
488
489 struct internal_reloc *
490 _bfd_coff_read_internal_relocs (bfd *abfd,
491                                 asection *sec,
492                                 bfd_boolean cache,
493                                 bfd_byte *external_relocs,
494                                 bfd_boolean require_internal,
495                                 struct internal_reloc *internal_relocs)
496 {
497   bfd_size_type relsz;
498   bfd_byte *free_external = NULL;
499   struct internal_reloc *free_internal = NULL;
500   bfd_byte *erel;
501   bfd_byte *erel_end;
502   struct internal_reloc *irel;
503   bfd_size_type amt;
504
505   if (sec->reloc_count == 0)
506     return internal_relocs;     /* Nothing to do.  */
507
508   if (coff_section_data (abfd, sec) != NULL
509       && coff_section_data (abfd, sec)->relocs != NULL)
510     {
511       if (! require_internal)
512         return coff_section_data (abfd, sec)->relocs;
513       memcpy (internal_relocs, coff_section_data (abfd, sec)->relocs,
514               sec->reloc_count * sizeof (struct internal_reloc));
515       return internal_relocs;
516     }
517
518   relsz = bfd_coff_relsz (abfd);
519
520   amt = sec->reloc_count * relsz;
521   if (external_relocs == NULL)
522     {
523       free_external = (bfd_byte *) bfd_malloc (amt);
524       if (free_external == NULL)
525         goto error_return;
526       external_relocs = free_external;
527     }
528
529   if (bfd_seek (abfd, sec->rel_filepos, SEEK_SET) != 0
530       || bfd_bread (external_relocs, amt, abfd) != amt)
531     goto error_return;
532
533   if (internal_relocs == NULL)
534     {
535       amt = sec->reloc_count;
536       amt *= sizeof (struct internal_reloc);
537       free_internal = (struct internal_reloc *) bfd_malloc (amt);
538       if (free_internal == NULL)
539         goto error_return;
540       internal_relocs = free_internal;
541     }
542
543   /* Swap in the relocs.  */
544   erel = external_relocs;
545   erel_end = erel + relsz * sec->reloc_count;
546   irel = internal_relocs;
547   for (; erel < erel_end; erel += relsz, irel++)
548     bfd_coff_swap_reloc_in (abfd, (void *) erel, (void *) irel);
549
550   if (free_external != NULL)
551     {
552       free (free_external);
553       free_external = NULL;
554     }
555
556   if (cache && free_internal != NULL)
557     {
558       if (coff_section_data (abfd, sec) == NULL)
559         {
560           amt = sizeof (struct coff_section_tdata);
561           sec->used_by_bfd = bfd_zalloc (abfd, amt);
562           if (sec->used_by_bfd == NULL)
563             goto error_return;
564           coff_section_data (abfd, sec)->contents = NULL;
565         }
566       coff_section_data (abfd, sec)->relocs = free_internal;
567     }
568
569   return internal_relocs;
570
571  error_return:
572   if (free_external != NULL)
573     free (free_external);
574   if (free_internal != NULL)
575     free (free_internal);
576   return NULL;
577 }
578
579 /* Set lineno_count for the output sections of a COFF file.  */
580
581 int
582 coff_count_linenumbers (bfd *abfd)
583 {
584   unsigned int limit = bfd_get_symcount (abfd);
585   unsigned int i;
586   int total = 0;
587   asymbol **p;
588   asection *s;
589
590   if (limit == 0)
591     {
592       /* This may be from the backend linker, in which case the
593          lineno_count in the sections is correct.  */
594       for (s = abfd->sections; s != NULL; s = s->next)
595         total += s->lineno_count;
596       return total;
597     }
598
599   for (s = abfd->sections; s != NULL; s = s->next)
600     BFD_ASSERT (s->lineno_count == 0);
601
602   for (p = abfd->outsymbols, i = 0; i < limit; i++, p++)
603     {
604       asymbol *q_maybe = *p;
605
606       if (bfd_family_coff (bfd_asymbol_bfd (q_maybe)))
607         {
608           coff_symbol_type *q = coffsymbol (q_maybe);
609
610           /* The AIX 4.1 compiler can sometimes generate line numbers
611              attached to debugging symbols.  We try to simply ignore
612              those here.  */
613           if (q->lineno != NULL
614               && q->symbol.section->owner != NULL)
615             {
616               /* This symbol has line numbers.  Increment the owning
617                  section's linenumber count.  */
618               alent *l = q->lineno;
619
620               do
621                 {
622                   asection * sec = q->symbol.section->output_section;
623
624                   /* Do not try to update fields in read-only sections.  */
625                   if (! bfd_is_const_section (sec))
626                     sec->lineno_count ++;
627
628                   ++total;
629                   ++l;
630                 }
631               while (l->line_number != 0);
632             }
633         }
634     }
635
636   return total;
637 }
638
639 static void
640 fixup_symbol_value (bfd *abfd,
641                     coff_symbol_type *coff_symbol_ptr,
642                     struct internal_syment *syment)
643 {
644   /* Normalize the symbol flags.  */
645   if (coff_symbol_ptr->symbol.section
646       && bfd_is_com_section (coff_symbol_ptr->symbol.section))
647     {
648       /* A common symbol is undefined with a value.  */
649       syment->n_scnum = N_UNDEF;
650       syment->n_value = coff_symbol_ptr->symbol.value;
651     }
652   else if ((coff_symbol_ptr->symbol.flags & BSF_DEBUGGING) != 0
653            && (coff_symbol_ptr->symbol.flags & BSF_DEBUGGING_RELOC) == 0)
654     {
655       syment->n_value = coff_symbol_ptr->symbol.value;
656     }
657   else if (bfd_is_und_section (coff_symbol_ptr->symbol.section))
658     {
659       syment->n_scnum = N_UNDEF;
660       syment->n_value = 0;
661     }
662   /* FIXME: Do we need to handle the absolute section here?  */
663   else
664     {
665       if (coff_symbol_ptr->symbol.section)
666         {
667           syment->n_scnum =
668             coff_symbol_ptr->symbol.section->output_section->target_index;
669
670           syment->n_value = (coff_symbol_ptr->symbol.value
671                              + coff_symbol_ptr->symbol.section->output_offset);
672           if (! obj_pe (abfd))
673             {
674               syment->n_value += (syment->n_sclass == C_STATLAB)
675                 ? coff_symbol_ptr->symbol.section->output_section->lma
676                 : coff_symbol_ptr->symbol.section->output_section->vma;
677             }
678         }
679       else
680         {
681           BFD_ASSERT (0);
682           /* This can happen, but I don't know why yet (steve@cygnus.com) */
683           syment->n_scnum = N_ABS;
684           syment->n_value = coff_symbol_ptr->symbol.value;
685         }
686     }
687 }
688
689 /* Run through all the symbols in the symbol table and work out what
690    their indexes into the symbol table will be when output.
691
692    Coff requires that each C_FILE symbol points to the next one in the
693    chain, and that the last one points to the first external symbol. We
694    do that here too.  */
695
696 bfd_boolean
697 coff_renumber_symbols (bfd *bfd_ptr, int *first_undef)
698 {
699   unsigned int symbol_count = bfd_get_symcount (bfd_ptr);
700   asymbol **symbol_ptr_ptr = bfd_ptr->outsymbols;
701   unsigned int native_index = 0;
702   struct internal_syment *last_file = NULL;
703   unsigned int symbol_index;
704
705   /* COFF demands that undefined symbols come after all other symbols.
706      Since we don't need to impose this extra knowledge on all our
707      client programs, deal with that here.  Sort the symbol table;
708      just move the undefined symbols to the end, leaving the rest
709      alone.  The O'Reilly book says that defined global symbols come
710      at the end before the undefined symbols, so we do that here as
711      well.  */
712   /* @@ Do we have some condition we could test for, so we don't always
713      have to do this?  I don't think relocatability is quite right, but
714      I'm not certain.  [raeburn:19920508.1711EST]  */
715   {
716     asymbol **newsyms;
717     unsigned int i;
718     bfd_size_type amt;
719
720     amt = sizeof (asymbol *) * ((bfd_size_type) symbol_count + 1);
721     newsyms = (asymbol **) bfd_alloc (bfd_ptr, amt);
722     if (!newsyms)
723       return FALSE;
724     bfd_ptr->outsymbols = newsyms;
725     for (i = 0; i < symbol_count; i++)
726       if ((symbol_ptr_ptr[i]->flags & BSF_NOT_AT_END) != 0
727           || (!bfd_is_und_section (symbol_ptr_ptr[i]->section)
728               && !bfd_is_com_section (symbol_ptr_ptr[i]->section)
729               && ((symbol_ptr_ptr[i]->flags & BSF_FUNCTION) != 0
730                   || ((symbol_ptr_ptr[i]->flags & (BSF_GLOBAL | BSF_WEAK))
731                       == 0))))
732         *newsyms++ = symbol_ptr_ptr[i];
733
734     for (i = 0; i < symbol_count; i++)
735       if ((symbol_ptr_ptr[i]->flags & BSF_NOT_AT_END) == 0
736           && !bfd_is_und_section (symbol_ptr_ptr[i]->section)
737           && (bfd_is_com_section (symbol_ptr_ptr[i]->section)
738               || ((symbol_ptr_ptr[i]->flags & BSF_FUNCTION) == 0
739                   && ((symbol_ptr_ptr[i]->flags & (BSF_GLOBAL | BSF_WEAK))
740                       != 0))))
741         *newsyms++ = symbol_ptr_ptr[i];
742
743     *first_undef = newsyms - bfd_ptr->outsymbols;
744
745     for (i = 0; i < symbol_count; i++)
746       if ((symbol_ptr_ptr[i]->flags & BSF_NOT_AT_END) == 0
747           && bfd_is_und_section (symbol_ptr_ptr[i]->section))
748         *newsyms++ = symbol_ptr_ptr[i];
749     *newsyms = (asymbol *) NULL;
750     symbol_ptr_ptr = bfd_ptr->outsymbols;
751   }
752
753   for (symbol_index = 0; symbol_index < symbol_count; symbol_index++)
754     {
755       coff_symbol_type *coff_symbol_ptr;
756
757       coff_symbol_ptr = coff_symbol_from (symbol_ptr_ptr[symbol_index]);
758       symbol_ptr_ptr[symbol_index]->udata.i = symbol_index;
759       if (coff_symbol_ptr && coff_symbol_ptr->native)
760         {
761           combined_entry_type *s = coff_symbol_ptr->native;
762           int i;
763
764           BFD_ASSERT (s->is_sym);
765           if (s->u.syment.n_sclass == C_FILE)
766             {
767               if (last_file != NULL)
768                 last_file->n_value = native_index;
769               last_file = &(s->u.syment);
770             }
771           else
772             /* Modify the symbol values according to their section and
773                type.  */
774             fixup_symbol_value (bfd_ptr, coff_symbol_ptr, &(s->u.syment));
775
776           for (i = 0; i < s->u.syment.n_numaux + 1; i++)
777             s[i].offset = native_index++;
778         }
779       else
780         native_index++;
781     }
782
783   obj_conv_table_size (bfd_ptr) = native_index;
784
785   return TRUE;
786 }
787
788 /* Run thorough the symbol table again, and fix it so that all
789    pointers to entries are changed to the entries' index in the output
790    symbol table.  */
791
792 void
793 coff_mangle_symbols (bfd *bfd_ptr)
794 {
795   unsigned int symbol_count = bfd_get_symcount (bfd_ptr);
796   asymbol **symbol_ptr_ptr = bfd_ptr->outsymbols;
797   unsigned int symbol_index;
798
799   for (symbol_index = 0; symbol_index < symbol_count; symbol_index++)
800     {
801       coff_symbol_type *coff_symbol_ptr;
802
803       coff_symbol_ptr = coff_symbol_from (symbol_ptr_ptr[symbol_index]);
804       if (coff_symbol_ptr && coff_symbol_ptr->native)
805         {
806           int i;
807           combined_entry_type *s = coff_symbol_ptr->native;
808
809           BFD_ASSERT (s->is_sym);
810           if (s->fix_value)
811             {
812               /* FIXME: We should use a union here.  */
813               s->u.syment.n_value =
814                 (bfd_hostptr_t) ((combined_entry_type *)
815                           ((bfd_hostptr_t) s->u.syment.n_value))->offset;
816               s->fix_value = 0;
817             }
818           if (s->fix_line)
819             {
820               /* The value is the offset into the line number entries
821                  for the symbol's section.  On output, the symbol's
822                  section should be N_DEBUG.  */
823               s->u.syment.n_value =
824                 (coff_symbol_ptr->symbol.section->output_section->line_filepos
825                  + s->u.syment.n_value * bfd_coff_linesz (bfd_ptr));
826               coff_symbol_ptr->symbol.section =
827                 coff_section_from_bfd_index (bfd_ptr, N_DEBUG);
828               BFD_ASSERT (coff_symbol_ptr->symbol.flags & BSF_DEBUGGING);
829             }
830           for (i = 0; i < s->u.syment.n_numaux; i++)
831             {
832               combined_entry_type *a = s + i + 1;
833
834               BFD_ASSERT (! a->is_sym);
835               if (a->fix_tag)
836                 {
837                   a->u.auxent.x_sym.x_tagndx.l =
838                     a->u.auxent.x_sym.x_tagndx.p->offset;
839                   a->fix_tag = 0;
840                 }
841               if (a->fix_end)
842                 {
843                   a->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.l =
844                     a->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.p->offset;
845                   a->fix_end = 0;
846                 }
847               if (a->fix_scnlen)
848                 {
849                   a->u.auxent.x_csect.x_scnlen.l =
850                     a->u.auxent.x_csect.x_scnlen.p->offset;
851                   a->fix_scnlen = 0;
852                 }
853             }
854         }
855     }
856 }
857
858 static void
859 coff_fix_symbol_name (bfd *abfd,
860                       asymbol *symbol,
861                       combined_entry_type *native,
862                       bfd_size_type *string_size_p,
863                       asection **debug_string_section_p,
864                       bfd_size_type *debug_string_size_p)
865 {
866   unsigned int name_length;
867   union internal_auxent *auxent;
868   char *name = (char *) (symbol->name);
869
870   if (name == NULL)
871     {
872       /* COFF symbols always have names, so we'll make one up.  */
873       symbol->name = "strange";
874       name = (char *) symbol->name;
875     }
876   name_length = strlen (name);
877
878   BFD_ASSERT (native->is_sym);
879   if (native->u.syment.n_sclass == C_FILE
880       && native->u.syment.n_numaux > 0)
881     {
882       unsigned int filnmlen;
883
884       if (bfd_coff_force_symnames_in_strings (abfd))
885         {
886           native->u.syment._n._n_n._n_offset =
887               (*string_size_p + STRING_SIZE_SIZE);
888           native->u.syment._n._n_n._n_zeroes = 0;
889           *string_size_p += 6;  /* strlen(".file") + 1 */
890         }
891       else
892         strncpy (native->u.syment._n._n_name, ".file", SYMNMLEN);
893
894       BFD_ASSERT (! (native + 1)->is_sym);
895       auxent = &(native + 1)->u.auxent;
896
897       filnmlen = bfd_coff_filnmlen (abfd);
898
899       if (bfd_coff_long_filenames (abfd))
900         {
901           if (name_length <= filnmlen)
902             strncpy (auxent->x_file.x_fname, name, filnmlen);
903           else
904             {
905               auxent->x_file.x_n.x_offset = *string_size_p + STRING_SIZE_SIZE;
906               auxent->x_file.x_n.x_zeroes = 0;
907               *string_size_p += name_length + 1;
908             }
909         }
910       else
911         {
912           strncpy (auxent->x_file.x_fname, name, filnmlen);
913           if (name_length > filnmlen)
914             name[filnmlen] = '\0';
915         }
916     }
917   else
918     {
919       if (name_length <= SYMNMLEN && !bfd_coff_force_symnames_in_strings (abfd))
920         /* This name will fit into the symbol neatly.  */
921         strncpy (native->u.syment._n._n_name, symbol->name, SYMNMLEN);
922
923       else if (!bfd_coff_symname_in_debug (abfd, &native->u.syment))
924         {
925           native->u.syment._n._n_n._n_offset = (*string_size_p
926                                                 + STRING_SIZE_SIZE);
927           native->u.syment._n._n_n._n_zeroes = 0;
928           *string_size_p += name_length + 1;
929         }
930       else
931         {
932           file_ptr filepos;
933           bfd_byte buf[4];
934           int prefix_len = bfd_coff_debug_string_prefix_length (abfd);
935
936           /* This name should be written into the .debug section.  For
937              some reason each name is preceded by a two byte length
938              and also followed by a null byte.  FIXME: We assume that
939              the .debug section has already been created, and that it
940              is large enough.  */
941           if (*debug_string_section_p == (asection *) NULL)
942             *debug_string_section_p = bfd_get_section_by_name (abfd, ".debug");
943           filepos = bfd_tell (abfd);
944           if (prefix_len == 4)
945             bfd_put_32 (abfd, (bfd_vma) (name_length + 1), buf);
946           else
947             bfd_put_16 (abfd, (bfd_vma) (name_length + 1), buf);
948
949           if (!bfd_set_section_contents (abfd,
950                                          *debug_string_section_p,
951                                          (void *) buf,
952                                          (file_ptr) *debug_string_size_p,
953                                          (bfd_size_type) prefix_len)
954               || !bfd_set_section_contents (abfd,
955                                             *debug_string_section_p,
956                                             (void *) symbol->name,
957                                             (file_ptr) (*debug_string_size_p
958                                                         + prefix_len),
959                                             (bfd_size_type) name_length + 1))
960             abort ();
961           if (bfd_seek (abfd, filepos, SEEK_SET) != 0)
962             abort ();
963           native->u.syment._n._n_n._n_offset =
964               *debug_string_size_p + prefix_len;
965           native->u.syment._n._n_n._n_zeroes = 0;
966           *debug_string_size_p += name_length + 1 + prefix_len;
967         }
968     }
969 }
970
971 /* We need to keep track of the symbol index so that when we write out
972    the relocs we can get the index for a symbol.  This method is a
973    hack.  FIXME.  */
974
975 #define set_index(symbol, idx)  ((symbol)->udata.i = (idx))
976
977 /* Write a symbol out to a COFF file.  */
978
979 static bfd_boolean
980 coff_write_symbol (bfd *abfd,
981                    asymbol *symbol,
982                    combined_entry_type *native,
983                    bfd_vma *written,
984                    bfd_size_type *string_size_p,
985                    asection **debug_string_section_p,
986                    bfd_size_type *debug_string_size_p)
987 {
988   unsigned int numaux = native->u.syment.n_numaux;
989   int type = native->u.syment.n_type;
990   int n_sclass = (int) native->u.syment.n_sclass;
991   asection *output_section = symbol->section->output_section
992                                ? symbol->section->output_section
993                                : symbol->section;
994   void * buf;
995   bfd_size_type symesz;
996
997   BFD_ASSERT (native->is_sym);
998
999   if (native->u.syment.n_sclass == C_FILE)
1000     symbol->flags |= BSF_DEBUGGING;
1001
1002   if (symbol->flags & BSF_DEBUGGING
1003       && bfd_is_abs_section (symbol->section))
1004     native->u.syment.n_scnum = N_DEBUG;
1005
1006   else if (bfd_is_abs_section (symbol->section))
1007     native->u.syment.n_scnum = N_ABS;
1008
1009   else if (bfd_is_und_section (symbol->section))
1010     native->u.syment.n_scnum = N_UNDEF;
1011
1012   else
1013     native->u.syment.n_scnum =
1014       output_section->target_index;
1015
1016   coff_fix_symbol_name (abfd, symbol, native, string_size_p,
1017                         debug_string_section_p, debug_string_size_p);
1018
1019   symesz = bfd_coff_symesz (abfd);
1020   buf = bfd_alloc (abfd, symesz);
1021   if (!buf)
1022     return FALSE;
1023   bfd_coff_swap_sym_out (abfd, &native->u.syment, buf);
1024   if (bfd_bwrite (buf, symesz, abfd) != symesz)
1025     return FALSE;
1026   bfd_release (abfd, buf);
1027
1028   if (native->u.syment.n_numaux > 0)
1029     {
1030       bfd_size_type auxesz;
1031       unsigned int j;
1032
1033       auxesz = bfd_coff_auxesz (abfd);
1034       buf = bfd_alloc (abfd, auxesz);
1035       if (!buf)
1036         return FALSE;
1037       for (j = 0; j < native->u.syment.n_numaux; j++)
1038         {
1039           BFD_ASSERT (! (native + j + 1)->is_sym);
1040           bfd_coff_swap_aux_out (abfd,
1041                                  &((native + j + 1)->u.auxent),
1042                                  type, n_sclass, (int) j,
1043                                  native->u.syment.n_numaux,
1044                                  buf);
1045           if (bfd_bwrite (buf, auxesz, abfd) != auxesz)
1046             return FALSE;
1047         }
1048       bfd_release (abfd, buf);
1049     }
1050
1051   /* Store the index for use when we write out the relocs.  */
1052   set_index (symbol, *written);
1053
1054   *written += numaux + 1;
1055   return TRUE;
1056 }
1057
1058 /* Write out a symbol to a COFF file that does not come from a COFF
1059    file originally.  This symbol may have been created by the linker,
1060    or we may be linking a non COFF file to a COFF file.  */
1061
1062 bfd_boolean
1063 coff_write_alien_symbol (bfd *abfd,
1064                          asymbol *symbol,
1065                          struct internal_syment *isym,
1066                          bfd_vma *written,
1067                          bfd_size_type *string_size_p,
1068                          asection **debug_string_section_p,
1069                          bfd_size_type *debug_string_size_p)
1070 {
1071   combined_entry_type *native;
1072   combined_entry_type dummy[2];
1073   asection *output_section = symbol->section->output_section
1074                                ? symbol->section->output_section
1075                                : symbol->section;
1076   struct bfd_link_info *link_info = coff_data (abfd)->link_info;
1077   bfd_boolean ret;
1078
1079   if ((!link_info || link_info->strip_discarded)
1080       && !bfd_is_abs_section (symbol->section)
1081       && symbol->section->output_section == bfd_abs_section_ptr)
1082     {
1083       symbol->name = "";
1084       if (isym != NULL)
1085         memset (isym, 0, sizeof (*isym));
1086       return TRUE;
1087     }
1088   native = dummy;
1089   native->is_sym = TRUE;
1090   native[1].is_sym = FALSE;
1091   native->u.syment.n_type = T_NULL;
1092   native->u.syment.n_flags = 0;
1093   native->u.syment.n_numaux = 0;
1094   if (bfd_is_und_section (symbol->section))
1095     {
1096       native->u.syment.n_scnum = N_UNDEF;
1097       native->u.syment.n_value = symbol->value;
1098     }
1099   else if (bfd_is_com_section (symbol->section))
1100     {
1101       native->u.syment.n_scnum = N_UNDEF;
1102       native->u.syment.n_value = symbol->value;
1103     }
1104   else if (symbol->flags & BSF_FILE)
1105     {
1106       native->u.syment.n_scnum = N_DEBUG;
1107       native->u.syment.n_numaux = 1;
1108     }
1109   else if (symbol->flags & BSF_DEBUGGING)
1110     {
1111       /* There isn't much point to writing out a debugging symbol
1112          unless we are prepared to convert it into COFF debugging
1113          format.  So, we just ignore them.  We must clobber the symbol
1114          name to keep it from being put in the string table.  */
1115       symbol->name = "";
1116       if (isym != NULL)
1117         memset (isym, 0, sizeof (*isym));
1118       return TRUE;
1119     }
1120   else
1121     {
1122       native->u.syment.n_scnum = output_section->target_index;
1123       native->u.syment.n_value = (symbol->value
1124                                   + symbol->section->output_offset);
1125       if (! obj_pe (abfd))
1126         native->u.syment.n_value += output_section->vma;
1127
1128       /* Copy the any flags from the file header into the symbol.
1129          FIXME: Why?  */
1130       {
1131         coff_symbol_type *c = coff_symbol_from (symbol);
1132         if (c != (coff_symbol_type *) NULL)
1133           native->u.syment.n_flags = bfd_asymbol_bfd (&c->symbol)->flags;
1134       }
1135     }
1136
1137   native->u.syment.n_type = 0;
1138   if (symbol->flags & BSF_FILE)
1139     native->u.syment.n_sclass = C_FILE;
1140   else if (symbol->flags & BSF_LOCAL)
1141     native->u.syment.n_sclass = C_STAT;
1142   else if (symbol->flags & BSF_WEAK)
1143     native->u.syment.n_sclass = obj_pe (abfd) ? C_NT_WEAK : C_WEAKEXT;
1144   else
1145     native->u.syment.n_sclass = C_EXT;
1146
1147   ret = coff_write_symbol (abfd, symbol, native, written, string_size_p,
1148                            debug_string_section_p, debug_string_size_p);
1149   if (isym != NULL)
1150     *isym = native->u.syment;
1151   return ret;
1152 }
1153
1154 /* Write a native symbol to a COFF file.  */
1155
1156 static bfd_boolean
1157 coff_write_native_symbol (bfd *abfd,
1158                           coff_symbol_type *symbol,
1159                           bfd_vma *written,
1160                           bfd_size_type *string_size_p,
1161                           asection **debug_string_section_p,
1162                           bfd_size_type *debug_string_size_p)
1163 {
1164   combined_entry_type *native = symbol->native;
1165   alent *lineno = symbol->lineno;
1166   struct bfd_link_info *link_info = coff_data (abfd)->link_info;
1167
1168   if ((!link_info || link_info->strip_discarded)
1169       && !bfd_is_abs_section (symbol->symbol.section)
1170       && symbol->symbol.section->output_section == bfd_abs_section_ptr)
1171     {
1172       symbol->symbol.name = "";
1173       return TRUE;
1174     }
1175
1176   BFD_ASSERT (native->is_sym);
1177   /* If this symbol has an associated line number, we must store the
1178      symbol index in the line number field.  We also tag the auxent to
1179      point to the right place in the lineno table.  */
1180   if (lineno && !symbol->done_lineno && symbol->symbol.section->owner != NULL)
1181     {
1182       unsigned int count = 0;
1183
1184       lineno[count].u.offset = *written;
1185       if (native->u.syment.n_numaux)
1186         {
1187           union internal_auxent *a = &((native + 1)->u.auxent);
1188
1189           a->x_sym.x_fcnary.x_fcn.x_lnnoptr =
1190             symbol->symbol.section->output_section->moving_line_filepos;
1191         }
1192
1193       /* Count and relocate all other linenumbers.  */
1194       count++;
1195       while (lineno[count].line_number != 0)
1196         {
1197           lineno[count].u.offset +=
1198             (symbol->symbol.section->output_section->vma
1199              + symbol->symbol.section->output_offset);
1200           count++;
1201         }
1202       symbol->done_lineno = TRUE;
1203
1204       if (! bfd_is_const_section (symbol->symbol.section->output_section))
1205         symbol->symbol.section->output_section->moving_line_filepos +=
1206           count * bfd_coff_linesz (abfd);
1207     }
1208
1209   return coff_write_symbol (abfd, &(symbol->symbol), native, written,
1210                             string_size_p, debug_string_section_p,
1211                             debug_string_size_p);
1212 }
1213
1214 static void
1215 null_error_handler (const char * fmt ATTRIBUTE_UNUSED, ...)
1216 {
1217 }
1218
1219 /* Write out the COFF symbols.  */
1220
1221 bfd_boolean
1222 coff_write_symbols (bfd *abfd)
1223 {
1224   bfd_size_type string_size;
1225   asection *debug_string_section;
1226   bfd_size_type debug_string_size;
1227   unsigned int i;
1228   unsigned int limit = bfd_get_symcount (abfd);
1229   bfd_vma written = 0;
1230   asymbol **p;
1231
1232   string_size = 0;
1233   debug_string_section = NULL;
1234   debug_string_size = 0;
1235
1236   /* If this target supports long section names, they must be put into
1237      the string table.  This is supported by PE.  This code must
1238      handle section names just as they are handled in
1239      coff_write_object_contents.  */
1240   if (bfd_coff_long_section_names (abfd))
1241     {
1242       asection *o;
1243
1244       for (o = abfd->sections; o != NULL; o = o->next)
1245         {
1246           size_t len;
1247
1248           len = strlen (o->name);
1249           if (len > SCNNMLEN)
1250             string_size += len + 1;
1251         }
1252     }
1253
1254   /* Seek to the right place.  */
1255   if (bfd_seek (abfd, obj_sym_filepos (abfd), SEEK_SET) != 0)
1256     return FALSE;
1257
1258   /* Output all the symbols we have.  */
1259   written = 0;
1260   for (p = abfd->outsymbols, i = 0; i < limit; i++, p++)
1261     {
1262       asymbol *symbol = *p;
1263       coff_symbol_type *c_symbol = coff_symbol_from (symbol);
1264
1265       if (c_symbol == (coff_symbol_type *) NULL
1266           || c_symbol->native == (combined_entry_type *) NULL)
1267         {
1268           if (!coff_write_alien_symbol (abfd, symbol, NULL, &written,
1269                                         &string_size, &debug_string_section,
1270                                         &debug_string_size))
1271             return FALSE;
1272         }
1273       else
1274         {
1275           if (coff_backend_info (abfd)->_bfd_coff_classify_symbol != NULL)
1276             {
1277               bfd_error_handler_type current_error_handler;
1278               enum coff_symbol_classification sym_class;
1279               unsigned char *n_sclass;
1280
1281               /* Suppress error reporting by bfd_coff_classify_symbol.
1282                  Error messages can be generated when we are processing a local
1283                  symbol which has no associated section and we do not have to
1284                  worry about this, all we need to know is that it is local.  */
1285               current_error_handler = bfd_set_error_handler (null_error_handler);
1286               BFD_ASSERT (c_symbol->native->is_sym);
1287               sym_class = bfd_coff_classify_symbol (abfd,
1288                                                     &c_symbol->native->u.syment);
1289               (void) bfd_set_error_handler (current_error_handler);
1290
1291               n_sclass = &c_symbol->native->u.syment.n_sclass;
1292
1293               /* If the symbol class has been changed (eg objcopy/ld script/etc)
1294                  we cannot retain the existing sclass from the original symbol.
1295                  Weak symbols only have one valid sclass, so just set it always.
1296                  If it is not local class and should be, set it C_STAT.
1297                  If it is global and not classified as global, or if it is
1298                  weak (which is also classified as global), set it C_EXT.  */
1299
1300               if (symbol->flags & BSF_WEAK)
1301                 *n_sclass = obj_pe (abfd) ? C_NT_WEAK : C_WEAKEXT;
1302               else if (symbol->flags & BSF_LOCAL && sym_class != COFF_SYMBOL_LOCAL)
1303                 *n_sclass = C_STAT;
1304               else if (symbol->flags & BSF_GLOBAL
1305                        && (sym_class != COFF_SYMBOL_GLOBAL
1306 #ifdef COFF_WITH_PE
1307                            || *n_sclass == C_NT_WEAK
1308 #endif
1309                            || *n_sclass == C_WEAKEXT))
1310                 c_symbol->native->u.syment.n_sclass = C_EXT;
1311             }
1312
1313           if (!coff_write_native_symbol (abfd, c_symbol, &written,
1314                                          &string_size, &debug_string_section,
1315                                          &debug_string_size))
1316             return FALSE;
1317         }
1318     }
1319
1320   obj_raw_syment_count (abfd) = written;
1321
1322   /* Now write out strings.  */
1323   if (string_size != 0)
1324     {
1325       unsigned int size = string_size + STRING_SIZE_SIZE;
1326       bfd_byte buffer[STRING_SIZE_SIZE];
1327
1328 #if STRING_SIZE_SIZE == 4
1329       H_PUT_32 (abfd, size, buffer);
1330 #else
1331  #error Change H_PUT_32
1332 #endif
1333       if (bfd_bwrite ((void *) buffer, (bfd_size_type) sizeof (buffer), abfd)
1334           != sizeof (buffer))
1335         return FALSE;
1336
1337       /* Handle long section names.  This code must handle section
1338          names just as they are handled in coff_write_object_contents.  */
1339       if (bfd_coff_long_section_names (abfd))
1340         {
1341           asection *o;
1342
1343           for (o = abfd->sections; o != NULL; o = o->next)
1344             {
1345               size_t len;
1346
1347               len = strlen (o->name);
1348               if (len > SCNNMLEN)
1349                 {
1350                   if (bfd_bwrite (o->name, (bfd_size_type) (len + 1), abfd)
1351                       != len + 1)
1352                     return FALSE;
1353                 }
1354             }
1355         }
1356
1357       for (p = abfd->outsymbols, i = 0;
1358            i < limit;
1359            i++, p++)
1360         {
1361           asymbol *q = *p;
1362           size_t name_length = strlen (q->name);
1363           coff_symbol_type *c_symbol = coff_symbol_from (q);
1364           size_t maxlen;
1365
1366           /* Figure out whether the symbol name should go in the string
1367              table.  Symbol names that are short enough are stored
1368              directly in the syment structure.  File names permit a
1369              different, longer, length in the syment structure.  On
1370              XCOFF, some symbol names are stored in the .debug section
1371              rather than in the string table.  */
1372
1373           if (c_symbol == NULL
1374               || c_symbol->native == NULL)
1375             /* This is not a COFF symbol, so it certainly is not a
1376                file name, nor does it go in the .debug section.  */
1377             maxlen = bfd_coff_force_symnames_in_strings (abfd) ? 0 : SYMNMLEN;
1378
1379           else if (! c_symbol->native->is_sym)
1380             maxlen = bfd_coff_force_symnames_in_strings (abfd) ? 0 : SYMNMLEN;
1381             
1382           else if (bfd_coff_symname_in_debug (abfd,
1383                                               &c_symbol->native->u.syment))
1384             /* This symbol name is in the XCOFF .debug section.
1385                Don't write it into the string table.  */
1386             maxlen = name_length;
1387
1388           else if (c_symbol->native->u.syment.n_sclass == C_FILE
1389                    && c_symbol->native->u.syment.n_numaux > 0)
1390             {
1391               if (bfd_coff_force_symnames_in_strings (abfd))
1392                 {
1393                   if (bfd_bwrite (".file", (bfd_size_type) 6, abfd) != 6)
1394                     return FALSE;
1395                 }
1396               maxlen = bfd_coff_filnmlen (abfd);
1397             }
1398           else
1399             maxlen = bfd_coff_force_symnames_in_strings (abfd) ? 0 : SYMNMLEN;
1400
1401           if (name_length > maxlen)
1402             {
1403               if (bfd_bwrite ((void *) (q->name), (bfd_size_type) name_length + 1,
1404                              abfd) != name_length + 1)
1405                 return FALSE;
1406             }
1407         }
1408     }
1409   else
1410     {
1411       /* We would normally not write anything here, but we'll write
1412          out 4 so that any stupid coff reader which tries to read the
1413          string table even when there isn't one won't croak.  */
1414       unsigned int size = STRING_SIZE_SIZE;
1415       bfd_byte buffer[STRING_SIZE_SIZE];
1416
1417 #if STRING_SIZE_SIZE == 4
1418       H_PUT_32 (abfd, size, buffer);
1419 #else
1420  #error Change H_PUT_32
1421 #endif
1422       if (bfd_bwrite ((void *) buffer, (bfd_size_type) STRING_SIZE_SIZE, abfd)
1423           != STRING_SIZE_SIZE)
1424         return FALSE;
1425     }
1426
1427   /* Make sure the .debug section was created to be the correct size.
1428      We should create it ourselves on the fly, but we don't because
1429      BFD won't let us write to any section until we know how large all
1430      the sections are.  We could still do it by making another pass
1431      over the symbols.  FIXME.  */
1432   BFD_ASSERT (debug_string_size == 0
1433               || (debug_string_section != (asection *) NULL
1434                   && (BFD_ALIGN (debug_string_size,
1435                                  1 << debug_string_section->alignment_power)
1436                       == debug_string_section->size)));
1437
1438   return TRUE;
1439 }
1440
1441 bfd_boolean
1442 coff_write_linenumbers (bfd *abfd)
1443 {
1444   asection *s;
1445   bfd_size_type linesz;
1446   void * buff;
1447
1448   linesz = bfd_coff_linesz (abfd);
1449   buff = bfd_alloc (abfd, linesz);
1450   if (!buff)
1451     return FALSE;
1452   for (s = abfd->sections; s != (asection *) NULL; s = s->next)
1453     {
1454       if (s->lineno_count)
1455         {
1456           asymbol **q = abfd->outsymbols;
1457           if (bfd_seek (abfd, s->line_filepos, SEEK_SET) != 0)
1458             return FALSE;
1459           /* Find all the linenumbers in this section.  */
1460           while (*q)
1461             {
1462               asymbol *p = *q;
1463               if (p->section->output_section == s)
1464                 {
1465                   alent *l =
1466                   BFD_SEND (bfd_asymbol_bfd (p), _get_lineno,
1467                             (bfd_asymbol_bfd (p), p));
1468                   if (l)
1469                     {
1470                       /* Found a linenumber entry, output.  */
1471                       struct internal_lineno out;
1472
1473                       memset ((void *) & out, 0, sizeof (out));
1474                       out.l_lnno = 0;
1475                       out.l_addr.l_symndx = l->u.offset;
1476                       bfd_coff_swap_lineno_out (abfd, &out, buff);
1477                       if (bfd_bwrite (buff, (bfd_size_type) linesz, abfd)
1478                           != linesz)
1479                         return FALSE;
1480                       l++;
1481                       while (l->line_number)
1482                         {
1483                           out.l_lnno = l->line_number;
1484                           out.l_addr.l_symndx = l->u.offset;
1485                           bfd_coff_swap_lineno_out (abfd, &out, buff);
1486                           if (bfd_bwrite (buff, (bfd_size_type) linesz, abfd)
1487                               != linesz)
1488                             return FALSE;
1489                           l++;
1490                         }
1491                     }
1492                 }
1493               q++;
1494             }
1495         }
1496     }
1497   bfd_release (abfd, buff);
1498   return TRUE;
1499 }
1500
1501 alent *
1502 coff_get_lineno (bfd *ignore_abfd ATTRIBUTE_UNUSED, asymbol *symbol)
1503 {
1504   return coffsymbol (symbol)->lineno;
1505 }
1506
1507 /* This function transforms the offsets into the symbol table into
1508    pointers to syments.  */
1509
1510 static void
1511 coff_pointerize_aux (bfd *abfd,
1512                      combined_entry_type *table_base,
1513                      combined_entry_type *symbol,
1514                      unsigned int indaux,
1515                      combined_entry_type *auxent)
1516 {
1517   unsigned int type = symbol->u.syment.n_type;
1518   unsigned int n_sclass = symbol->u.syment.n_sclass;
1519
1520   BFD_ASSERT (symbol->is_sym);
1521   if (coff_backend_info (abfd)->_bfd_coff_pointerize_aux_hook)
1522     {
1523       if ((*coff_backend_info (abfd)->_bfd_coff_pointerize_aux_hook)
1524           (abfd, table_base, symbol, indaux, auxent))
1525         return;
1526     }
1527
1528   /* Don't bother if this is a file or a section.  */
1529   if (n_sclass == C_STAT && type == T_NULL)
1530     return;
1531   if (n_sclass == C_FILE)
1532     return;
1533
1534   BFD_ASSERT (! auxent->is_sym);
1535   /* Otherwise patch up.  */
1536 #define N_TMASK coff_data  (abfd)->local_n_tmask
1537 #define N_BTSHFT coff_data (abfd)->local_n_btshft
1538
1539   if ((ISFCN (type) || ISTAG (n_sclass) || n_sclass == C_BLOCK
1540        || n_sclass == C_FCN)
1541       && auxent->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.l > 0)
1542     {
1543       auxent->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.p =
1544         table_base + auxent->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.l;
1545       auxent->fix_end = 1;
1546     }
1547   /* A negative tagndx is meaningless, but the SCO 3.2v4 cc can
1548      generate one, so we must be careful to ignore it.  */
1549   if (auxent->u.auxent.x_sym.x_tagndx.l > 0)
1550     {
1551       auxent->u.auxent.x_sym.x_tagndx.p =
1552         table_base + auxent->u.auxent.x_sym.x_tagndx.l;
1553       auxent->fix_tag = 1;
1554     }
1555 }
1556
1557 /* Allocate space for the ".debug" section, and read it.
1558    We did not read the debug section until now, because
1559    we didn't want to go to the trouble until someone needed it.  */
1560
1561 static char *
1562 build_debug_section (bfd *abfd, asection ** sect_return)
1563 {
1564   char *debug_section;
1565   file_ptr position;
1566   bfd_size_type sec_size;
1567
1568   asection *sect = bfd_get_section_by_name (abfd, ".debug");
1569
1570   if (!sect)
1571     {
1572       bfd_set_error (bfd_error_no_debug_section);
1573       return NULL;
1574     }
1575
1576   sec_size = sect->size;
1577   debug_section = (char *) bfd_alloc (abfd, sec_size);
1578   if (debug_section == NULL)
1579     return NULL;
1580
1581   /* Seek to the beginning of the `.debug' section and read it.
1582      Save the current position first; it is needed by our caller.
1583      Then read debug section and reset the file pointer.  */
1584
1585   position = bfd_tell (abfd);
1586   if (bfd_seek (abfd, sect->filepos, SEEK_SET) != 0
1587       || bfd_bread (debug_section, sec_size, abfd) != sec_size
1588       || bfd_seek (abfd, position, SEEK_SET) != 0)
1589     return NULL;
1590
1591   * sect_return = sect;
1592   return debug_section;
1593 }
1594
1595 /* Return a pointer to a malloc'd copy of 'name'.  'name' may not be
1596    \0-terminated, but will not exceed 'maxlen' characters.  The copy *will*
1597    be \0-terminated.  */
1598
1599 static char *
1600 copy_name (bfd *abfd, char *name, size_t maxlen)
1601 {
1602   size_t len;
1603   char *newname;
1604
1605   for (len = 0; len < maxlen; ++len)
1606     if (name[len] == '\0')
1607       break;
1608
1609   if ((newname = (char *) bfd_alloc (abfd, (bfd_size_type) len + 1)) == NULL)
1610     return NULL;
1611
1612   strncpy (newname, name, len);
1613   newname[len] = '\0';
1614   return newname;
1615 }
1616
1617 /* Read in the external symbols.  */
1618
1619 bfd_boolean
1620 _bfd_coff_get_external_symbols (bfd *abfd)
1621 {
1622   bfd_size_type symesz;
1623   bfd_size_type size;
1624   void * syms;
1625
1626   if (obj_coff_external_syms (abfd) != NULL)
1627     return TRUE;
1628
1629   symesz = bfd_coff_symesz (abfd);
1630
1631   size = obj_raw_syment_count (abfd) * symesz;
1632   if (size == 0)
1633     return TRUE;
1634
1635   syms = bfd_malloc (size);
1636   if (syms == NULL)
1637     return FALSE;
1638
1639   if (bfd_seek (abfd, obj_sym_filepos (abfd), SEEK_SET) != 0
1640       || bfd_bread (syms, size, abfd) != size)
1641     {
1642       if (syms != NULL)
1643         free (syms);
1644       return FALSE;
1645     }
1646
1647   obj_coff_external_syms (abfd) = syms;
1648
1649   return TRUE;
1650 }
1651
1652 /* Read in the external strings.  The strings are not loaded until
1653    they are needed.  This is because we have no simple way of
1654    detecting a missing string table in an archive.  If the strings
1655    are loaded then the STRINGS and STRINGS_LEN fields in the
1656    coff_tdata structure will be set.  */
1657
1658 const char *
1659 _bfd_coff_read_string_table (bfd *abfd)
1660 {
1661   char extstrsize[STRING_SIZE_SIZE];
1662   bfd_size_type strsize;
1663   char *strings;
1664   file_ptr pos;
1665
1666   if (obj_coff_strings (abfd) != NULL)
1667     return obj_coff_strings (abfd);
1668
1669   if (obj_sym_filepos (abfd) == 0)
1670     {
1671       bfd_set_error (bfd_error_no_symbols);
1672       return NULL;
1673     }
1674
1675   pos = obj_sym_filepos (abfd);
1676   pos += obj_raw_syment_count (abfd) * bfd_coff_symesz (abfd);
1677   if (bfd_seek (abfd, pos, SEEK_SET) != 0)
1678     return NULL;
1679
1680   if (bfd_bread (extstrsize, (bfd_size_type) sizeof extstrsize, abfd)
1681       != sizeof extstrsize)
1682     {
1683       if (bfd_get_error () != bfd_error_file_truncated)
1684         return NULL;
1685
1686       /* There is no string table.  */
1687       strsize = STRING_SIZE_SIZE;
1688     }
1689   else
1690     {
1691 #if STRING_SIZE_SIZE == 4
1692       strsize = H_GET_32 (abfd, extstrsize);
1693 #else
1694  #error Change H_GET_32
1695 #endif
1696     }
1697
1698   if (strsize < STRING_SIZE_SIZE)
1699     {
1700       (*_bfd_error_handler)
1701         (_("%B: bad string table size %lu"), abfd, (unsigned long) strsize);
1702       bfd_set_error (bfd_error_bad_value);
1703       return NULL;
1704     }
1705
1706   strings = (char *) bfd_malloc (strsize + 1);
1707   if (strings == NULL)
1708     return NULL;
1709
1710   /* PR 17521 file: 079-54929-0.004.
1711      A corrupt file could contain an index that points into the first
1712      STRING_SIZE_SIZE bytes of the string table, so make sure that
1713      they are zero.  */
1714   memset (strings, 0, STRING_SIZE_SIZE);
1715
1716   if (bfd_bread (strings + STRING_SIZE_SIZE, strsize - STRING_SIZE_SIZE, abfd)
1717       != strsize - STRING_SIZE_SIZE)
1718     {
1719       free (strings);
1720       return NULL;
1721     }
1722
1723   obj_coff_strings (abfd) = strings;
1724   obj_coff_strings_len (abfd) = strsize;
1725   /* Terminate the string table, just in case.  */
1726   strings[strsize] = 0;
1727   return strings;
1728 }
1729
1730 /* Free up the external symbols and strings read from a COFF file.  */
1731
1732 bfd_boolean
1733 _bfd_coff_free_symbols (bfd *abfd)
1734 {
1735   if (obj_coff_external_syms (abfd) != NULL
1736       && ! obj_coff_keep_syms (abfd))
1737     {
1738       free (obj_coff_external_syms (abfd));
1739       obj_coff_external_syms (abfd) = NULL;
1740     }
1741   if (obj_coff_strings (abfd) != NULL
1742       && ! obj_coff_keep_strings (abfd))
1743     {
1744       free (obj_coff_strings (abfd));
1745       obj_coff_strings (abfd) = NULL;
1746       obj_coff_strings_len (abfd) = 0;
1747     }
1748   return TRUE;
1749 }
1750
1751 /* Read a symbol table into freshly bfd_allocated memory, swap it, and
1752    knit the symbol names into a normalized form.  By normalized here I
1753    mean that all symbols have an n_offset pointer that points to a null-
1754    terminated string.  */
1755
1756 combined_entry_type *
1757 coff_get_normalized_symtab (bfd *abfd)
1758 {
1759   combined_entry_type *internal;
1760   combined_entry_type *internal_ptr;
1761   combined_entry_type *symbol_ptr;
1762   combined_entry_type *internal_end;
1763   size_t symesz;
1764   char *raw_src;
1765   char *raw_end;
1766   const char *string_table = NULL;
1767   asection * debug_sec = NULL;
1768   char *debug_sec_data = NULL;
1769   bfd_size_type size;
1770
1771   if (obj_raw_syments (abfd) != NULL)
1772     return obj_raw_syments (abfd);
1773
1774   if (! _bfd_coff_get_external_symbols (abfd))
1775     return NULL;
1776
1777   size = obj_raw_syment_count (abfd) * sizeof (combined_entry_type);
1778   internal = (combined_entry_type *) bfd_zalloc (abfd, size);
1779   if (internal == NULL && size != 0)
1780     return NULL;
1781   internal_end = internal + obj_raw_syment_count (abfd);
1782   
1783   raw_src = (char *) obj_coff_external_syms (abfd);
1784
1785   /* Mark the end of the symbols.  */
1786   symesz = bfd_coff_symesz (abfd);
1787   raw_end = (char *) raw_src + obj_raw_syment_count (abfd) * symesz;
1788
1789   /* FIXME SOMEDAY.  A string table size of zero is very weird, but
1790      probably possible.  If one shows up, it will probably kill us.  */
1791
1792   /* Swap all the raw entries.  */
1793   for (internal_ptr = internal;
1794        raw_src < raw_end;
1795        raw_src += symesz, internal_ptr++)
1796     {
1797       unsigned int i;
1798
1799       bfd_coff_swap_sym_in (abfd, (void *) raw_src,
1800                             (void *) & internal_ptr->u.syment);
1801       symbol_ptr = internal_ptr;
1802       internal_ptr->is_sym = TRUE;
1803
1804       /* PR 17512: file: 1353-1166-0.004.  */
1805       if (symbol_ptr->u.syment.n_sclass == C_FILE
1806           && symbol_ptr->u.syment.n_numaux > 0
1807           && raw_src + symesz + symbol_ptr->u.syment.n_numaux
1808           * sizeof (union internal_auxent) >= raw_end)
1809         {
1810           bfd_release (abfd, internal);
1811           return NULL;
1812         }
1813
1814       for (i = 0;
1815            i < symbol_ptr->u.syment.n_numaux;
1816            i++)
1817         {
1818           internal_ptr++;
1819           /* PR 17512: Prevent buffer overrun.  */
1820           if (internal_ptr >= internal_end)
1821             {
1822               bfd_release (abfd, internal);
1823               return NULL;
1824             }
1825
1826           raw_src += symesz;
1827
1828           bfd_coff_swap_aux_in (abfd, (void *) raw_src,
1829                                 symbol_ptr->u.syment.n_type,
1830                                 symbol_ptr->u.syment.n_sclass,
1831                                 (int) i, symbol_ptr->u.syment.n_numaux,
1832                                 &(internal_ptr->u.auxent));
1833
1834           internal_ptr->is_sym = FALSE;
1835           coff_pointerize_aux (abfd, internal, symbol_ptr, i,
1836                                internal_ptr);
1837         }
1838     }
1839
1840   /* Free the raw symbols, but not the strings (if we have them).  */
1841   obj_coff_keep_strings (abfd) = TRUE;
1842   if (! _bfd_coff_free_symbols (abfd))
1843     return NULL;
1844
1845   for (internal_ptr = internal; internal_ptr < internal_end;
1846        internal_ptr++)
1847     {
1848       BFD_ASSERT (internal_ptr->is_sym);
1849
1850       if (internal_ptr->u.syment.n_sclass == C_FILE
1851           && internal_ptr->u.syment.n_numaux > 0)
1852         {
1853           combined_entry_type * aux = internal_ptr + 1;
1854
1855           /* Make a file symbol point to the name in the auxent, since
1856              the text ".file" is redundant.  */
1857           BFD_ASSERT (! aux->is_sym);
1858
1859           if (aux->u.auxent.x_file.x_n.x_zeroes == 0)
1860             {
1861               /* The filename is a long one, point into the string table.  */
1862               if (string_table == NULL)
1863                 {
1864                   string_table = _bfd_coff_read_string_table (abfd);
1865                   if (string_table == NULL)
1866                     return NULL;
1867                 }
1868
1869               if ((bfd_size_type)(aux->u.auxent.x_file.x_n.x_offset)
1870                   >= obj_coff_strings_len (abfd))
1871                 internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) _("<corrupt>");
1872               else
1873                 internal_ptr->u.syment._n._n_n._n_offset =
1874                   (bfd_hostptr_t) (string_table + (aux->u.auxent.x_file.x_n.x_offset));
1875             }
1876           else
1877             {
1878               /* Ordinary short filename, put into memory anyway.  The
1879                  Microsoft PE tools sometimes store a filename in
1880                  multiple AUX entries.  */
1881               if (internal_ptr->u.syment.n_numaux > 1
1882                   && coff_data (abfd)->pe)
1883                 internal_ptr->u.syment._n._n_n._n_offset =
1884                   (bfd_hostptr_t)
1885                   copy_name (abfd,
1886                              aux->u.auxent.x_file.x_fname,
1887                              internal_ptr->u.syment.n_numaux * symesz);
1888               else
1889                 internal_ptr->u.syment._n._n_n._n_offset =
1890                   ((bfd_hostptr_t)
1891                    copy_name (abfd,
1892                               aux->u.auxent.x_file.x_fname,
1893                               (size_t) bfd_coff_filnmlen (abfd)));
1894             }
1895         }
1896       else
1897         {
1898           if (internal_ptr->u.syment._n._n_n._n_zeroes != 0)
1899             {
1900               /* This is a "short" name.  Make it long.  */
1901               size_t i;
1902               char *newstring;
1903
1904               /* Find the length of this string without walking into memory
1905                  that isn't ours.  */
1906               for (i = 0; i < 8; ++i)
1907                 if (internal_ptr->u.syment._n._n_name[i] == '\0')
1908                   break;
1909
1910               newstring = (char *) bfd_zalloc (abfd, (bfd_size_type) (i + 1));
1911               if (newstring == NULL)
1912                 return NULL;
1913               strncpy (newstring, internal_ptr->u.syment._n._n_name, i);
1914               internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) newstring;
1915               internal_ptr->u.syment._n._n_n._n_zeroes = 0;
1916             }
1917           else if (internal_ptr->u.syment._n._n_n._n_offset == 0)
1918             internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) "";
1919           else if (!bfd_coff_symname_in_debug (abfd, &internal_ptr->u.syment))
1920             {
1921               /* Long name already.  Point symbol at the string in the
1922                  table.  */
1923               if (string_table == NULL)
1924                 {
1925                   string_table = _bfd_coff_read_string_table (abfd);
1926                   if (string_table == NULL)
1927                     return NULL;
1928                 }
1929               if (internal_ptr->u.syment._n._n_n._n_offset >= obj_coff_strings_len (abfd)
1930                   || string_table + internal_ptr->u.syment._n._n_n._n_offset < string_table)
1931                 internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) _("<corrupt>");
1932               else
1933                 internal_ptr->u.syment._n._n_n._n_offset =
1934                   ((bfd_hostptr_t)
1935                    (string_table
1936                     + internal_ptr->u.syment._n._n_n._n_offset));
1937             }
1938           else
1939             {
1940               /* Long name in debug section.  Very similar.  */
1941               if (debug_sec_data == NULL)
1942                 debug_sec_data = build_debug_section (abfd, & debug_sec);
1943               if (debug_sec_data != NULL)
1944                 {
1945                   BFD_ASSERT (debug_sec != NULL);
1946                   /* PR binutils/17512: Catch out of range offsets into the debug data.  */
1947                   if (internal_ptr->u.syment._n._n_n._n_offset > debug_sec->size
1948                       || debug_sec_data + internal_ptr->u.syment._n._n_n._n_offset < debug_sec_data)
1949                     internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) _("<corrupt>");
1950                   else
1951                     internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t)
1952                       (debug_sec_data + internal_ptr->u.syment._n._n_n._n_offset);
1953                 }
1954               else
1955                 internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) "";
1956             }
1957         }
1958       internal_ptr += internal_ptr->u.syment.n_numaux;
1959     }
1960
1961   obj_raw_syments (abfd) = internal;
1962   BFD_ASSERT (obj_raw_syment_count (abfd)
1963               == (unsigned int) (internal_ptr - internal));
1964
1965   return internal;
1966 }
1967
1968 long
1969 coff_get_reloc_upper_bound (bfd *abfd, sec_ptr asect)
1970 {
1971   if (bfd_get_format (abfd) != bfd_object)
1972     {
1973       bfd_set_error (bfd_error_invalid_operation);
1974       return -1;
1975     }
1976   return (asect->reloc_count + 1) * sizeof (arelent *);
1977 }
1978
1979 asymbol *
1980 coff_make_empty_symbol (bfd *abfd)
1981 {
1982   bfd_size_type amt = sizeof (coff_symbol_type);
1983   coff_symbol_type *new_symbol = (coff_symbol_type *) bfd_zalloc (abfd, amt);
1984
1985   if (new_symbol == NULL)
1986     return NULL;
1987   new_symbol->symbol.section = 0;
1988   new_symbol->native = NULL;
1989   new_symbol->lineno = NULL;
1990   new_symbol->done_lineno = FALSE;
1991   new_symbol->symbol.the_bfd = abfd;
1992
1993   return & new_symbol->symbol;
1994 }
1995
1996 /* Make a debugging symbol.  */
1997
1998 asymbol *
1999 coff_bfd_make_debug_symbol (bfd *abfd,
2000                             void * ptr ATTRIBUTE_UNUSED,
2001                             unsigned long sz ATTRIBUTE_UNUSED)
2002 {
2003   bfd_size_type amt = sizeof (coff_symbol_type);
2004   coff_symbol_type *new_symbol = (coff_symbol_type *) bfd_alloc (abfd, amt);
2005
2006   if (new_symbol == NULL)
2007     return NULL;
2008   /* @@ The 10 is a guess at a plausible maximum number of aux entries
2009      (but shouldn't be a constant).  */
2010   amt = sizeof (combined_entry_type) * 10;
2011   new_symbol->native = (combined_entry_type *) bfd_zalloc (abfd, amt);
2012   if (!new_symbol->native)
2013     return NULL;
2014   new_symbol->native->is_sym = TRUE;
2015   new_symbol->symbol.section = bfd_abs_section_ptr;
2016   new_symbol->symbol.flags = BSF_DEBUGGING;
2017   new_symbol->lineno = NULL;
2018   new_symbol->done_lineno = FALSE;
2019   new_symbol->symbol.the_bfd = abfd;
2020
2021   return & new_symbol->symbol;
2022 }
2023
2024 void
2025 coff_get_symbol_info (bfd *abfd, asymbol *symbol, symbol_info *ret)
2026 {
2027   bfd_symbol_info (symbol, ret);
2028
2029   if (coffsymbol (symbol)->native != NULL
2030       && coffsymbol (symbol)->native->fix_value
2031       && coffsymbol (symbol)->native->is_sym)
2032     ret->value = coffsymbol (symbol)->native->u.syment.n_value -
2033       (bfd_hostptr_t) obj_raw_syments (abfd);
2034 }
2035
2036 /* Print out information about COFF symbol.  */
2037
2038 void
2039 coff_print_symbol (bfd *abfd,
2040                    void * filep,
2041                    asymbol *symbol,
2042                    bfd_print_symbol_type how)
2043 {
2044   FILE * file = (FILE *) filep;
2045
2046   switch (how)
2047     {
2048     case bfd_print_symbol_name:
2049       fprintf (file, "%s", symbol->name);
2050       break;
2051
2052     case bfd_print_symbol_more:
2053       fprintf (file, "coff %s %s",
2054                coffsymbol (symbol)->native ? "n" : "g",
2055                coffsymbol (symbol)->lineno ? "l" : " ");
2056       break;
2057
2058     case bfd_print_symbol_all:
2059       if (coffsymbol (symbol)->native)
2060         {
2061           bfd_vma val;
2062           unsigned int aux;
2063           combined_entry_type *combined = coffsymbol (symbol)->native;
2064           combined_entry_type *root = obj_raw_syments (abfd);
2065           struct lineno_cache_entry *l = coffsymbol (symbol)->lineno;
2066
2067           fprintf (file, "[%3ld]", (long) (combined - root));
2068
2069           /* PR 17512: file: 079-33786-0.001:0.1.  */
2070           if (combined < obj_raw_syments (abfd)
2071               || combined >= obj_raw_syments (abfd) + obj_raw_syment_count (abfd))
2072             {
2073               fprintf (file, _("<corrupt info> %s"), symbol->name);
2074               break;
2075             }
2076
2077           BFD_ASSERT (combined->is_sym);
2078           if (! combined->fix_value)
2079             val = (bfd_vma) combined->u.syment.n_value;
2080           else
2081             val = combined->u.syment.n_value - (bfd_hostptr_t) root;
2082
2083           fprintf (file, "(sec %2d)(fl 0x%02x)(ty %3x)(scl %3d) (nx %d) 0x",
2084                    combined->u.syment.n_scnum,
2085                    combined->u.syment.n_flags,
2086                    combined->u.syment.n_type,
2087                    combined->u.syment.n_sclass,
2088                    combined->u.syment.n_numaux);
2089           bfd_fprintf_vma (abfd, file, val);
2090           fprintf (file, " %s", symbol->name);
2091
2092           for (aux = 0; aux < combined->u.syment.n_numaux; aux++)
2093             {
2094               combined_entry_type *auxp = combined + aux + 1;
2095               long tagndx;
2096
2097               BFD_ASSERT (! auxp->is_sym);
2098               if (auxp->fix_tag)
2099                 tagndx = auxp->u.auxent.x_sym.x_tagndx.p - root;
2100               else
2101                 tagndx = auxp->u.auxent.x_sym.x_tagndx.l;
2102
2103               fprintf (file, "\n");
2104
2105               if (bfd_coff_print_aux (abfd, file, root, combined, auxp, aux))
2106                 continue;
2107
2108               switch (combined->u.syment.n_sclass)
2109                 {
2110                 case C_FILE:
2111                   fprintf (file, "File ");
2112                   break;
2113
2114                 case C_STAT:
2115                   if (combined->u.syment.n_type == T_NULL)
2116                     /* Probably a section symbol ?  */
2117                     {
2118                       fprintf (file, "AUX scnlen 0x%lx nreloc %d nlnno %d",
2119                                (unsigned long) auxp->u.auxent.x_scn.x_scnlen,
2120                                auxp->u.auxent.x_scn.x_nreloc,
2121                                auxp->u.auxent.x_scn.x_nlinno);
2122                       if (auxp->u.auxent.x_scn.x_checksum != 0
2123                           || auxp->u.auxent.x_scn.x_associated != 0
2124                           || auxp->u.auxent.x_scn.x_comdat != 0)
2125                         fprintf (file, " checksum 0x%lx assoc %d comdat %d",
2126                                  auxp->u.auxent.x_scn.x_checksum,
2127                                  auxp->u.auxent.x_scn.x_associated,
2128                                  auxp->u.auxent.x_scn.x_comdat);
2129                       break;
2130                     }
2131                     /* Otherwise fall through.  */
2132                 case C_EXT:
2133                 case C_AIX_WEAKEXT:
2134                   if (ISFCN (combined->u.syment.n_type))
2135                     {
2136                       long next, llnos;
2137
2138                       if (auxp->fix_end)
2139                         next = (auxp->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.p
2140                                - root);
2141                       else
2142                         next = auxp->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.l;
2143                       llnos = auxp->u.auxent.x_sym.x_fcnary.x_fcn.x_lnnoptr;
2144                       fprintf (file,
2145                                "AUX tagndx %ld ttlsiz 0x%lx lnnos %ld next %ld",
2146                                tagndx,
2147                                (unsigned long) auxp->u.auxent.x_sym.x_misc.x_fsize,
2148                                llnos, next);
2149                       break;
2150                     }
2151                   /* Otherwise fall through.  */
2152                 default:
2153                   fprintf (file, "AUX lnno %d size 0x%x tagndx %ld",
2154                            auxp->u.auxent.x_sym.x_misc.x_lnsz.x_lnno,
2155                            auxp->u.auxent.x_sym.x_misc.x_lnsz.x_size,
2156                            tagndx);
2157                   if (auxp->fix_end)
2158                     fprintf (file, " endndx %ld",
2159                              ((long)
2160                               (auxp->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.p
2161                                - root)));
2162                   break;
2163                 }
2164             }
2165
2166           if (l)
2167             {
2168               fprintf (file, "\n%s :", l->u.sym->name);
2169               l++;
2170               while (l->line_number)
2171                 {
2172                   if (l->line_number > 0)
2173                     {
2174                       fprintf (file, "\n%4d : ", l->line_number);
2175                       bfd_fprintf_vma (abfd, file, l->u.offset + symbol->section->vma);
2176                     }
2177                   l++;
2178                 }
2179             }
2180         }
2181       else
2182         {
2183           bfd_print_symbol_vandf (abfd, (void *) file, symbol);
2184           fprintf (file, " %-5s %s %s %s",
2185                    symbol->section->name,
2186                    coffsymbol (symbol)->native ? "n" : "g",
2187                    coffsymbol (symbol)->lineno ? "l" : " ",
2188                    symbol->name);
2189         }
2190     }
2191 }
2192
2193 /* Return whether a symbol name implies a local symbol.  In COFF,
2194    local symbols generally start with ``.L''.  Most targets use this
2195    function for the is_local_label_name entry point, but some may
2196    override it.  */
2197
2198 bfd_boolean
2199 _bfd_coff_is_local_label_name (bfd *abfd ATTRIBUTE_UNUSED,
2200                                const char *name)
2201 {
2202   return name[0] == '.' && name[1] == 'L';
2203 }
2204
2205 /* Provided a BFD, a section and an offset (in bytes, not octets) into the
2206    section, calculate and return the name of the source file and the line
2207    nearest to the wanted location.  */
2208
2209 bfd_boolean
2210 coff_find_nearest_line_with_names (bfd *abfd,
2211                                    asymbol **symbols,
2212                                    asection *section,
2213                                    bfd_vma offset,
2214                                    const char **filename_ptr,
2215                                    const char **functionname_ptr,
2216                                    unsigned int *line_ptr,
2217                                    const struct dwarf_debug_section *debug_sections)
2218 {
2219   bfd_boolean found;
2220   unsigned int i;
2221   unsigned int line_base;
2222   coff_data_type *cof = coff_data (abfd);
2223   /* Run through the raw syments if available.  */
2224   combined_entry_type *p;
2225   combined_entry_type *pend;
2226   alent *l;
2227   struct coff_section_tdata *sec_data;
2228   bfd_size_type amt;
2229
2230   /* Before looking through the symbol table, try to use a .stab
2231      section to find the information.  */
2232   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
2233                                              &found, filename_ptr,
2234                                              functionname_ptr, line_ptr,
2235                                              &coff_data(abfd)->line_info))
2236     return FALSE;
2237
2238   if (found)
2239     return TRUE;
2240
2241   /* Also try examining DWARF2 debugging information.  */
2242   if (_bfd_dwarf2_find_nearest_line (abfd, symbols, NULL, section, offset,
2243                                      filename_ptr, functionname_ptr,
2244                                      line_ptr, NULL, debug_sections, 0,
2245                                      &coff_data(abfd)->dwarf2_find_line_info))
2246     return TRUE;
2247
2248   *filename_ptr = 0;
2249   *functionname_ptr = 0;
2250   *line_ptr = 0;
2251
2252   /* Don't try and find line numbers in a non coff file.  */
2253   if (!bfd_family_coff (abfd))
2254     return FALSE;
2255
2256   if (cof == NULL)
2257     return FALSE;
2258
2259   /* Find the first C_FILE symbol.  */
2260   p = cof->raw_syments;
2261   if (!p)
2262     return FALSE;
2263
2264   pend = p + cof->raw_syment_count;
2265   while (p < pend)
2266     {
2267       BFD_ASSERT (p->is_sym);
2268       if (p->u.syment.n_sclass == C_FILE)
2269         break;
2270       p += 1 + p->u.syment.n_numaux;
2271     }
2272
2273   if (p < pend)
2274     {
2275       bfd_vma sec_vma;
2276       bfd_vma maxdiff;
2277
2278       /* Look through the C_FILE symbols to find the best one.  */
2279       sec_vma = bfd_get_section_vma (abfd, section);
2280       *filename_ptr = (char *) p->u.syment._n._n_n._n_offset;
2281       maxdiff = (bfd_vma) 0 - (bfd_vma) 1;
2282       while (1)
2283         {
2284           bfd_vma file_addr;
2285           combined_entry_type *p2;
2286
2287           for (p2 = p + 1 + p->u.syment.n_numaux;
2288                p2 < pend;
2289                p2 += 1 + p2->u.syment.n_numaux)
2290             {
2291               BFD_ASSERT (p2->is_sym);
2292               if (p2->u.syment.n_scnum > 0
2293                   && (section
2294                       == coff_section_from_bfd_index (abfd,
2295                                                       p2->u.syment.n_scnum)))
2296                 break;
2297               if (p2->u.syment.n_sclass == C_FILE)
2298                 {
2299                   p2 = pend;
2300                   break;
2301                 }
2302             }
2303           if (p2 >= pend)
2304             break;
2305
2306           file_addr = (bfd_vma) p2->u.syment.n_value;
2307           /* PR 11512: Include the section address of the function name symbol.  */
2308           if (p2->u.syment.n_scnum > 0)
2309             file_addr += coff_section_from_bfd_index (abfd,
2310                                                       p2->u.syment.n_scnum)->vma;
2311           /* We use <= MAXDIFF here so that if we get a zero length
2312              file, we actually use the next file entry.  */
2313           if (p2 < pend
2314               && offset + sec_vma >= file_addr
2315               && offset + sec_vma - file_addr <= maxdiff)
2316             {
2317               *filename_ptr = (char *) p->u.syment._n._n_n._n_offset;
2318               maxdiff = offset + sec_vma - p2->u.syment.n_value;
2319             }
2320
2321           /* Avoid endless loops on erroneous files by ensuring that
2322              we always move forward in the file.  */
2323           if (p >= cof->raw_syments + p->u.syment.n_value)
2324             break;
2325
2326           p = cof->raw_syments + p->u.syment.n_value;
2327           if (p > pend || p->u.syment.n_sclass != C_FILE)
2328             break;
2329         }
2330     }
2331
2332   /* Now wander though the raw linenumbers of the section.  */
2333   /* If we have been called on this section before, and the offset we
2334      want is further down then we can prime the lookup loop.  */
2335   sec_data = coff_section_data (abfd, section);
2336   if (sec_data != NULL
2337       && sec_data->i > 0
2338       && offset >= sec_data->offset)
2339     {
2340       i = sec_data->i;
2341       *functionname_ptr = sec_data->function;
2342       line_base = sec_data->line_base;
2343     }
2344   else
2345     {
2346       i = 0;
2347       line_base = 0;
2348     }
2349
2350   if (section->lineno != NULL)
2351     {
2352       bfd_vma last_value = 0;
2353
2354       l = &section->lineno[i];
2355
2356       for (; i < section->lineno_count; i++)
2357         {
2358           if (l->line_number == 0)
2359             {
2360               /* Get the symbol this line number points at.  */
2361               coff_symbol_type *coff = (coff_symbol_type *) (l->u.sym);
2362               if (coff->symbol.value > offset)
2363                 break;
2364               *functionname_ptr = coff->symbol.name;
2365               last_value = coff->symbol.value;
2366               if (coff->native)
2367                 {
2368                   combined_entry_type *s = coff->native;
2369
2370                   BFD_ASSERT (s->is_sym);
2371                   s = s + 1 + s->u.syment.n_numaux;
2372
2373                   /* In XCOFF a debugging symbol can follow the
2374                      function symbol.  */
2375                   if (s->u.syment.n_scnum == N_DEBUG)
2376                     s = s + 1 + s->u.syment.n_numaux;
2377
2378                   /* S should now point to the .bf of the function.  */
2379                   if (s->u.syment.n_numaux)
2380                     {
2381                       /* The linenumber is stored in the auxent.  */
2382                       union internal_auxent *a = &((s + 1)->u.auxent);
2383
2384                       line_base = a->x_sym.x_misc.x_lnsz.x_lnno;
2385                       *line_ptr = line_base;
2386                     }
2387                 }
2388             }
2389           else
2390             {
2391               if (l->u.offset > offset)
2392                 break;
2393               *line_ptr = l->line_number + line_base - 1;
2394             }
2395           l++;
2396         }
2397
2398       /* If we fell off the end of the loop, then assume that this
2399          symbol has no line number info.  Otherwise, symbols with no
2400          line number info get reported with the line number of the
2401          last line of the last symbol which does have line number
2402          info.  We use 0x100 as a slop to account for cases where the
2403          last line has executable code.  */
2404       if (i >= section->lineno_count
2405           && last_value != 0
2406           && offset - last_value > 0x100)
2407         {
2408           *functionname_ptr = NULL;
2409           *line_ptr = 0;
2410         }
2411     }
2412
2413   /* Cache the results for the next call.  */
2414   if (sec_data == NULL && section->owner == abfd)
2415     {
2416       amt = sizeof (struct coff_section_tdata);
2417       section->used_by_bfd = bfd_zalloc (abfd, amt);
2418       sec_data = (struct coff_section_tdata *) section->used_by_bfd;
2419     }
2420   if (sec_data != NULL)
2421     {
2422       sec_data->offset = offset;
2423       sec_data->i = i - 1;
2424       sec_data->function = *functionname_ptr;
2425       sec_data->line_base = line_base;
2426     }
2427
2428   return TRUE;
2429 }
2430
2431 bfd_boolean
2432 coff_find_nearest_line (bfd *abfd,
2433                         asymbol **symbols,
2434                         asection *section,
2435                         bfd_vma offset,
2436                         const char **filename_ptr,
2437                         const char **functionname_ptr,
2438                         unsigned int *line_ptr,
2439                         unsigned int *discriminator_ptr)
2440 {
2441   if (discriminator_ptr)
2442     *discriminator_ptr = 0;
2443   return coff_find_nearest_line_with_names (abfd, symbols, section, offset,
2444                                             filename_ptr, functionname_ptr,
2445                                             line_ptr, dwarf_debug_sections);
2446 }
2447
2448 bfd_boolean
2449 coff_find_inliner_info (bfd *abfd,
2450                         const char **filename_ptr,
2451                         const char **functionname_ptr,
2452                         unsigned int *line_ptr)
2453 {
2454   bfd_boolean found;
2455
2456   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
2457                                          functionname_ptr, line_ptr,
2458                                          &coff_data(abfd)->dwarf2_find_line_info);
2459   return (found);
2460 }
2461
2462 int
2463 coff_sizeof_headers (bfd *abfd, struct bfd_link_info *info)
2464 {
2465   size_t size;
2466
2467   if (!info->relocatable)
2468     size = bfd_coff_filhsz (abfd) + bfd_coff_aoutsz (abfd);
2469   else
2470     size = bfd_coff_filhsz (abfd);
2471
2472   size += abfd->section_count * bfd_coff_scnhsz (abfd);
2473   return size;
2474 }
2475
2476 /* Change the class of a coff symbol held by BFD.  */
2477
2478 bfd_boolean
2479 bfd_coff_set_symbol_class (bfd *         abfd,
2480                            asymbol *     symbol,
2481                            unsigned int  symbol_class)
2482 {
2483   coff_symbol_type * csym;
2484
2485   csym = coff_symbol_from (symbol);
2486   if (csym == NULL)
2487     {
2488       bfd_set_error (bfd_error_invalid_operation);
2489       return FALSE;
2490     }
2491   else if (csym->native == NULL)
2492     {
2493       /* This is an alien symbol which no native coff backend data.
2494          We cheat here by creating a fake native entry for it and
2495          then filling in the class.  This code is based on that in
2496          coff_write_alien_symbol().  */
2497
2498       combined_entry_type * native;
2499       bfd_size_type amt = sizeof (* native);
2500
2501       native = (combined_entry_type *) bfd_zalloc (abfd, amt);
2502       if (native == NULL)
2503         return FALSE;
2504
2505       native->is_sym = TRUE;
2506       native->u.syment.n_type   = T_NULL;
2507       native->u.syment.n_sclass = symbol_class;
2508
2509       if (bfd_is_und_section (symbol->section))
2510         {
2511           native->u.syment.n_scnum = N_UNDEF;
2512           native->u.syment.n_value = symbol->value;
2513         }
2514       else if (bfd_is_com_section (symbol->section))
2515         {
2516           native->u.syment.n_scnum = N_UNDEF;
2517           native->u.syment.n_value = symbol->value;
2518         }
2519       else
2520         {
2521           native->u.syment.n_scnum =
2522             symbol->section->output_section->target_index;
2523           native->u.syment.n_value = (symbol->value
2524                                       + symbol->section->output_offset);
2525           if (! obj_pe (abfd))
2526             native->u.syment.n_value += symbol->section->output_section->vma;
2527
2528           /* Copy the any flags from the file header into the symbol.
2529              FIXME: Why?  */
2530           native->u.syment.n_flags = bfd_asymbol_bfd (& csym->symbol)->flags;
2531         }
2532
2533       csym->native = native;
2534     }
2535   else
2536     csym->native->u.syment.n_sclass = symbol_class;
2537
2538   return TRUE;
2539 }
2540
2541 bfd_boolean
2542 _bfd_coff_section_already_linked (bfd *abfd,
2543                                   asection *sec,
2544                                   struct bfd_link_info *info)
2545 {
2546   flagword flags;
2547   const char *name, *key;
2548   struct bfd_section_already_linked *l;
2549   struct bfd_section_already_linked_hash_entry *already_linked_list;
2550   struct coff_comdat_info *s_comdat;
2551
2552   flags = sec->flags;
2553   if ((flags & SEC_LINK_ONCE) == 0)
2554     return FALSE;
2555
2556   /* The COFF backend linker doesn't support group sections.  */
2557   if ((flags & SEC_GROUP) != 0)
2558     return FALSE;
2559
2560   name = bfd_get_section_name (abfd, sec);
2561   s_comdat = bfd_coff_get_comdat_section (abfd, sec);
2562
2563   if (s_comdat != NULL)
2564     key = s_comdat->name;
2565   else
2566     {
2567       if (CONST_STRNEQ (name, ".gnu.linkonce.")
2568           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
2569         key++;
2570       else
2571         /* FIXME: gcc as of 2011-09 emits sections like .text$<key>,
2572            .xdata$<key> and .pdata$<key> only the first of which has a
2573            comdat key.  Should these all match the LTO IR key?  */
2574         key = name;
2575     }
2576
2577   already_linked_list = bfd_section_already_linked_table_lookup (key);
2578
2579   for (l = already_linked_list->entry; l != NULL; l = l->next)
2580     {
2581       struct coff_comdat_info *l_comdat;
2582
2583       l_comdat = bfd_coff_get_comdat_section (l->sec->owner, l->sec);
2584
2585       /* The section names must match, and both sections must be
2586          comdat and have the same comdat name, or both sections must
2587          be non-comdat.  LTO IR plugin sections are an exception.  They
2588          are always named .gnu.linkonce.t.<key> (<key> is some string)
2589          and match any comdat section with comdat name of <key>, and
2590          any linkonce section with the same suffix, ie.
2591          .gnu.linkonce.*.<key>.  */
2592       if (((s_comdat != NULL) == (l_comdat != NULL)
2593            && strcmp (name, l->sec->name) == 0)
2594           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
2595         {
2596           /* The section has already been linked.  See if we should
2597              issue a warning.  */
2598           return _bfd_handle_already_linked (sec, l, info);
2599         }
2600     }
2601
2602   /* This is the first section with this name.  Record it.  */
2603   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
2604     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
2605   return FALSE;
2606 }