Upgrade libressl. 1/2
[dragonfly.git] / contrib / binutils-2.27 / bfd / coffgen.c
1 /* Support for the generic parts of COFF, for BFD.
2    Copyright (C) 1990-2016 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 (return_section->compress_status == COMPRESS_SECTION_DONE)
182             {
183               if (name[1] != 'z')
184                 {
185                   unsigned int len = strlen (name);
186
187                   new_name = bfd_alloc (abfd, len + 2);
188                   if (new_name == NULL)
189                     return FALSE;
190                   new_name[0] = '.';
191                   new_name[1] = 'z';
192                   memcpy (new_name + 2, name + 1, len);
193                 }
194             }
195          break;
196         case decompress:
197           if (!bfd_init_section_decompress_status (abfd, return_section))
198             {
199               (*_bfd_error_handler)
200                 (_("%B: unable to initialize decompress status for section %s"),
201                  abfd, name);
202               return FALSE;
203             }
204           if (name[1] == 'z')
205             {
206               unsigned int len = strlen (name);
207
208               new_name = bfd_alloc (abfd, len);
209               if (new_name == NULL)
210                 return FALSE;
211               new_name[0] = '.';
212               memcpy (new_name + 1, name + 2, len - 1);
213             }
214           break;
215         }
216       if (new_name != NULL)
217         bfd_rename_section (abfd, return_section, new_name);
218     }
219
220   return result;
221 }
222
223 /* Read in a COFF object and make it into a BFD.  This is used by
224    ECOFF as well.  */
225 const bfd_target *
226 coff_real_object_p (bfd *,
227                     unsigned,
228                     struct internal_filehdr *,
229                     struct internal_aouthdr *);
230 const bfd_target *
231 coff_real_object_p (bfd *abfd,
232                     unsigned nscns,
233                     struct internal_filehdr *internal_f,
234                     struct internal_aouthdr *internal_a)
235 {
236   flagword oflags = abfd->flags;
237   bfd_vma ostart = bfd_get_start_address (abfd);
238   void * tdata;
239   void * tdata_save;
240   bfd_size_type readsize;       /* Length of file_info.  */
241   unsigned int scnhsz;
242   char *external_sections;
243
244   if (!(internal_f->f_flags & F_RELFLG))
245     abfd->flags |= HAS_RELOC;
246   if ((internal_f->f_flags & F_EXEC))
247     abfd->flags |= EXEC_P;
248   if (!(internal_f->f_flags & F_LNNO))
249     abfd->flags |= HAS_LINENO;
250   if (!(internal_f->f_flags & F_LSYMS))
251     abfd->flags |= HAS_LOCALS;
252
253   /* FIXME: How can we set D_PAGED correctly?  */
254   if ((internal_f->f_flags & F_EXEC) != 0)
255     abfd->flags |= D_PAGED;
256
257   bfd_get_symcount (abfd) = internal_f->f_nsyms;
258   if (internal_f->f_nsyms)
259     abfd->flags |= HAS_SYMS;
260
261   if (internal_a != (struct internal_aouthdr *) NULL)
262     bfd_get_start_address (abfd) = internal_a->entry;
263   else
264     bfd_get_start_address (abfd) = 0;
265
266   /* Set up the tdata area.  ECOFF uses its own routine, and overrides
267      abfd->flags.  */
268   tdata_save = abfd->tdata.any;
269   tdata = bfd_coff_mkobject_hook (abfd, (void *) internal_f, (void *) internal_a);
270   if (tdata == NULL)
271     goto fail2;
272
273   scnhsz = bfd_coff_scnhsz (abfd);
274   readsize = (bfd_size_type) nscns * scnhsz;
275   external_sections = (char *) bfd_alloc (abfd, readsize);
276   if (!external_sections)
277     goto fail;
278
279   if (bfd_bread ((void *) external_sections, readsize, abfd) != readsize)
280     goto fail;
281
282   /* Set the arch/mach *before* swapping in sections; section header swapping
283      may depend on arch/mach info.  */
284   if (! bfd_coff_set_arch_mach_hook (abfd, (void *) internal_f))
285     goto fail;
286
287   /* Now copy data as required; construct all asections etc.  */
288   if (nscns != 0)
289     {
290       unsigned int i;
291       for (i = 0; i < nscns; i++)
292         {
293           struct internal_scnhdr tmp;
294           bfd_coff_swap_scnhdr_in (abfd,
295                                    (void *) (external_sections + i * scnhsz),
296                                    (void *) & tmp);
297           if (! make_a_section_from_file (abfd, &tmp, i + 1))
298             goto fail;
299         }
300     }
301
302   return abfd->xvec;
303
304  fail:
305   bfd_release (abfd, tdata);
306  fail2:
307   abfd->tdata.any = tdata_save;
308   abfd->flags = oflags;
309   bfd_get_start_address (abfd) = ostart;
310   return (const bfd_target *) NULL;
311 }
312
313 /* Turn a COFF file into a BFD, but fail with bfd_error_wrong_format if it is
314    not a COFF file.  This is also used by ECOFF.  */
315
316 const bfd_target *
317 coff_object_p (bfd *abfd)
318 {
319   bfd_size_type filhsz;
320   bfd_size_type aoutsz;
321   unsigned int nscns;
322   void * filehdr;
323   struct internal_filehdr internal_f;
324   struct internal_aouthdr internal_a;
325
326   /* Figure out how much to read.  */
327   filhsz = bfd_coff_filhsz (abfd);
328   aoutsz = bfd_coff_aoutsz (abfd);
329
330   filehdr = bfd_alloc (abfd, filhsz);
331   if (filehdr == NULL)
332     return NULL;
333   if (bfd_bread (filehdr, filhsz, abfd) != filhsz)
334     {
335       if (bfd_get_error () != bfd_error_system_call)
336         bfd_set_error (bfd_error_wrong_format);
337       bfd_release (abfd, filehdr);
338       return NULL;
339     }
340   bfd_coff_swap_filehdr_in (abfd, filehdr, &internal_f);
341   bfd_release (abfd, filehdr);
342
343   /* The XCOFF format has two sizes for the f_opthdr.  SMALL_AOUTSZ
344      (less than aoutsz) used in object files and AOUTSZ (equal to
345      aoutsz) in executables.  The bfd_coff_swap_aouthdr_in function
346      expects this header to be aoutsz bytes in length, so we use that
347      value in the call to bfd_alloc below.  But we must be careful to
348      only read in f_opthdr bytes in the call to bfd_bread.  We should
349      also attempt to catch corrupt or non-COFF binaries with a strange
350      value for f_opthdr.  */
351   if (! bfd_coff_bad_format_hook (abfd, &internal_f)
352       || internal_f.f_opthdr > aoutsz)
353     {
354       bfd_set_error (bfd_error_wrong_format);
355       return NULL;
356     }
357   nscns = internal_f.f_nscns;
358
359   if (internal_f.f_opthdr)
360     {
361       void * opthdr;
362
363       opthdr = bfd_alloc (abfd, aoutsz);
364       if (opthdr == NULL)
365         return NULL;
366       if (bfd_bread (opthdr, (bfd_size_type) internal_f.f_opthdr, abfd)
367           != internal_f.f_opthdr)
368         {
369           bfd_release (abfd, opthdr);
370           return NULL;
371         }
372       /* PR 17512: file: 11056-1136-0.004.  */
373       if (internal_f.f_opthdr < aoutsz)
374         memset (((char *) opthdr) + internal_f.f_opthdr, 0, aoutsz - internal_f.f_opthdr);
375
376       bfd_coff_swap_aouthdr_in (abfd, opthdr, (void *) &internal_a);
377       bfd_release (abfd, opthdr);
378     }
379
380   return coff_real_object_p (abfd, nscns, &internal_f,
381                              (internal_f.f_opthdr != 0
382                               ? &internal_a
383                               : (struct internal_aouthdr *) NULL));
384 }
385
386 /* Get the BFD section from a COFF symbol section number.  */
387
388 asection *
389 coff_section_from_bfd_index (bfd *abfd, int section_index)
390 {
391   struct bfd_section *answer = abfd->sections;
392
393   if (section_index == N_ABS)
394     return bfd_abs_section_ptr;
395   if (section_index == N_UNDEF)
396     return bfd_und_section_ptr;
397   if (section_index == N_DEBUG)
398     return bfd_abs_section_ptr;
399
400   while (answer)
401     {
402       if (answer->target_index == section_index)
403         return answer;
404       answer = answer->next;
405     }
406
407   /* We should not reach this point, but the SCO 3.2v4 /lib/libc_s.a
408      has a bad symbol table in biglitpow.o.  */
409   return bfd_und_section_ptr;
410 }
411
412 /* Get the upper bound of a COFF symbol table.  */
413
414 long
415 coff_get_symtab_upper_bound (bfd *abfd)
416 {
417   if (!bfd_coff_slurp_symbol_table (abfd))
418     return -1;
419
420   return (bfd_get_symcount (abfd) + 1) * (sizeof (coff_symbol_type *));
421 }
422
423 /* Canonicalize a COFF symbol table.  */
424
425 long
426 coff_canonicalize_symtab (bfd *abfd, asymbol **alocation)
427 {
428   unsigned int counter;
429   coff_symbol_type *symbase;
430   coff_symbol_type **location = (coff_symbol_type **) alocation;
431
432   if (!bfd_coff_slurp_symbol_table (abfd))
433     return -1;
434
435   symbase = obj_symbols (abfd);
436   counter = bfd_get_symcount (abfd);
437   while (counter-- > 0)
438     *location++ = symbase++;
439
440   *location = NULL;
441
442   return bfd_get_symcount (abfd);
443 }
444
445 /* Get the name of a symbol.  The caller must pass in a buffer of size
446    >= SYMNMLEN + 1.  */
447
448 const char *
449 _bfd_coff_internal_syment_name (bfd *abfd,
450                                 const struct internal_syment *sym,
451                                 char *buf)
452 {
453   /* FIXME: It's not clear this will work correctly if sizeof
454      (_n_zeroes) != 4.  */
455   if (sym->_n._n_n._n_zeroes != 0
456       || sym->_n._n_n._n_offset == 0)
457     {
458       memcpy (buf, sym->_n._n_name, SYMNMLEN);
459       buf[SYMNMLEN] = '\0';
460       return buf;
461     }
462   else
463     {
464       const char *strings;
465
466       BFD_ASSERT (sym->_n._n_n._n_offset >= STRING_SIZE_SIZE);
467       strings = obj_coff_strings (abfd);
468       if (strings == NULL)
469         {
470           strings = _bfd_coff_read_string_table (abfd);
471           if (strings == NULL)
472             return NULL;
473         }
474       /* PR 17910: Only check for string overflow if the length has been set.
475          Some DLLs, eg those produced by Visual Studio, may not set the length field.  */
476       if (obj_coff_strings_len (abfd) > 0
477           && sym->_n._n_n._n_offset >= obj_coff_strings_len (abfd))
478         return NULL;
479       return strings + sym->_n._n_n._n_offset;
480     }
481 }
482
483 /* Read in and swap the relocs.  This returns a buffer holding the
484    relocs for section SEC in file ABFD.  If CACHE is TRUE and
485    INTERNAL_RELOCS is NULL, the relocs read in will be saved in case
486    the function is called again.  If EXTERNAL_RELOCS is not NULL, it
487    is a buffer large enough to hold the unswapped relocs.  If
488    INTERNAL_RELOCS is not NULL, it is a buffer large enough to hold
489    the swapped relocs.  If REQUIRE_INTERNAL is TRUE, then the return
490    value must be INTERNAL_RELOCS.  The function returns NULL on error.  */
491
492 struct internal_reloc *
493 _bfd_coff_read_internal_relocs (bfd *abfd,
494                                 asection *sec,
495                                 bfd_boolean cache,
496                                 bfd_byte *external_relocs,
497                                 bfd_boolean require_internal,
498                                 struct internal_reloc *internal_relocs)
499 {
500   bfd_size_type relsz;
501   bfd_byte *free_external = NULL;
502   struct internal_reloc *free_internal = NULL;
503   bfd_byte *erel;
504   bfd_byte *erel_end;
505   struct internal_reloc *irel;
506   bfd_size_type amt;
507
508   if (sec->reloc_count == 0)
509     return internal_relocs;     /* Nothing to do.  */
510
511   if (coff_section_data (abfd, sec) != NULL
512       && coff_section_data (abfd, sec)->relocs != NULL)
513     {
514       if (! require_internal)
515         return coff_section_data (abfd, sec)->relocs;
516       memcpy (internal_relocs, coff_section_data (abfd, sec)->relocs,
517               sec->reloc_count * sizeof (struct internal_reloc));
518       return internal_relocs;
519     }
520
521   relsz = bfd_coff_relsz (abfd);
522
523   amt = sec->reloc_count * relsz;
524   if (external_relocs == NULL)
525     {
526       free_external = (bfd_byte *) bfd_malloc (amt);
527       if (free_external == NULL)
528         goto error_return;
529       external_relocs = free_external;
530     }
531
532   if (bfd_seek (abfd, sec->rel_filepos, SEEK_SET) != 0
533       || bfd_bread (external_relocs, amt, abfd) != amt)
534     goto error_return;
535
536   if (internal_relocs == NULL)
537     {
538       amt = sec->reloc_count;
539       amt *= sizeof (struct internal_reloc);
540       free_internal = (struct internal_reloc *) bfd_malloc (amt);
541       if (free_internal == NULL)
542         goto error_return;
543       internal_relocs = free_internal;
544     }
545
546   /* Swap in the relocs.  */
547   erel = external_relocs;
548   erel_end = erel + relsz * sec->reloc_count;
549   irel = internal_relocs;
550   for (; erel < erel_end; erel += relsz, irel++)
551     bfd_coff_swap_reloc_in (abfd, (void *) erel, (void *) irel);
552
553   if (free_external != NULL)
554     {
555       free (free_external);
556       free_external = NULL;
557     }
558
559   if (cache && free_internal != NULL)
560     {
561       if (coff_section_data (abfd, sec) == NULL)
562         {
563           amt = sizeof (struct coff_section_tdata);
564           sec->used_by_bfd = bfd_zalloc (abfd, amt);
565           if (sec->used_by_bfd == NULL)
566             goto error_return;
567           coff_section_data (abfd, sec)->contents = NULL;
568         }
569       coff_section_data (abfd, sec)->relocs = free_internal;
570     }
571
572   return internal_relocs;
573
574  error_return:
575   if (free_external != NULL)
576     free (free_external);
577   if (free_internal != NULL)
578     free (free_internal);
579   return NULL;
580 }
581
582 /* Set lineno_count for the output sections of a COFF file.  */
583
584 int
585 coff_count_linenumbers (bfd *abfd)
586 {
587   unsigned int limit = bfd_get_symcount (abfd);
588   unsigned int i;
589   int total = 0;
590   asymbol **p;
591   asection *s;
592
593   if (limit == 0)
594     {
595       /* This may be from the backend linker, in which case the
596          lineno_count in the sections is correct.  */
597       for (s = abfd->sections; s != NULL; s = s->next)
598         total += s->lineno_count;
599       return total;
600     }
601
602   for (s = abfd->sections; s != NULL; s = s->next)
603     BFD_ASSERT (s->lineno_count == 0);
604
605   for (p = abfd->outsymbols, i = 0; i < limit; i++, p++)
606     {
607       asymbol *q_maybe = *p;
608
609       if (bfd_family_coff (bfd_asymbol_bfd (q_maybe)))
610         {
611           coff_symbol_type *q = coffsymbol (q_maybe);
612
613           /* The AIX 4.1 compiler can sometimes generate line numbers
614              attached to debugging symbols.  We try to simply ignore
615              those here.  */
616           if (q->lineno != NULL
617               && q->symbol.section->owner != NULL)
618             {
619               /* This symbol has line numbers.  Increment the owning
620                  section's linenumber count.  */
621               alent *l = q->lineno;
622
623               do
624                 {
625                   asection * sec = q->symbol.section->output_section;
626
627                   /* Do not try to update fields in read-only sections.  */
628                   if (! bfd_is_const_section (sec))
629                     sec->lineno_count ++;
630
631                   ++total;
632                   ++l;
633                 }
634               while (l->line_number != 0);
635             }
636         }
637     }
638
639   return total;
640 }
641
642 static void
643 fixup_symbol_value (bfd *abfd,
644                     coff_symbol_type *coff_symbol_ptr,
645                     struct internal_syment *syment)
646 {
647   /* Normalize the symbol flags.  */
648   if (coff_symbol_ptr->symbol.section
649       && bfd_is_com_section (coff_symbol_ptr->symbol.section))
650     {
651       /* A common symbol is undefined with a value.  */
652       syment->n_scnum = N_UNDEF;
653       syment->n_value = coff_symbol_ptr->symbol.value;
654     }
655   else if ((coff_symbol_ptr->symbol.flags & BSF_DEBUGGING) != 0
656            && (coff_symbol_ptr->symbol.flags & BSF_DEBUGGING_RELOC) == 0)
657     {
658       syment->n_value = coff_symbol_ptr->symbol.value;
659     }
660   else if (bfd_is_und_section (coff_symbol_ptr->symbol.section))
661     {
662       syment->n_scnum = N_UNDEF;
663       syment->n_value = 0;
664     }
665   /* FIXME: Do we need to handle the absolute section here?  */
666   else
667     {
668       if (coff_symbol_ptr->symbol.section)
669         {
670           syment->n_scnum =
671             coff_symbol_ptr->symbol.section->output_section->target_index;
672
673           syment->n_value = (coff_symbol_ptr->symbol.value
674                              + coff_symbol_ptr->symbol.section->output_offset);
675           if (! obj_pe (abfd))
676             {
677               syment->n_value += (syment->n_sclass == C_STATLAB)
678                 ? coff_symbol_ptr->symbol.section->output_section->lma
679                 : coff_symbol_ptr->symbol.section->output_section->vma;
680             }
681         }
682       else
683         {
684           BFD_ASSERT (0);
685           /* This can happen, but I don't know why yet (steve@cygnus.com) */
686           syment->n_scnum = N_ABS;
687           syment->n_value = coff_symbol_ptr->symbol.value;
688         }
689     }
690 }
691
692 /* Run through all the symbols in the symbol table and work out what
693    their indexes into the symbol table will be when output.
694
695    Coff requires that each C_FILE symbol points to the next one in the
696    chain, and that the last one points to the first external symbol. We
697    do that here too.  */
698
699 bfd_boolean
700 coff_renumber_symbols (bfd *bfd_ptr, int *first_undef)
701 {
702   unsigned int symbol_count = bfd_get_symcount (bfd_ptr);
703   asymbol **symbol_ptr_ptr = bfd_ptr->outsymbols;
704   unsigned int native_index = 0;
705   struct internal_syment *last_file = NULL;
706   unsigned int symbol_index;
707
708   /* COFF demands that undefined symbols come after all other symbols.
709      Since we don't need to impose this extra knowledge on all our
710      client programs, deal with that here.  Sort the symbol table;
711      just move the undefined symbols to the end, leaving the rest
712      alone.  The O'Reilly book says that defined global symbols come
713      at the end before the undefined symbols, so we do that here as
714      well.  */
715   /* @@ Do we have some condition we could test for, so we don't always
716      have to do this?  I don't think relocatability is quite right, but
717      I'm not certain.  [raeburn:19920508.1711EST]  */
718   {
719     asymbol **newsyms;
720     unsigned int i;
721     bfd_size_type amt;
722
723     amt = sizeof (asymbol *) * ((bfd_size_type) symbol_count + 1);
724     newsyms = (asymbol **) bfd_alloc (bfd_ptr, amt);
725     if (!newsyms)
726       return FALSE;
727     bfd_ptr->outsymbols = newsyms;
728     for (i = 0; i < symbol_count; i++)
729       if ((symbol_ptr_ptr[i]->flags & BSF_NOT_AT_END) != 0
730           || (!bfd_is_und_section (symbol_ptr_ptr[i]->section)
731               && !bfd_is_com_section (symbol_ptr_ptr[i]->section)
732               && ((symbol_ptr_ptr[i]->flags & BSF_FUNCTION) != 0
733                   || ((symbol_ptr_ptr[i]->flags & (BSF_GLOBAL | BSF_WEAK))
734                       == 0))))
735         *newsyms++ = symbol_ptr_ptr[i];
736
737     for (i = 0; i < symbol_count; i++)
738       if ((symbol_ptr_ptr[i]->flags & BSF_NOT_AT_END) == 0
739           && !bfd_is_und_section (symbol_ptr_ptr[i]->section)
740           && (bfd_is_com_section (symbol_ptr_ptr[i]->section)
741               || ((symbol_ptr_ptr[i]->flags & BSF_FUNCTION) == 0
742                   && ((symbol_ptr_ptr[i]->flags & (BSF_GLOBAL | BSF_WEAK))
743                       != 0))))
744         *newsyms++ = symbol_ptr_ptr[i];
745
746     *first_undef = newsyms - bfd_ptr->outsymbols;
747
748     for (i = 0; i < symbol_count; i++)
749       if ((symbol_ptr_ptr[i]->flags & BSF_NOT_AT_END) == 0
750           && bfd_is_und_section (symbol_ptr_ptr[i]->section))
751         *newsyms++ = symbol_ptr_ptr[i];
752     *newsyms = (asymbol *) NULL;
753     symbol_ptr_ptr = bfd_ptr->outsymbols;
754   }
755
756   for (symbol_index = 0; symbol_index < symbol_count; symbol_index++)
757     {
758       coff_symbol_type *coff_symbol_ptr;
759
760       coff_symbol_ptr = coff_symbol_from (symbol_ptr_ptr[symbol_index]);
761       symbol_ptr_ptr[symbol_index]->udata.i = symbol_index;
762       if (coff_symbol_ptr && coff_symbol_ptr->native)
763         {
764           combined_entry_type *s = coff_symbol_ptr->native;
765           int i;
766
767           BFD_ASSERT (s->is_sym);
768           if (s->u.syment.n_sclass == C_FILE)
769             {
770               if (last_file != NULL)
771                 last_file->n_value = native_index;
772               last_file = &(s->u.syment);
773             }
774           else
775             /* Modify the symbol values according to their section and
776                type.  */
777             fixup_symbol_value (bfd_ptr, coff_symbol_ptr, &(s->u.syment));
778
779           for (i = 0; i < s->u.syment.n_numaux + 1; i++)
780             s[i].offset = native_index++;
781         }
782       else
783         native_index++;
784     }
785
786   obj_conv_table_size (bfd_ptr) = native_index;
787
788   return TRUE;
789 }
790
791 /* Run thorough the symbol table again, and fix it so that all
792    pointers to entries are changed to the entries' index in the output
793    symbol table.  */
794
795 void
796 coff_mangle_symbols (bfd *bfd_ptr)
797 {
798   unsigned int symbol_count = bfd_get_symcount (bfd_ptr);
799   asymbol **symbol_ptr_ptr = bfd_ptr->outsymbols;
800   unsigned int symbol_index;
801
802   for (symbol_index = 0; symbol_index < symbol_count; symbol_index++)
803     {
804       coff_symbol_type *coff_symbol_ptr;
805
806       coff_symbol_ptr = coff_symbol_from (symbol_ptr_ptr[symbol_index]);
807       if (coff_symbol_ptr && coff_symbol_ptr->native)
808         {
809           int i;
810           combined_entry_type *s = coff_symbol_ptr->native;
811
812           BFD_ASSERT (s->is_sym);
813           if (s->fix_value)
814             {
815               /* FIXME: We should use a union here.  */
816               s->u.syment.n_value =
817                 (bfd_hostptr_t) ((combined_entry_type *)
818                           ((bfd_hostptr_t) s->u.syment.n_value))->offset;
819               s->fix_value = 0;
820             }
821           if (s->fix_line)
822             {
823               /* The value is the offset into the line number entries
824                  for the symbol's section.  On output, the symbol's
825                  section should be N_DEBUG.  */
826               s->u.syment.n_value =
827                 (coff_symbol_ptr->symbol.section->output_section->line_filepos
828                  + s->u.syment.n_value * bfd_coff_linesz (bfd_ptr));
829               coff_symbol_ptr->symbol.section =
830                 coff_section_from_bfd_index (bfd_ptr, N_DEBUG);
831               BFD_ASSERT (coff_symbol_ptr->symbol.flags & BSF_DEBUGGING);
832             }
833           for (i = 0; i < s->u.syment.n_numaux; i++)
834             {
835               combined_entry_type *a = s + i + 1;
836
837               BFD_ASSERT (! a->is_sym);
838               if (a->fix_tag)
839                 {
840                   a->u.auxent.x_sym.x_tagndx.l =
841                     a->u.auxent.x_sym.x_tagndx.p->offset;
842                   a->fix_tag = 0;
843                 }
844               if (a->fix_end)
845                 {
846                   a->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.l =
847                     a->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.p->offset;
848                   a->fix_end = 0;
849                 }
850               if (a->fix_scnlen)
851                 {
852                   a->u.auxent.x_csect.x_scnlen.l =
853                     a->u.auxent.x_csect.x_scnlen.p->offset;
854                   a->fix_scnlen = 0;
855                 }
856             }
857         }
858     }
859 }
860
861 static void
862 coff_fix_symbol_name (bfd *abfd,
863                       asymbol *symbol,
864                       combined_entry_type *native,
865                       bfd_size_type *string_size_p,
866                       asection **debug_string_section_p,
867                       bfd_size_type *debug_string_size_p)
868 {
869   unsigned int name_length;
870   union internal_auxent *auxent;
871   char *name = (char *) (symbol->name);
872
873   if (name == NULL)
874     {
875       /* COFF symbols always have names, so we'll make one up.  */
876       symbol->name = "strange";
877       name = (char *) symbol->name;
878     }
879   name_length = strlen (name);
880
881   BFD_ASSERT (native->is_sym);
882   if (native->u.syment.n_sclass == C_FILE
883       && native->u.syment.n_numaux > 0)
884     {
885       unsigned int filnmlen;
886
887       if (bfd_coff_force_symnames_in_strings (abfd))
888         {
889           native->u.syment._n._n_n._n_offset =
890               (*string_size_p + STRING_SIZE_SIZE);
891           native->u.syment._n._n_n._n_zeroes = 0;
892           *string_size_p += 6;  /* strlen(".file") + 1 */
893         }
894       else
895         strncpy (native->u.syment._n._n_name, ".file", SYMNMLEN);
896
897       BFD_ASSERT (! (native + 1)->is_sym);
898       auxent = &(native + 1)->u.auxent;
899
900       filnmlen = bfd_coff_filnmlen (abfd);
901
902       if (bfd_coff_long_filenames (abfd))
903         {
904           if (name_length <= filnmlen)
905             strncpy (auxent->x_file.x_fname, name, filnmlen);
906           else
907             {
908               auxent->x_file.x_n.x_offset = *string_size_p + STRING_SIZE_SIZE;
909               auxent->x_file.x_n.x_zeroes = 0;
910               *string_size_p += name_length + 1;
911             }
912         }
913       else
914         {
915           strncpy (auxent->x_file.x_fname, name, filnmlen);
916           if (name_length > filnmlen)
917             name[filnmlen] = '\0';
918         }
919     }
920   else
921     {
922       if (name_length <= SYMNMLEN && !bfd_coff_force_symnames_in_strings (abfd))
923         /* This name will fit into the symbol neatly.  */
924         strncpy (native->u.syment._n._n_name, symbol->name, SYMNMLEN);
925
926       else if (!bfd_coff_symname_in_debug (abfd, &native->u.syment))
927         {
928           native->u.syment._n._n_n._n_offset = (*string_size_p
929                                                 + STRING_SIZE_SIZE);
930           native->u.syment._n._n_n._n_zeroes = 0;
931           *string_size_p += name_length + 1;
932         }
933       else
934         {
935           file_ptr filepos;
936           bfd_byte buf[4];
937           int prefix_len = bfd_coff_debug_string_prefix_length (abfd);
938
939           /* This name should be written into the .debug section.  For
940              some reason each name is preceded by a two byte length
941              and also followed by a null byte.  FIXME: We assume that
942              the .debug section has already been created, and that it
943              is large enough.  */
944           if (*debug_string_section_p == (asection *) NULL)
945             *debug_string_section_p = bfd_get_section_by_name (abfd, ".debug");
946           filepos = bfd_tell (abfd);
947           if (prefix_len == 4)
948             bfd_put_32 (abfd, (bfd_vma) (name_length + 1), buf);
949           else
950             bfd_put_16 (abfd, (bfd_vma) (name_length + 1), buf);
951
952           if (!bfd_set_section_contents (abfd,
953                                          *debug_string_section_p,
954                                          (void *) buf,
955                                          (file_ptr) *debug_string_size_p,
956                                          (bfd_size_type) prefix_len)
957               || !bfd_set_section_contents (abfd,
958                                             *debug_string_section_p,
959                                             (void *) symbol->name,
960                                             (file_ptr) (*debug_string_size_p
961                                                         + prefix_len),
962                                             (bfd_size_type) name_length + 1))
963             abort ();
964           if (bfd_seek (abfd, filepos, SEEK_SET) != 0)
965             abort ();
966           native->u.syment._n._n_n._n_offset =
967               *debug_string_size_p + prefix_len;
968           native->u.syment._n._n_n._n_zeroes = 0;
969           *debug_string_size_p += name_length + 1 + prefix_len;
970         }
971     }
972 }
973
974 /* We need to keep track of the symbol index so that when we write out
975    the relocs we can get the index for a symbol.  This method is a
976    hack.  FIXME.  */
977
978 #define set_index(symbol, idx)  ((symbol)->udata.i = (idx))
979
980 /* Write a symbol out to a COFF file.  */
981
982 static bfd_boolean
983 coff_write_symbol (bfd *abfd,
984                    asymbol *symbol,
985                    combined_entry_type *native,
986                    bfd_vma *written,
987                    bfd_size_type *string_size_p,
988                    asection **debug_string_section_p,
989                    bfd_size_type *debug_string_size_p)
990 {
991   unsigned int numaux = native->u.syment.n_numaux;
992   int type = native->u.syment.n_type;
993   int n_sclass = (int) native->u.syment.n_sclass;
994   asection *output_section = symbol->section->output_section
995                                ? symbol->section->output_section
996                                : symbol->section;
997   void * buf;
998   bfd_size_type symesz;
999
1000   BFD_ASSERT (native->is_sym);
1001
1002   if (native->u.syment.n_sclass == C_FILE)
1003     symbol->flags |= BSF_DEBUGGING;
1004
1005   if (symbol->flags & BSF_DEBUGGING
1006       && bfd_is_abs_section (symbol->section))
1007     native->u.syment.n_scnum = N_DEBUG;
1008
1009   else if (bfd_is_abs_section (symbol->section))
1010     native->u.syment.n_scnum = N_ABS;
1011
1012   else if (bfd_is_und_section (symbol->section))
1013     native->u.syment.n_scnum = N_UNDEF;
1014
1015   else
1016     native->u.syment.n_scnum =
1017       output_section->target_index;
1018
1019   coff_fix_symbol_name (abfd, symbol, native, string_size_p,
1020                         debug_string_section_p, debug_string_size_p);
1021
1022   symesz = bfd_coff_symesz (abfd);
1023   buf = bfd_alloc (abfd, symesz);
1024   if (!buf)
1025     return FALSE;
1026   bfd_coff_swap_sym_out (abfd, &native->u.syment, buf);
1027   if (bfd_bwrite (buf, symesz, abfd) != symesz)
1028     return FALSE;
1029   bfd_release (abfd, buf);
1030
1031   if (native->u.syment.n_numaux > 0)
1032     {
1033       bfd_size_type auxesz;
1034       unsigned int j;
1035
1036       auxesz = bfd_coff_auxesz (abfd);
1037       buf = bfd_alloc (abfd, auxesz);
1038       if (!buf)
1039         return FALSE;
1040       for (j = 0; j < native->u.syment.n_numaux; j++)
1041         {
1042           BFD_ASSERT (! (native + j + 1)->is_sym);
1043           bfd_coff_swap_aux_out (abfd,
1044                                  &((native + j + 1)->u.auxent),
1045                                  type, n_sclass, (int) j,
1046                                  native->u.syment.n_numaux,
1047                                  buf);
1048           if (bfd_bwrite (buf, auxesz, abfd) != auxesz)
1049             return FALSE;
1050         }
1051       bfd_release (abfd, buf);
1052     }
1053
1054   /* Store the index for use when we write out the relocs.  */
1055   set_index (symbol, *written);
1056
1057   *written += numaux + 1;
1058   return TRUE;
1059 }
1060
1061 /* Write out a symbol to a COFF file that does not come from a COFF
1062    file originally.  This symbol may have been created by the linker,
1063    or we may be linking a non COFF file to a COFF file.  */
1064
1065 bfd_boolean
1066 coff_write_alien_symbol (bfd *abfd,
1067                          asymbol *symbol,
1068                          struct internal_syment *isym,
1069                          union internal_auxent *iaux,
1070                          bfd_vma *written,
1071                          bfd_size_type *string_size_p,
1072                          asection **debug_string_section_p,
1073                          bfd_size_type *debug_string_size_p)
1074 {
1075   combined_entry_type *native;
1076   combined_entry_type dummy[2];
1077   asection *output_section = symbol->section->output_section
1078                                ? symbol->section->output_section
1079                                : symbol->section;
1080   struct bfd_link_info *link_info = coff_data (abfd)->link_info;
1081   bfd_boolean ret;
1082
1083   if ((!link_info || link_info->strip_discarded)
1084       && !bfd_is_abs_section (symbol->section)
1085       && symbol->section->output_section == bfd_abs_section_ptr)
1086     {
1087       symbol->name = "";
1088       if (isym != NULL)
1089         memset (isym, 0, sizeof (*isym));
1090       return TRUE;
1091     }
1092   native = dummy;
1093   native->is_sym = TRUE;
1094   native[1].is_sym = FALSE;
1095   native->u.syment.n_type = T_NULL;
1096   native->u.syment.n_flags = 0;
1097   native->u.syment.n_numaux = 0;
1098   if (bfd_is_und_section (symbol->section))
1099     {
1100       native->u.syment.n_scnum = N_UNDEF;
1101       native->u.syment.n_value = symbol->value;
1102     }
1103   else if (bfd_is_com_section (symbol->section))
1104     {
1105       native->u.syment.n_scnum = N_UNDEF;
1106       native->u.syment.n_value = symbol->value;
1107     }
1108   else if (symbol->flags & BSF_FILE)
1109     {
1110       native->u.syment.n_scnum = N_DEBUG;
1111       native->u.syment.n_numaux = 1;
1112     }
1113   else if (symbol->flags & BSF_DEBUGGING)
1114     {
1115       /* There isn't much point to writing out a debugging symbol
1116          unless we are prepared to convert it into COFF debugging
1117          format.  So, we just ignore them.  We must clobber the symbol
1118          name to keep it from being put in the string table.  */
1119       symbol->name = "";
1120       if (isym != NULL)
1121         memset (isym, 0, sizeof (*isym));
1122       return TRUE;
1123     }
1124   else
1125     {
1126       native->u.syment.n_scnum = output_section->target_index;
1127       native->u.syment.n_value = (symbol->value
1128                                   + symbol->section->output_offset);
1129       if (! obj_pe (abfd))
1130         native->u.syment.n_value += output_section->vma;
1131
1132       /* Copy the any flags from the file header into the symbol.
1133          FIXME: Why?  */
1134       {
1135         coff_symbol_type *c = coff_symbol_from (symbol);
1136         if (c != (coff_symbol_type *) NULL)
1137           native->u.syment.n_flags = bfd_asymbol_bfd (&c->symbol)->flags;
1138       }
1139     }
1140
1141   native->u.syment.n_type = 0;
1142   if (symbol->flags & BSF_FILE)
1143     native->u.syment.n_sclass = C_FILE;
1144   else if (symbol->flags & BSF_LOCAL)
1145     native->u.syment.n_sclass = C_STAT;
1146   else if (symbol->flags & BSF_WEAK)
1147     native->u.syment.n_sclass = obj_pe (abfd) ? C_NT_WEAK : C_WEAKEXT;
1148   else
1149     native->u.syment.n_sclass = C_EXT;
1150
1151   ret = coff_write_symbol (abfd, symbol, native, written, string_size_p,
1152                            debug_string_section_p, debug_string_size_p);
1153   if (isym != NULL)
1154     *isym = native->u.syment;
1155   if (iaux != NULL && native->u.syment.n_numaux)
1156     *iaux = native[1].u.auxent;
1157   return ret;
1158 }
1159
1160 /* Write a native symbol to a COFF file.  */
1161
1162 static bfd_boolean
1163 coff_write_native_symbol (bfd *abfd,
1164                           coff_symbol_type *symbol,
1165                           bfd_vma *written,
1166                           bfd_size_type *string_size_p,
1167                           asection **debug_string_section_p,
1168                           bfd_size_type *debug_string_size_p)
1169 {
1170   combined_entry_type *native = symbol->native;
1171   alent *lineno = symbol->lineno;
1172   struct bfd_link_info *link_info = coff_data (abfd)->link_info;
1173
1174   if ((!link_info || link_info->strip_discarded)
1175       && !bfd_is_abs_section (symbol->symbol.section)
1176       && symbol->symbol.section->output_section == bfd_abs_section_ptr)
1177     {
1178       symbol->symbol.name = "";
1179       return TRUE;
1180     }
1181
1182   BFD_ASSERT (native->is_sym);
1183   /* If this symbol has an associated line number, we must store the
1184      symbol index in the line number field.  We also tag the auxent to
1185      point to the right place in the lineno table.  */
1186   if (lineno && !symbol->done_lineno && symbol->symbol.section->owner != NULL)
1187     {
1188       unsigned int count = 0;
1189
1190       lineno[count].u.offset = *written;
1191       if (native->u.syment.n_numaux)
1192         {
1193           union internal_auxent *a = &((native + 1)->u.auxent);
1194
1195           a->x_sym.x_fcnary.x_fcn.x_lnnoptr =
1196             symbol->symbol.section->output_section->moving_line_filepos;
1197         }
1198
1199       /* Count and relocate all other linenumbers.  */
1200       count++;
1201       while (lineno[count].line_number != 0)
1202         {
1203           lineno[count].u.offset +=
1204             (symbol->symbol.section->output_section->vma
1205              + symbol->symbol.section->output_offset);
1206           count++;
1207         }
1208       symbol->done_lineno = TRUE;
1209
1210       if (! bfd_is_const_section (symbol->symbol.section->output_section))
1211         symbol->symbol.section->output_section->moving_line_filepos +=
1212           count * bfd_coff_linesz (abfd);
1213     }
1214
1215   return coff_write_symbol (abfd, &(symbol->symbol), native, written,
1216                             string_size_p, debug_string_section_p,
1217                             debug_string_size_p);
1218 }
1219
1220 static void
1221 null_error_handler (const char * fmt ATTRIBUTE_UNUSED, ...)
1222 {
1223 }
1224
1225 /* Write out the COFF symbols.  */
1226
1227 bfd_boolean
1228 coff_write_symbols (bfd *abfd)
1229 {
1230   bfd_size_type string_size;
1231   asection *debug_string_section;
1232   bfd_size_type debug_string_size;
1233   unsigned int i;
1234   unsigned int limit = bfd_get_symcount (abfd);
1235   bfd_vma written = 0;
1236   asymbol **p;
1237
1238   string_size = 0;
1239   debug_string_section = NULL;
1240   debug_string_size = 0;
1241
1242   /* If this target supports long section names, they must be put into
1243      the string table.  This is supported by PE.  This code must
1244      handle section names just as they are handled in
1245      coff_write_object_contents.  */
1246   if (bfd_coff_long_section_names (abfd))
1247     {
1248       asection *o;
1249
1250       for (o = abfd->sections; o != NULL; o = o->next)
1251         {
1252           size_t len;
1253
1254           len = strlen (o->name);
1255           if (len > SCNNMLEN)
1256             string_size += len + 1;
1257         }
1258     }
1259
1260   /* Seek to the right place.  */
1261   if (bfd_seek (abfd, obj_sym_filepos (abfd), SEEK_SET) != 0)
1262     return FALSE;
1263
1264   /* Output all the symbols we have.  */
1265   written = 0;
1266   for (p = abfd->outsymbols, i = 0; i < limit; i++, p++)
1267     {
1268       asymbol *symbol = *p;
1269       coff_symbol_type *c_symbol = coff_symbol_from (symbol);
1270
1271       if (c_symbol == (coff_symbol_type *) NULL
1272           || c_symbol->native == (combined_entry_type *) NULL)
1273         {
1274           if (!coff_write_alien_symbol (abfd, symbol, NULL, NULL, &written,
1275                                         &string_size, &debug_string_section,
1276                                         &debug_string_size))
1277             return FALSE;
1278         }
1279       else
1280         {
1281           if (coff_backend_info (abfd)->_bfd_coff_classify_symbol != NULL)
1282             {
1283               bfd_error_handler_type current_error_handler;
1284               enum coff_symbol_classification sym_class;
1285               unsigned char *n_sclass;
1286
1287               /* Suppress error reporting by bfd_coff_classify_symbol.
1288                  Error messages can be generated when we are processing a local
1289                  symbol which has no associated section and we do not have to
1290                  worry about this, all we need to know is that it is local.  */
1291               current_error_handler = bfd_set_error_handler (null_error_handler);
1292               BFD_ASSERT (c_symbol->native->is_sym);
1293               sym_class = bfd_coff_classify_symbol (abfd,
1294                                                     &c_symbol->native->u.syment);
1295               (void) bfd_set_error_handler (current_error_handler);
1296
1297               n_sclass = &c_symbol->native->u.syment.n_sclass;
1298
1299               /* If the symbol class has been changed (eg objcopy/ld script/etc)
1300                  we cannot retain the existing sclass from the original symbol.
1301                  Weak symbols only have one valid sclass, so just set it always.
1302                  If it is not local class and should be, set it C_STAT.
1303                  If it is global and not classified as global, or if it is
1304                  weak (which is also classified as global), set it C_EXT.  */
1305
1306               if (symbol->flags & BSF_WEAK)
1307                 *n_sclass = obj_pe (abfd) ? C_NT_WEAK : C_WEAKEXT;
1308               else if (symbol->flags & BSF_LOCAL && sym_class != COFF_SYMBOL_LOCAL)
1309                 *n_sclass = C_STAT;
1310               else if (symbol->flags & BSF_GLOBAL
1311                        && (sym_class != COFF_SYMBOL_GLOBAL
1312 #ifdef COFF_WITH_PE
1313                            || *n_sclass == C_NT_WEAK
1314 #endif
1315                            || *n_sclass == C_WEAKEXT))
1316                 c_symbol->native->u.syment.n_sclass = C_EXT;
1317             }
1318
1319           if (!coff_write_native_symbol (abfd, c_symbol, &written,
1320                                          &string_size, &debug_string_section,
1321                                          &debug_string_size))
1322             return FALSE;
1323         }
1324     }
1325
1326   obj_raw_syment_count (abfd) = written;
1327
1328   /* Now write out strings.  */
1329   if (string_size != 0)
1330     {
1331       unsigned int size = string_size + STRING_SIZE_SIZE;
1332       bfd_byte buffer[STRING_SIZE_SIZE];
1333
1334 #if STRING_SIZE_SIZE == 4
1335       H_PUT_32 (abfd, size, buffer);
1336 #else
1337  #error Change H_PUT_32
1338 #endif
1339       if (bfd_bwrite ((void *) buffer, (bfd_size_type) sizeof (buffer), abfd)
1340           != sizeof (buffer))
1341         return FALSE;
1342
1343       /* Handle long section names.  This code must handle section
1344          names just as they are handled in coff_write_object_contents.  */
1345       if (bfd_coff_long_section_names (abfd))
1346         {
1347           asection *o;
1348
1349           for (o = abfd->sections; o != NULL; o = o->next)
1350             {
1351               size_t len;
1352
1353               len = strlen (o->name);
1354               if (len > SCNNMLEN)
1355                 {
1356                   if (bfd_bwrite (o->name, (bfd_size_type) (len + 1), abfd)
1357                       != len + 1)
1358                     return FALSE;
1359                 }
1360             }
1361         }
1362
1363       for (p = abfd->outsymbols, i = 0;
1364            i < limit;
1365            i++, p++)
1366         {
1367           asymbol *q = *p;
1368           size_t name_length = strlen (q->name);
1369           coff_symbol_type *c_symbol = coff_symbol_from (q);
1370           size_t maxlen;
1371
1372           /* Figure out whether the symbol name should go in the string
1373              table.  Symbol names that are short enough are stored
1374              directly in the syment structure.  File names permit a
1375              different, longer, length in the syment structure.  On
1376              XCOFF, some symbol names are stored in the .debug section
1377              rather than in the string table.  */
1378
1379           if (c_symbol == NULL
1380               || c_symbol->native == NULL)
1381             /* This is not a COFF symbol, so it certainly is not a
1382                file name, nor does it go in the .debug section.  */
1383             maxlen = bfd_coff_force_symnames_in_strings (abfd) ? 0 : SYMNMLEN;
1384
1385           else if (! c_symbol->native->is_sym)
1386             maxlen = bfd_coff_force_symnames_in_strings (abfd) ? 0 : SYMNMLEN;
1387
1388           else if (bfd_coff_symname_in_debug (abfd,
1389                                               &c_symbol->native->u.syment))
1390             /* This symbol name is in the XCOFF .debug section.
1391                Don't write it into the string table.  */
1392             maxlen = name_length;
1393
1394           else if (c_symbol->native->u.syment.n_sclass == C_FILE
1395                    && c_symbol->native->u.syment.n_numaux > 0)
1396             {
1397               if (bfd_coff_force_symnames_in_strings (abfd))
1398                 {
1399                   if (bfd_bwrite (".file", (bfd_size_type) 6, abfd) != 6)
1400                     return FALSE;
1401                 }
1402               maxlen = bfd_coff_filnmlen (abfd);
1403             }
1404           else
1405             maxlen = bfd_coff_force_symnames_in_strings (abfd) ? 0 : SYMNMLEN;
1406
1407           if (name_length > maxlen)
1408             {
1409               if (bfd_bwrite ((void *) (q->name), (bfd_size_type) name_length + 1,
1410                              abfd) != name_length + 1)
1411                 return FALSE;
1412             }
1413         }
1414     }
1415   else
1416     {
1417       /* We would normally not write anything here, but we'll write
1418          out 4 so that any stupid coff reader which tries to read the
1419          string table even when there isn't one won't croak.  */
1420       unsigned int size = STRING_SIZE_SIZE;
1421       bfd_byte buffer[STRING_SIZE_SIZE];
1422
1423 #if STRING_SIZE_SIZE == 4
1424       H_PUT_32 (abfd, size, buffer);
1425 #else
1426  #error Change H_PUT_32
1427 #endif
1428       if (bfd_bwrite ((void *) buffer, (bfd_size_type) STRING_SIZE_SIZE, abfd)
1429           != STRING_SIZE_SIZE)
1430         return FALSE;
1431     }
1432
1433   /* Make sure the .debug section was created to be the correct size.
1434      We should create it ourselves on the fly, but we don't because
1435      BFD won't let us write to any section until we know how large all
1436      the sections are.  We could still do it by making another pass
1437      over the symbols.  FIXME.  */
1438   BFD_ASSERT (debug_string_size == 0
1439               || (debug_string_section != (asection *) NULL
1440                   && (BFD_ALIGN (debug_string_size,
1441                                  1 << debug_string_section->alignment_power)
1442                       == debug_string_section->size)));
1443
1444   return TRUE;
1445 }
1446
1447 bfd_boolean
1448 coff_write_linenumbers (bfd *abfd)
1449 {
1450   asection *s;
1451   bfd_size_type linesz;
1452   void * buff;
1453
1454   linesz = bfd_coff_linesz (abfd);
1455   buff = bfd_alloc (abfd, linesz);
1456   if (!buff)
1457     return FALSE;
1458   for (s = abfd->sections; s != (asection *) NULL; s = s->next)
1459     {
1460       if (s->lineno_count)
1461         {
1462           asymbol **q = abfd->outsymbols;
1463           if (bfd_seek (abfd, s->line_filepos, SEEK_SET) != 0)
1464             return FALSE;
1465           /* Find all the linenumbers in this section.  */
1466           while (*q)
1467             {
1468               asymbol *p = *q;
1469               if (p->section->output_section == s)
1470                 {
1471                   alent *l =
1472                   BFD_SEND (bfd_asymbol_bfd (p), _get_lineno,
1473                             (bfd_asymbol_bfd (p), p));
1474                   if (l)
1475                     {
1476                       /* Found a linenumber entry, output.  */
1477                       struct internal_lineno out;
1478
1479                       memset ((void *) & out, 0, sizeof (out));
1480                       out.l_lnno = 0;
1481                       out.l_addr.l_symndx = l->u.offset;
1482                       bfd_coff_swap_lineno_out (abfd, &out, buff);
1483                       if (bfd_bwrite (buff, (bfd_size_type) linesz, abfd)
1484                           != linesz)
1485                         return FALSE;
1486                       l++;
1487                       while (l->line_number)
1488                         {
1489                           out.l_lnno = l->line_number;
1490                           out.l_addr.l_symndx = l->u.offset;
1491                           bfd_coff_swap_lineno_out (abfd, &out, buff);
1492                           if (bfd_bwrite (buff, (bfd_size_type) linesz, abfd)
1493                               != linesz)
1494                             return FALSE;
1495                           l++;
1496                         }
1497                     }
1498                 }
1499               q++;
1500             }
1501         }
1502     }
1503   bfd_release (abfd, buff);
1504   return TRUE;
1505 }
1506
1507 alent *
1508 coff_get_lineno (bfd *ignore_abfd ATTRIBUTE_UNUSED, asymbol *symbol)
1509 {
1510   return coffsymbol (symbol)->lineno;
1511 }
1512
1513 /* This function transforms the offsets into the symbol table into
1514    pointers to syments.  */
1515
1516 static void
1517 coff_pointerize_aux (bfd *abfd,
1518                      combined_entry_type *table_base,
1519                      combined_entry_type *symbol,
1520                      unsigned int indaux,
1521                      combined_entry_type *auxent)
1522 {
1523   unsigned int type = symbol->u.syment.n_type;
1524   unsigned int n_sclass = symbol->u.syment.n_sclass;
1525
1526   BFD_ASSERT (symbol->is_sym);
1527   if (coff_backend_info (abfd)->_bfd_coff_pointerize_aux_hook)
1528     {
1529       if ((*coff_backend_info (abfd)->_bfd_coff_pointerize_aux_hook)
1530           (abfd, table_base, symbol, indaux, auxent))
1531         return;
1532     }
1533
1534   /* Don't bother if this is a file or a section.  */
1535   if (n_sclass == C_STAT && type == T_NULL)
1536     return;
1537   if (n_sclass == C_FILE)
1538     return;
1539
1540   BFD_ASSERT (! auxent->is_sym);
1541   /* Otherwise patch up.  */
1542 #define N_TMASK coff_data  (abfd)->local_n_tmask
1543 #define N_BTSHFT coff_data (abfd)->local_n_btshft
1544
1545   if ((ISFCN (type) || ISTAG (n_sclass) || n_sclass == C_BLOCK
1546        || n_sclass == C_FCN)
1547       && auxent->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.l > 0)
1548     {
1549       auxent->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.p =
1550         table_base + auxent->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.l;
1551       auxent->fix_end = 1;
1552     }
1553   /* A negative tagndx is meaningless, but the SCO 3.2v4 cc can
1554      generate one, so we must be careful to ignore it.  */
1555   if (auxent->u.auxent.x_sym.x_tagndx.l > 0)
1556     {
1557       auxent->u.auxent.x_sym.x_tagndx.p =
1558         table_base + auxent->u.auxent.x_sym.x_tagndx.l;
1559       auxent->fix_tag = 1;
1560     }
1561 }
1562
1563 /* Allocate space for the ".debug" section, and read it.
1564    We did not read the debug section until now, because
1565    we didn't want to go to the trouble until someone needed it.  */
1566
1567 static char *
1568 build_debug_section (bfd *abfd, asection ** sect_return)
1569 {
1570   char *debug_section;
1571   file_ptr position;
1572   bfd_size_type sec_size;
1573
1574   asection *sect = bfd_get_section_by_name (abfd, ".debug");
1575
1576   if (!sect)
1577     {
1578       bfd_set_error (bfd_error_no_debug_section);
1579       return NULL;
1580     }
1581
1582   sec_size = sect->size;
1583   debug_section = (char *) bfd_alloc (abfd, sec_size);
1584   if (debug_section == NULL)
1585     return NULL;
1586
1587   /* Seek to the beginning of the `.debug' section and read it.
1588      Save the current position first; it is needed by our caller.
1589      Then read debug section and reset the file pointer.  */
1590
1591   position = bfd_tell (abfd);
1592   if (bfd_seek (abfd, sect->filepos, SEEK_SET) != 0
1593       || bfd_bread (debug_section, sec_size, abfd) != sec_size
1594       || bfd_seek (abfd, position, SEEK_SET) != 0)
1595     return NULL;
1596
1597   * sect_return = sect;
1598   return debug_section;
1599 }
1600
1601 /* Return a pointer to a malloc'd copy of 'name'.  'name' may not be
1602    \0-terminated, but will not exceed 'maxlen' characters.  The copy *will*
1603    be \0-terminated.  */
1604
1605 static char *
1606 copy_name (bfd *abfd, char *name, size_t maxlen)
1607 {
1608   size_t len;
1609   char *newname;
1610
1611   for (len = 0; len < maxlen; ++len)
1612     if (name[len] == '\0')
1613       break;
1614
1615   if ((newname = (char *) bfd_alloc (abfd, (bfd_size_type) len + 1)) == NULL)
1616     return NULL;
1617
1618   strncpy (newname, name, len);
1619   newname[len] = '\0';
1620   return newname;
1621 }
1622
1623 /* Read in the external symbols.  */
1624
1625 bfd_boolean
1626 _bfd_coff_get_external_symbols (bfd *abfd)
1627 {
1628   bfd_size_type symesz;
1629   bfd_size_type size;
1630   void * syms;
1631
1632   if (obj_coff_external_syms (abfd) != NULL)
1633     return TRUE;
1634
1635   symesz = bfd_coff_symesz (abfd);
1636
1637   size = obj_raw_syment_count (abfd) * symesz;
1638   if (size == 0)
1639     return TRUE;
1640
1641   syms = bfd_malloc (size);
1642   if (syms == NULL)
1643     return FALSE;
1644
1645   if (bfd_seek (abfd, obj_sym_filepos (abfd), SEEK_SET) != 0
1646       || bfd_bread (syms, size, abfd) != size)
1647     {
1648       if (syms != NULL)
1649         free (syms);
1650       return FALSE;
1651     }
1652
1653   obj_coff_external_syms (abfd) = syms;
1654
1655   return TRUE;
1656 }
1657
1658 /* Read in the external strings.  The strings are not loaded until
1659    they are needed.  This is because we have no simple way of
1660    detecting a missing string table in an archive.  If the strings
1661    are loaded then the STRINGS and STRINGS_LEN fields in the
1662    coff_tdata structure will be set.  */
1663
1664 const char *
1665 _bfd_coff_read_string_table (bfd *abfd)
1666 {
1667   char extstrsize[STRING_SIZE_SIZE];
1668   bfd_size_type strsize;
1669   char *strings;
1670   file_ptr pos;
1671
1672   if (obj_coff_strings (abfd) != NULL)
1673     return obj_coff_strings (abfd);
1674
1675   if (obj_sym_filepos (abfd) == 0)
1676     {
1677       bfd_set_error (bfd_error_no_symbols);
1678       return NULL;
1679     }
1680
1681   pos = obj_sym_filepos (abfd);
1682   pos += obj_raw_syment_count (abfd) * bfd_coff_symesz (abfd);
1683   if (bfd_seek (abfd, pos, SEEK_SET) != 0)
1684     return NULL;
1685
1686   if (bfd_bread (extstrsize, (bfd_size_type) sizeof extstrsize, abfd)
1687       != sizeof extstrsize)
1688     {
1689       if (bfd_get_error () != bfd_error_file_truncated)
1690         return NULL;
1691
1692       /* There is no string table.  */
1693       strsize = STRING_SIZE_SIZE;
1694     }
1695   else
1696     {
1697 #if STRING_SIZE_SIZE == 4
1698       strsize = H_GET_32 (abfd, extstrsize);
1699 #else
1700  #error Change H_GET_32
1701 #endif
1702     }
1703
1704   if (strsize < STRING_SIZE_SIZE)
1705     {
1706       (*_bfd_error_handler)
1707         (_("%B: bad string table size %lu"), abfd, (unsigned long) strsize);
1708       bfd_set_error (bfd_error_bad_value);
1709       return NULL;
1710     }
1711
1712   strings = (char *) bfd_malloc (strsize + 1);
1713   if (strings == NULL)
1714     return NULL;
1715
1716   /* PR 17521 file: 079-54929-0.004.
1717      A corrupt file could contain an index that points into the first
1718      STRING_SIZE_SIZE bytes of the string table, so make sure that
1719      they are zero.  */
1720   memset (strings, 0, STRING_SIZE_SIZE);
1721
1722   if (bfd_bread (strings + STRING_SIZE_SIZE, strsize - STRING_SIZE_SIZE, abfd)
1723       != strsize - STRING_SIZE_SIZE)
1724     {
1725       free (strings);
1726       return NULL;
1727     }
1728
1729   obj_coff_strings (abfd) = strings;
1730   obj_coff_strings_len (abfd) = strsize;
1731   /* Terminate the string table, just in case.  */
1732   strings[strsize] = 0;
1733   return strings;
1734 }
1735
1736 /* Free up the external symbols and strings read from a COFF file.  */
1737
1738 bfd_boolean
1739 _bfd_coff_free_symbols (bfd *abfd)
1740 {
1741   if (obj_coff_external_syms (abfd) != NULL
1742       && ! obj_coff_keep_syms (abfd))
1743     {
1744       free (obj_coff_external_syms (abfd));
1745       obj_coff_external_syms (abfd) = NULL;
1746     }
1747   if (obj_coff_strings (abfd) != NULL
1748       && ! obj_coff_keep_strings (abfd))
1749     {
1750       free (obj_coff_strings (abfd));
1751       obj_coff_strings (abfd) = NULL;
1752       obj_coff_strings_len (abfd) = 0;
1753     }
1754   return TRUE;
1755 }
1756
1757 /* Read a symbol table into freshly bfd_allocated memory, swap it, and
1758    knit the symbol names into a normalized form.  By normalized here I
1759    mean that all symbols have an n_offset pointer that points to a null-
1760    terminated string.  */
1761
1762 combined_entry_type *
1763 coff_get_normalized_symtab (bfd *abfd)
1764 {
1765   combined_entry_type *internal;
1766   combined_entry_type *internal_ptr;
1767   combined_entry_type *symbol_ptr;
1768   combined_entry_type *internal_end;
1769   size_t symesz;
1770   char *raw_src;
1771   char *raw_end;
1772   const char *string_table = NULL;
1773   asection * debug_sec = NULL;
1774   char *debug_sec_data = NULL;
1775   bfd_size_type size;
1776
1777   if (obj_raw_syments (abfd) != NULL)
1778     return obj_raw_syments (abfd);
1779
1780   if (! _bfd_coff_get_external_symbols (abfd))
1781     return NULL;
1782
1783   size = obj_raw_syment_count (abfd) * sizeof (combined_entry_type);
1784   internal = (combined_entry_type *) bfd_zalloc (abfd, size);
1785   if (internal == NULL && size != 0)
1786     return NULL;
1787   internal_end = internal + obj_raw_syment_count (abfd);
1788
1789   raw_src = (char *) obj_coff_external_syms (abfd);
1790
1791   /* Mark the end of the symbols.  */
1792   symesz = bfd_coff_symesz (abfd);
1793   raw_end = (char *) raw_src + obj_raw_syment_count (abfd) * symesz;
1794
1795   /* FIXME SOMEDAY.  A string table size of zero is very weird, but
1796      probably possible.  If one shows up, it will probably kill us.  */
1797
1798   /* Swap all the raw entries.  */
1799   for (internal_ptr = internal;
1800        raw_src < raw_end;
1801        raw_src += symesz, internal_ptr++)
1802     {
1803       unsigned int i;
1804
1805       bfd_coff_swap_sym_in (abfd, (void *) raw_src,
1806                             (void *) & internal_ptr->u.syment);
1807       symbol_ptr = internal_ptr;
1808       internal_ptr->is_sym = TRUE;
1809
1810       /* PR 17512: file: 1353-1166-0.004.  */
1811       if (symbol_ptr->u.syment.n_sclass == C_FILE
1812           && symbol_ptr->u.syment.n_numaux > 0
1813           && raw_src + symesz + symbol_ptr->u.syment.n_numaux
1814           * symesz > raw_end)
1815         {
1816           bfd_release (abfd, internal);
1817           return NULL;
1818         }
1819
1820       for (i = 0;
1821            i < symbol_ptr->u.syment.n_numaux;
1822            i++)
1823         {
1824           internal_ptr++;
1825           /* PR 17512: Prevent buffer overrun.  */
1826           if (internal_ptr >= internal_end)
1827             {
1828               bfd_release (abfd, internal);
1829               return NULL;
1830             }
1831
1832           raw_src += symesz;
1833           bfd_coff_swap_aux_in (abfd, (void *) raw_src,
1834                                 symbol_ptr->u.syment.n_type,
1835                                 symbol_ptr->u.syment.n_sclass,
1836                                 (int) i, symbol_ptr->u.syment.n_numaux,
1837                                 &(internal_ptr->u.auxent));
1838
1839           internal_ptr->is_sym = FALSE;
1840           coff_pointerize_aux (abfd, internal, symbol_ptr, i,
1841                                internal_ptr);
1842         }
1843     }
1844
1845   /* Free the raw symbols, but not the strings (if we have them).  */
1846   obj_coff_keep_strings (abfd) = TRUE;
1847   if (! _bfd_coff_free_symbols (abfd))
1848     return NULL;
1849
1850   for (internal_ptr = internal; internal_ptr < internal_end;
1851        internal_ptr++)
1852     {
1853       BFD_ASSERT (internal_ptr->is_sym);
1854
1855       if (internal_ptr->u.syment.n_sclass == C_FILE
1856           && internal_ptr->u.syment.n_numaux > 0)
1857         {
1858           combined_entry_type * aux = internal_ptr + 1;
1859
1860           /* Make a file symbol point to the name in the auxent, since
1861              the text ".file" is redundant.  */
1862           BFD_ASSERT (! aux->is_sym);
1863
1864           if (aux->u.auxent.x_file.x_n.x_zeroes == 0)
1865             {
1866               /* The filename is a long one, point into the string table.  */
1867               if (string_table == NULL)
1868                 {
1869                   string_table = _bfd_coff_read_string_table (abfd);
1870                   if (string_table == NULL)
1871                     return NULL;
1872                 }
1873
1874               if ((bfd_size_type)(aux->u.auxent.x_file.x_n.x_offset)
1875                   >= obj_coff_strings_len (abfd))
1876                 internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) _("<corrupt>");
1877               else
1878                 internal_ptr->u.syment._n._n_n._n_offset =
1879                   (bfd_hostptr_t) (string_table + (aux->u.auxent.x_file.x_n.x_offset));
1880             }
1881           else
1882             {
1883               /* Ordinary short filename, put into memory anyway.  The
1884                  Microsoft PE tools sometimes store a filename in
1885                  multiple AUX entries.  */
1886               if (internal_ptr->u.syment.n_numaux > 1
1887                   && coff_data (abfd)->pe)
1888                 internal_ptr->u.syment._n._n_n._n_offset =
1889                   (bfd_hostptr_t)
1890                   copy_name (abfd,
1891                              aux->u.auxent.x_file.x_fname,
1892                              internal_ptr->u.syment.n_numaux * symesz);
1893               else
1894                 internal_ptr->u.syment._n._n_n._n_offset =
1895                   ((bfd_hostptr_t)
1896                    copy_name (abfd,
1897                               aux->u.auxent.x_file.x_fname,
1898                               (size_t) bfd_coff_filnmlen (abfd)));
1899             }
1900         }
1901       else
1902         {
1903           if (internal_ptr->u.syment._n._n_n._n_zeroes != 0)
1904             {
1905               /* This is a "short" name.  Make it long.  */
1906               size_t i;
1907               char *newstring;
1908
1909               /* Find the length of this string without walking into memory
1910                  that isn't ours.  */
1911               for (i = 0; i < 8; ++i)
1912                 if (internal_ptr->u.syment._n._n_name[i] == '\0')
1913                   break;
1914
1915               newstring = (char *) bfd_zalloc (abfd, (bfd_size_type) (i + 1));
1916               if (newstring == NULL)
1917                 return NULL;
1918               strncpy (newstring, internal_ptr->u.syment._n._n_name, i);
1919               internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) newstring;
1920               internal_ptr->u.syment._n._n_n._n_zeroes = 0;
1921             }
1922           else if (internal_ptr->u.syment._n._n_n._n_offset == 0)
1923             internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) "";
1924           else if (!bfd_coff_symname_in_debug (abfd, &internal_ptr->u.syment))
1925             {
1926               /* Long name already.  Point symbol at the string in the
1927                  table.  */
1928               if (string_table == NULL)
1929                 {
1930                   string_table = _bfd_coff_read_string_table (abfd);
1931                   if (string_table == NULL)
1932                     return NULL;
1933                 }
1934               if (internal_ptr->u.syment._n._n_n._n_offset >= obj_coff_strings_len (abfd)
1935                   || string_table + internal_ptr->u.syment._n._n_n._n_offset < string_table)
1936                 internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) _("<corrupt>");
1937               else
1938                 internal_ptr->u.syment._n._n_n._n_offset =
1939                   ((bfd_hostptr_t)
1940                    (string_table
1941                     + internal_ptr->u.syment._n._n_n._n_offset));
1942             }
1943           else
1944             {
1945               /* Long name in debug section.  Very similar.  */
1946               if (debug_sec_data == NULL)
1947                 debug_sec_data = build_debug_section (abfd, & debug_sec);
1948               if (debug_sec_data != NULL)
1949                 {
1950                   BFD_ASSERT (debug_sec != NULL);
1951                   /* PR binutils/17512: Catch out of range offsets into the debug data.  */
1952                   if (internal_ptr->u.syment._n._n_n._n_offset > debug_sec->size
1953                       || debug_sec_data + internal_ptr->u.syment._n._n_n._n_offset < debug_sec_data)
1954                     internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) _("<corrupt>");
1955                   else
1956                     internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t)
1957                       (debug_sec_data + internal_ptr->u.syment._n._n_n._n_offset);
1958                 }
1959               else
1960                 internal_ptr->u.syment._n._n_n._n_offset = (bfd_hostptr_t) "";
1961             }
1962         }
1963       internal_ptr += internal_ptr->u.syment.n_numaux;
1964     }
1965
1966   obj_raw_syments (abfd) = internal;
1967   BFD_ASSERT (obj_raw_syment_count (abfd)
1968               == (unsigned int) (internal_ptr - internal));
1969
1970   return internal;
1971 }
1972
1973 long
1974 coff_get_reloc_upper_bound (bfd *abfd, sec_ptr asect)
1975 {
1976   if (bfd_get_format (abfd) != bfd_object)
1977     {
1978       bfd_set_error (bfd_error_invalid_operation);
1979       return -1;
1980     }
1981   return (asect->reloc_count + 1) * sizeof (arelent *);
1982 }
1983
1984 asymbol *
1985 coff_make_empty_symbol (bfd *abfd)
1986 {
1987   bfd_size_type amt = sizeof (coff_symbol_type);
1988   coff_symbol_type *new_symbol = (coff_symbol_type *) bfd_zalloc (abfd, amt);
1989
1990   if (new_symbol == NULL)
1991     return NULL;
1992   new_symbol->symbol.section = 0;
1993   new_symbol->native = NULL;
1994   new_symbol->lineno = NULL;
1995   new_symbol->done_lineno = FALSE;
1996   new_symbol->symbol.the_bfd = abfd;
1997
1998   return & new_symbol->symbol;
1999 }
2000
2001 /* Make a debugging symbol.  */
2002
2003 asymbol *
2004 coff_bfd_make_debug_symbol (bfd *abfd,
2005                             void * ptr ATTRIBUTE_UNUSED,
2006                             unsigned long sz ATTRIBUTE_UNUSED)
2007 {
2008   bfd_size_type amt = sizeof (coff_symbol_type);
2009   coff_symbol_type *new_symbol = (coff_symbol_type *) bfd_alloc (abfd, amt);
2010
2011   if (new_symbol == NULL)
2012     return NULL;
2013   /* @@ The 10 is a guess at a plausible maximum number of aux entries
2014      (but shouldn't be a constant).  */
2015   amt = sizeof (combined_entry_type) * 10;
2016   new_symbol->native = (combined_entry_type *) bfd_zalloc (abfd, amt);
2017   if (!new_symbol->native)
2018     return NULL;
2019   new_symbol->native->is_sym = TRUE;
2020   new_symbol->symbol.section = bfd_abs_section_ptr;
2021   new_symbol->symbol.flags = BSF_DEBUGGING;
2022   new_symbol->lineno = NULL;
2023   new_symbol->done_lineno = FALSE;
2024   new_symbol->symbol.the_bfd = abfd;
2025
2026   return & new_symbol->symbol;
2027 }
2028
2029 void
2030 coff_get_symbol_info (bfd *abfd, asymbol *symbol, symbol_info *ret)
2031 {
2032   bfd_symbol_info (symbol, ret);
2033
2034   if (coffsymbol (symbol)->native != NULL
2035       && coffsymbol (symbol)->native->fix_value
2036       && coffsymbol (symbol)->native->is_sym)
2037     ret->value = coffsymbol (symbol)->native->u.syment.n_value -
2038       (bfd_hostptr_t) obj_raw_syments (abfd);
2039 }
2040
2041 /* Print out information about COFF symbol.  */
2042
2043 void
2044 coff_print_symbol (bfd *abfd,
2045                    void * filep,
2046                    asymbol *symbol,
2047                    bfd_print_symbol_type how)
2048 {
2049   FILE * file = (FILE *) filep;
2050
2051   switch (how)
2052     {
2053     case bfd_print_symbol_name:
2054       fprintf (file, "%s", symbol->name);
2055       break;
2056
2057     case bfd_print_symbol_more:
2058       fprintf (file, "coff %s %s",
2059                coffsymbol (symbol)->native ? "n" : "g",
2060                coffsymbol (symbol)->lineno ? "l" : " ");
2061       break;
2062
2063     case bfd_print_symbol_all:
2064       if (coffsymbol (symbol)->native)
2065         {
2066           bfd_vma val;
2067           unsigned int aux;
2068           combined_entry_type *combined = coffsymbol (symbol)->native;
2069           combined_entry_type *root = obj_raw_syments (abfd);
2070           struct lineno_cache_entry *l = coffsymbol (symbol)->lineno;
2071
2072           fprintf (file, "[%3ld]", (long) (combined - root));
2073
2074           /* PR 17512: file: 079-33786-0.001:0.1.  */
2075           if (combined < obj_raw_syments (abfd)
2076               || combined >= obj_raw_syments (abfd) + obj_raw_syment_count (abfd))
2077             {
2078               fprintf (file, _("<corrupt info> %s"), symbol->name);
2079               break;
2080             }
2081
2082           BFD_ASSERT (combined->is_sym);
2083           if (! combined->fix_value)
2084             val = (bfd_vma) combined->u.syment.n_value;
2085           else
2086             val = combined->u.syment.n_value - (bfd_hostptr_t) root;
2087
2088           fprintf (file, "(sec %2d)(fl 0x%02x)(ty %3x)(scl %3d) (nx %d) 0x",
2089                    combined->u.syment.n_scnum,
2090                    combined->u.syment.n_flags,
2091                    combined->u.syment.n_type,
2092                    combined->u.syment.n_sclass,
2093                    combined->u.syment.n_numaux);
2094           bfd_fprintf_vma (abfd, file, val);
2095           fprintf (file, " %s", symbol->name);
2096
2097           for (aux = 0; aux < combined->u.syment.n_numaux; aux++)
2098             {
2099               combined_entry_type *auxp = combined + aux + 1;
2100               long tagndx;
2101
2102               BFD_ASSERT (! auxp->is_sym);
2103               if (auxp->fix_tag)
2104                 tagndx = auxp->u.auxent.x_sym.x_tagndx.p - root;
2105               else
2106                 tagndx = auxp->u.auxent.x_sym.x_tagndx.l;
2107
2108               fprintf (file, "\n");
2109
2110               if (bfd_coff_print_aux (abfd, file, root, combined, auxp, aux))
2111                 continue;
2112
2113               switch (combined->u.syment.n_sclass)
2114                 {
2115                 case C_FILE:
2116                   fprintf (file, "File ");
2117                   break;
2118
2119                 case C_STAT:
2120                   if (combined->u.syment.n_type == T_NULL)
2121                     /* Probably a section symbol ?  */
2122                     {
2123                       fprintf (file, "AUX scnlen 0x%lx nreloc %d nlnno %d",
2124                                (unsigned long) auxp->u.auxent.x_scn.x_scnlen,
2125                                auxp->u.auxent.x_scn.x_nreloc,
2126                                auxp->u.auxent.x_scn.x_nlinno);
2127                       if (auxp->u.auxent.x_scn.x_checksum != 0
2128                           || auxp->u.auxent.x_scn.x_associated != 0
2129                           || auxp->u.auxent.x_scn.x_comdat != 0)
2130                         fprintf (file, " checksum 0x%lx assoc %d comdat %d",
2131                                  auxp->u.auxent.x_scn.x_checksum,
2132                                  auxp->u.auxent.x_scn.x_associated,
2133                                  auxp->u.auxent.x_scn.x_comdat);
2134                       break;
2135                     }
2136                     /* Otherwise fall through.  */
2137                 case C_EXT:
2138                 case C_AIX_WEAKEXT:
2139                   if (ISFCN (combined->u.syment.n_type))
2140                     {
2141                       long next, llnos;
2142
2143                       if (auxp->fix_end)
2144                         next = (auxp->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.p
2145                                - root);
2146                       else
2147                         next = auxp->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.l;
2148                       llnos = auxp->u.auxent.x_sym.x_fcnary.x_fcn.x_lnnoptr;
2149                       fprintf (file,
2150                                "AUX tagndx %ld ttlsiz 0x%lx lnnos %ld next %ld",
2151                                tagndx,
2152                                (unsigned long) auxp->u.auxent.x_sym.x_misc.x_fsize,
2153                                llnos, next);
2154                       break;
2155                     }
2156                   /* Otherwise fall through.  */
2157                 default:
2158                   fprintf (file, "AUX lnno %d size 0x%x tagndx %ld",
2159                            auxp->u.auxent.x_sym.x_misc.x_lnsz.x_lnno,
2160                            auxp->u.auxent.x_sym.x_misc.x_lnsz.x_size,
2161                            tagndx);
2162                   if (auxp->fix_end)
2163                     fprintf (file, " endndx %ld",
2164                              ((long)
2165                               (auxp->u.auxent.x_sym.x_fcnary.x_fcn.x_endndx.p
2166                                - root)));
2167                   break;
2168                 }
2169             }
2170
2171           if (l)
2172             {
2173               fprintf (file, "\n%s :", l->u.sym->name);
2174               l++;
2175               while (l->line_number)
2176                 {
2177                   if (l->line_number > 0)
2178                     {
2179                       fprintf (file, "\n%4d : ", l->line_number);
2180                       bfd_fprintf_vma (abfd, file, l->u.offset + symbol->section->vma);
2181                     }
2182                   l++;
2183                 }
2184             }
2185         }
2186       else
2187         {
2188           bfd_print_symbol_vandf (abfd, (void *) file, symbol);
2189           fprintf (file, " %-5s %s %s %s",
2190                    symbol->section->name,
2191                    coffsymbol (symbol)->native ? "n" : "g",
2192                    coffsymbol (symbol)->lineno ? "l" : " ",
2193                    symbol->name);
2194         }
2195     }
2196 }
2197
2198 /* Return whether a symbol name implies a local symbol.  In COFF,
2199    local symbols generally start with ``.L''.  Most targets use this
2200    function for the is_local_label_name entry point, but some may
2201    override it.  */
2202
2203 bfd_boolean
2204 _bfd_coff_is_local_label_name (bfd *abfd ATTRIBUTE_UNUSED,
2205                                const char *name)
2206 {
2207   return name[0] == '.' && name[1] == 'L';
2208 }
2209
2210 /* Provided a BFD, a section and an offset (in bytes, not octets) into the
2211    section, calculate and return the name of the source file and the line
2212    nearest to the wanted location.  */
2213
2214 bfd_boolean
2215 coff_find_nearest_line_with_names (bfd *abfd,
2216                                    asymbol **symbols,
2217                                    asection *section,
2218                                    bfd_vma offset,
2219                                    const char **filename_ptr,
2220                                    const char **functionname_ptr,
2221                                    unsigned int *line_ptr,
2222                                    const struct dwarf_debug_section *debug_sections)
2223 {
2224   bfd_boolean found;
2225   unsigned int i;
2226   unsigned int line_base;
2227   coff_data_type *cof = coff_data (abfd);
2228   /* Run through the raw syments if available.  */
2229   combined_entry_type *p;
2230   combined_entry_type *pend;
2231   alent *l;
2232   struct coff_section_tdata *sec_data;
2233   bfd_size_type amt;
2234
2235   /* Before looking through the symbol table, try to use a .stab
2236      section to find the information.  */
2237   if (! _bfd_stab_section_find_nearest_line (abfd, symbols, section, offset,
2238                                              &found, filename_ptr,
2239                                              functionname_ptr, line_ptr,
2240                                              &coff_data(abfd)->line_info))
2241     return FALSE;
2242
2243   if (found)
2244     return TRUE;
2245
2246   /* Also try examining DWARF2 debugging information.  */
2247   if (_bfd_dwarf2_find_nearest_line (abfd, symbols, NULL, section, offset,
2248                                      filename_ptr, functionname_ptr,
2249                                      line_ptr, NULL, debug_sections, 0,
2250                                      &coff_data(abfd)->dwarf2_find_line_info))
2251     return TRUE;
2252
2253   /* If the DWARF lookup failed, but there is DWARF information available
2254      then the problem might be that the file has been rebased.  This tool
2255      changes the VMAs of all the sections, but it does not update the DWARF
2256      information.  So try again, using a bias against the address sought.  */
2257   if (coff_data (abfd)->dwarf2_find_line_info != NULL)
2258     {
2259       bfd_signed_vma bias;
2260
2261       bias = _bfd_dwarf2_find_symbol_bias (symbols,
2262                                            & coff_data (abfd)->dwarf2_find_line_info);
2263
2264       if (bias
2265           && _bfd_dwarf2_find_nearest_line (abfd, symbols, NULL, section,
2266                                             offset + bias,
2267                                             filename_ptr, functionname_ptr,
2268                                             line_ptr, NULL, debug_sections, 0,
2269                                             &coff_data(abfd)->dwarf2_find_line_info))
2270         return TRUE;
2271     }
2272
2273   *filename_ptr = 0;
2274   *functionname_ptr = 0;
2275   *line_ptr = 0;
2276
2277   /* Don't try and find line numbers in a non coff file.  */
2278   if (!bfd_family_coff (abfd))
2279     return FALSE;
2280
2281   if (cof == NULL)
2282     return FALSE;
2283
2284   /* Find the first C_FILE symbol.  */
2285   p = cof->raw_syments;
2286   if (!p)
2287     return FALSE;
2288
2289   pend = p + cof->raw_syment_count;
2290   while (p < pend)
2291     {
2292       BFD_ASSERT (p->is_sym);
2293       if (p->u.syment.n_sclass == C_FILE)
2294         break;
2295       p += 1 + p->u.syment.n_numaux;
2296     }
2297
2298   if (p < pend)
2299     {
2300       bfd_vma sec_vma;
2301       bfd_vma maxdiff;
2302
2303       /* Look through the C_FILE symbols to find the best one.  */
2304       sec_vma = bfd_get_section_vma (abfd, section);
2305       *filename_ptr = (char *) p->u.syment._n._n_n._n_offset;
2306       maxdiff = (bfd_vma) 0 - (bfd_vma) 1;
2307       while (1)
2308         {
2309           bfd_vma file_addr;
2310           combined_entry_type *p2;
2311
2312           for (p2 = p + 1 + p->u.syment.n_numaux;
2313                p2 < pend;
2314                p2 += 1 + p2->u.syment.n_numaux)
2315             {
2316               BFD_ASSERT (p2->is_sym);
2317               if (p2->u.syment.n_scnum > 0
2318                   && (section
2319                       == coff_section_from_bfd_index (abfd,
2320                                                       p2->u.syment.n_scnum)))
2321                 break;
2322               if (p2->u.syment.n_sclass == C_FILE)
2323                 {
2324                   p2 = pend;
2325                   break;
2326                 }
2327             }
2328           if (p2 >= pend)
2329             break;
2330
2331           file_addr = (bfd_vma) p2->u.syment.n_value;
2332           /* PR 11512: Include the section address of the function name symbol.  */
2333           if (p2->u.syment.n_scnum > 0)
2334             file_addr += coff_section_from_bfd_index (abfd,
2335                                                       p2->u.syment.n_scnum)->vma;
2336           /* We use <= MAXDIFF here so that if we get a zero length
2337              file, we actually use the next file entry.  */
2338           if (p2 < pend
2339               && offset + sec_vma >= file_addr
2340               && offset + sec_vma - file_addr <= maxdiff)
2341             {
2342               *filename_ptr = (char *) p->u.syment._n._n_n._n_offset;
2343               maxdiff = offset + sec_vma - p2->u.syment.n_value;
2344             }
2345
2346           /* Avoid endless loops on erroneous files by ensuring that
2347              we always move forward in the file.  */
2348           if (p >= cof->raw_syments + p->u.syment.n_value)
2349             break;
2350
2351           p = cof->raw_syments + p->u.syment.n_value;
2352           if (p > pend || p->u.syment.n_sclass != C_FILE)
2353             break;
2354         }
2355     }
2356
2357   /* Now wander though the raw linenumbers of the section.  */
2358   /* If we have been called on this section before, and the offset we
2359      want is further down then we can prime the lookup loop.  */
2360   sec_data = coff_section_data (abfd, section);
2361   if (sec_data != NULL
2362       && sec_data->i > 0
2363       && offset >= sec_data->offset)
2364     {
2365       i = sec_data->i;
2366       *functionname_ptr = sec_data->function;
2367       line_base = sec_data->line_base;
2368     }
2369   else
2370     {
2371       i = 0;
2372       line_base = 0;
2373     }
2374
2375   if (section->lineno != NULL)
2376     {
2377       bfd_vma last_value = 0;
2378
2379       l = &section->lineno[i];
2380
2381       for (; i < section->lineno_count; i++)
2382         {
2383           if (l->line_number == 0)
2384             {
2385               /* Get the symbol this line number points at.  */
2386               coff_symbol_type *coff = (coff_symbol_type *) (l->u.sym);
2387               if (coff->symbol.value > offset)
2388                 break;
2389               *functionname_ptr = coff->symbol.name;
2390               last_value = coff->symbol.value;
2391               if (coff->native)
2392                 {
2393                   combined_entry_type *s = coff->native;
2394
2395                   BFD_ASSERT (s->is_sym);
2396                   s = s + 1 + s->u.syment.n_numaux;
2397
2398                   /* In XCOFF a debugging symbol can follow the
2399                      function symbol.  */
2400                   if (s->u.syment.n_scnum == N_DEBUG)
2401                     s = s + 1 + s->u.syment.n_numaux;
2402
2403                   /* S should now point to the .bf of the function.  */
2404                   if (s->u.syment.n_numaux)
2405                     {
2406                       /* The linenumber is stored in the auxent.  */
2407                       union internal_auxent *a = &((s + 1)->u.auxent);
2408
2409                       line_base = a->x_sym.x_misc.x_lnsz.x_lnno;
2410                       *line_ptr = line_base;
2411                     }
2412                 }
2413             }
2414           else
2415             {
2416               if (l->u.offset > offset)
2417                 break;
2418               *line_ptr = l->line_number + line_base - 1;
2419             }
2420           l++;
2421         }
2422
2423       /* If we fell off the end of the loop, then assume that this
2424          symbol has no line number info.  Otherwise, symbols with no
2425          line number info get reported with the line number of the
2426          last line of the last symbol which does have line number
2427          info.  We use 0x100 as a slop to account for cases where the
2428          last line has executable code.  */
2429       if (i >= section->lineno_count
2430           && last_value != 0
2431           && offset - last_value > 0x100)
2432         {
2433           *functionname_ptr = NULL;
2434           *line_ptr = 0;
2435         }
2436     }
2437
2438   /* Cache the results for the next call.  */
2439   if (sec_data == NULL && section->owner == abfd)
2440     {
2441       amt = sizeof (struct coff_section_tdata);
2442       section->used_by_bfd = bfd_zalloc (abfd, amt);
2443       sec_data = (struct coff_section_tdata *) section->used_by_bfd;
2444     }
2445   if (sec_data != NULL)
2446     {
2447       sec_data->offset = offset;
2448       sec_data->i = i - 1;
2449       sec_data->function = *functionname_ptr;
2450       sec_data->line_base = line_base;
2451     }
2452
2453   return TRUE;
2454 }
2455
2456 bfd_boolean
2457 coff_find_nearest_line (bfd *abfd,
2458                         asymbol **symbols,
2459                         asection *section,
2460                         bfd_vma offset,
2461                         const char **filename_ptr,
2462                         const char **functionname_ptr,
2463                         unsigned int *line_ptr,
2464                         unsigned int *discriminator_ptr)
2465 {
2466   if (discriminator_ptr)
2467     *discriminator_ptr = 0;
2468   return coff_find_nearest_line_with_names (abfd, symbols, section, offset,
2469                                             filename_ptr, functionname_ptr,
2470                                             line_ptr, dwarf_debug_sections);
2471 }
2472
2473 bfd_boolean
2474 coff_find_inliner_info (bfd *abfd,
2475                         const char **filename_ptr,
2476                         const char **functionname_ptr,
2477                         unsigned int *line_ptr)
2478 {
2479   bfd_boolean found;
2480
2481   found = _bfd_dwarf2_find_inliner_info (abfd, filename_ptr,
2482                                          functionname_ptr, line_ptr,
2483                                          &coff_data(abfd)->dwarf2_find_line_info);
2484   return (found);
2485 }
2486
2487 int
2488 coff_sizeof_headers (bfd *abfd, struct bfd_link_info *info)
2489 {
2490   size_t size;
2491
2492   if (!bfd_link_relocatable (info))
2493     size = bfd_coff_filhsz (abfd) + bfd_coff_aoutsz (abfd);
2494   else
2495     size = bfd_coff_filhsz (abfd);
2496
2497   size += abfd->section_count * bfd_coff_scnhsz (abfd);
2498   return size;
2499 }
2500
2501 /* Change the class of a coff symbol held by BFD.  */
2502
2503 bfd_boolean
2504 bfd_coff_set_symbol_class (bfd *         abfd,
2505                            asymbol *     symbol,
2506                            unsigned int  symbol_class)
2507 {
2508   coff_symbol_type * csym;
2509
2510   csym = coff_symbol_from (symbol);
2511   if (csym == NULL)
2512     {
2513       bfd_set_error (bfd_error_invalid_operation);
2514       return FALSE;
2515     }
2516   else if (csym->native == NULL)
2517     {
2518       /* This is an alien symbol which no native coff backend data.
2519          We cheat here by creating a fake native entry for it and
2520          then filling in the class.  This code is based on that in
2521          coff_write_alien_symbol().  */
2522
2523       combined_entry_type * native;
2524       bfd_size_type amt = sizeof (* native);
2525
2526       native = (combined_entry_type *) bfd_zalloc (abfd, amt);
2527       if (native == NULL)
2528         return FALSE;
2529
2530       native->is_sym = TRUE;
2531       native->u.syment.n_type   = T_NULL;
2532       native->u.syment.n_sclass = symbol_class;
2533
2534       if (bfd_is_und_section (symbol->section))
2535         {
2536           native->u.syment.n_scnum = N_UNDEF;
2537           native->u.syment.n_value = symbol->value;
2538         }
2539       else if (bfd_is_com_section (symbol->section))
2540         {
2541           native->u.syment.n_scnum = N_UNDEF;
2542           native->u.syment.n_value = symbol->value;
2543         }
2544       else
2545         {
2546           native->u.syment.n_scnum =
2547             symbol->section->output_section->target_index;
2548           native->u.syment.n_value = (symbol->value
2549                                       + symbol->section->output_offset);
2550           if (! obj_pe (abfd))
2551             native->u.syment.n_value += symbol->section->output_section->vma;
2552
2553           /* Copy the any flags from the file header into the symbol.
2554              FIXME: Why?  */
2555           native->u.syment.n_flags = bfd_asymbol_bfd (& csym->symbol)->flags;
2556         }
2557
2558       csym->native = native;
2559     }
2560   else
2561     csym->native->u.syment.n_sclass = symbol_class;
2562
2563   return TRUE;
2564 }
2565
2566 bfd_boolean
2567 _bfd_coff_section_already_linked (bfd *abfd,
2568                                   asection *sec,
2569                                   struct bfd_link_info *info)
2570 {
2571   flagword flags;
2572   const char *name, *key;
2573   struct bfd_section_already_linked *l;
2574   struct bfd_section_already_linked_hash_entry *already_linked_list;
2575   struct coff_comdat_info *s_comdat;
2576
2577   flags = sec->flags;
2578   if ((flags & SEC_LINK_ONCE) == 0)
2579     return FALSE;
2580
2581   /* The COFF backend linker doesn't support group sections.  */
2582   if ((flags & SEC_GROUP) != 0)
2583     return FALSE;
2584
2585   name = bfd_get_section_name (abfd, sec);
2586   s_comdat = bfd_coff_get_comdat_section (abfd, sec);
2587
2588   if (s_comdat != NULL)
2589     key = s_comdat->name;
2590   else
2591     {
2592       if (CONST_STRNEQ (name, ".gnu.linkonce.")
2593           && (key = strchr (name + sizeof (".gnu.linkonce.") - 1, '.')) != NULL)
2594         key++;
2595       else
2596         /* FIXME: gcc as of 2011-09 emits sections like .text$<key>,
2597            .xdata$<key> and .pdata$<key> only the first of which has a
2598            comdat key.  Should these all match the LTO IR key?  */
2599         key = name;
2600     }
2601
2602   already_linked_list = bfd_section_already_linked_table_lookup (key);
2603
2604   for (l = already_linked_list->entry; l != NULL; l = l->next)
2605     {
2606       struct coff_comdat_info *l_comdat;
2607
2608       l_comdat = bfd_coff_get_comdat_section (l->sec->owner, l->sec);
2609
2610       /* The section names must match, and both sections must be
2611          comdat and have the same comdat name, or both sections must
2612          be non-comdat.  LTO IR plugin sections are an exception.  They
2613          are always named .gnu.linkonce.t.<key> (<key> is some string)
2614          and match any comdat section with comdat name of <key>, and
2615          any linkonce section with the same suffix, ie.
2616          .gnu.linkonce.*.<key>.  */
2617       if (((s_comdat != NULL) == (l_comdat != NULL)
2618            && strcmp (name, l->sec->name) == 0)
2619           || (l->sec->owner->flags & BFD_PLUGIN) != 0)
2620         {
2621           /* The section has already been linked.  See if we should
2622              issue a warning.  */
2623           return _bfd_handle_already_linked (sec, l, info);
2624         }
2625     }
2626
2627   /* This is the first section with this name.  Record it.  */
2628   if (!bfd_section_already_linked_table_insert (already_linked_list, sec))
2629     info->callbacks->einfo (_("%F%P: already_linked_table: %E\n"));
2630   return FALSE;
2631 }
2632
2633 /* Initialize COOKIE for input bfd ABFD. */
2634
2635 static bfd_boolean
2636 init_reloc_cookie (struct coff_reloc_cookie *cookie,
2637                    struct bfd_link_info *info ATTRIBUTE_UNUSED,
2638                    bfd *abfd)
2639 {
2640   /* Sometimes the symbol table does not yet have been loaded here.  */
2641   bfd_coff_slurp_symbol_table (abfd);
2642
2643   cookie->abfd = abfd;
2644   cookie->sym_hashes = obj_coff_sym_hashes (abfd);
2645
2646   cookie->symbols = obj_symbols (abfd);
2647
2648   return TRUE;
2649 }
2650
2651 /* Free the memory allocated by init_reloc_cookie, if appropriate.  */
2652
2653 static void
2654 fini_reloc_cookie (struct coff_reloc_cookie *cookie ATTRIBUTE_UNUSED,
2655                    bfd *abfd ATTRIBUTE_UNUSED)
2656 {
2657   /* Nothing to do.  */
2658 }
2659
2660 /* Initialize the relocation information in COOKIE for input section SEC
2661    of input bfd ABFD.  */
2662
2663 static bfd_boolean
2664 init_reloc_cookie_rels (struct coff_reloc_cookie *cookie,
2665                         struct bfd_link_info *info ATTRIBUTE_UNUSED,
2666                         bfd *abfd,
2667                         asection *sec)
2668 {
2669   if (sec->reloc_count == 0)
2670     {
2671       cookie->rels = NULL;
2672       cookie->relend = NULL;
2673       cookie->rel = NULL;
2674       return TRUE;
2675     }
2676
2677   cookie->rels = _bfd_coff_read_internal_relocs (abfd, sec, FALSE, NULL, 0, NULL);
2678
2679   if (cookie->rels == NULL)
2680     return FALSE;
2681
2682   cookie->rel = cookie->rels;
2683   cookie->relend = (cookie->rels + sec->reloc_count);
2684   return TRUE;
2685 }
2686
2687 /* Free the memory allocated by init_reloc_cookie_rels,
2688    if appropriate.  */
2689
2690 static void
2691 fini_reloc_cookie_rels (struct coff_reloc_cookie *cookie,
2692                         asection *sec)
2693 {
2694   if (cookie->rels
2695       /* PR 20401.  The relocs may not have been cached, so check first.
2696          If the relocs were loaded by init_reloc_cookie_rels() then this
2697          will be the case.  FIXME: Would performance be improved if the
2698          relocs *were* cached ?  */
2699       && coff_section_data (NULL, sec)
2700       && coff_section_data (NULL, sec)->relocs != cookie->rels)
2701     free (cookie->rels);
2702 }
2703
2704 /* Initialize the whole of COOKIE for input section SEC.  */
2705
2706 static bfd_boolean
2707 init_reloc_cookie_for_section (struct coff_reloc_cookie *cookie,
2708                                struct bfd_link_info *info,
2709                                asection *sec)
2710 {
2711   if (!init_reloc_cookie (cookie, info, sec->owner))
2712     return FALSE;
2713
2714   if (!init_reloc_cookie_rels (cookie, info, sec->owner, sec))
2715     {
2716       fini_reloc_cookie (cookie, sec->owner);
2717       return FALSE;
2718     }
2719   return TRUE;
2720 }
2721
2722 /* Free the memory allocated by init_reloc_cookie_for_section,
2723    if appropriate.  */
2724
2725 static void
2726 fini_reloc_cookie_for_section (struct coff_reloc_cookie *cookie,
2727                                asection *sec)
2728 {
2729   fini_reloc_cookie_rels (cookie, sec);
2730   fini_reloc_cookie (cookie, sec->owner);
2731 }
2732
2733 static asection *
2734 _bfd_coff_gc_mark_hook (asection *sec,
2735                         struct bfd_link_info *info ATTRIBUTE_UNUSED,
2736                         struct internal_reloc *rel ATTRIBUTE_UNUSED,
2737                         struct coff_link_hash_entry *h,
2738                         struct internal_syment *sym)
2739 {
2740   if (h != NULL)
2741     {
2742       switch (h->root.type)
2743         {
2744         case bfd_link_hash_defined:
2745         case bfd_link_hash_defweak:
2746           return h->root.u.def.section;
2747
2748         case bfd_link_hash_common:
2749           return h->root.u.c.p->section;
2750
2751         case bfd_link_hash_undefined:
2752         case bfd_link_hash_undefweak:
2753         default:
2754           break;
2755         }
2756       return NULL;
2757     }
2758
2759   return coff_section_from_bfd_index (sec->owner, sym->n_scnum);
2760 }
2761
2762 /* COOKIE->rel describes a relocation against section SEC, which is
2763    a section we've decided to keep.  Return the section that contains
2764    the relocation symbol, or NULL if no section contains it.  */
2765
2766 static asection *
2767 _bfd_coff_gc_mark_rsec (struct bfd_link_info *info, asection *sec,
2768                         coff_gc_mark_hook_fn gc_mark_hook,
2769                         struct coff_reloc_cookie *cookie)
2770 {
2771   struct coff_link_hash_entry *h;
2772
2773   h = cookie->sym_hashes[cookie->rel->r_symndx];
2774   if (h != NULL)
2775     {
2776       while (h->root.type == bfd_link_hash_indirect
2777              || h->root.type == bfd_link_hash_warning)
2778         h = (struct coff_link_hash_entry *) h->root.u.i.link;
2779
2780       return (*gc_mark_hook) (sec, info, cookie->rel, h, NULL);
2781     }
2782
2783   return (*gc_mark_hook) (sec, info, cookie->rel, NULL,
2784                           &(cookie->symbols
2785                             + obj_convert (sec->owner)[cookie->rel->r_symndx])->native->u.syment);
2786 }
2787
2788 static bfd_boolean _bfd_coff_gc_mark
2789   (struct bfd_link_info *, asection *, coff_gc_mark_hook_fn);
2790
2791 /* COOKIE->rel describes a relocation against section SEC, which is
2792    a section we've decided to keep.  Mark the section that contains
2793    the relocation symbol.  */
2794
2795 static bfd_boolean
2796 _bfd_coff_gc_mark_reloc (struct bfd_link_info *info,
2797                          asection *sec,
2798                          coff_gc_mark_hook_fn gc_mark_hook,
2799                          struct coff_reloc_cookie *cookie)
2800 {
2801   asection *rsec;
2802
2803   rsec = _bfd_coff_gc_mark_rsec (info, sec, gc_mark_hook, cookie);
2804   if (rsec && !rsec->gc_mark)
2805     {
2806       if (bfd_get_flavour (rsec->owner) != bfd_target_coff_flavour)
2807         rsec->gc_mark = 1;
2808       else if (!_bfd_coff_gc_mark (info, rsec, gc_mark_hook))
2809         return FALSE;
2810     }
2811   return TRUE;
2812 }
2813
2814 /* The mark phase of garbage collection.  For a given section, mark
2815    it and any sections in this section's group, and all the sections
2816    which define symbols to which it refers.  */
2817
2818 static bfd_boolean
2819 _bfd_coff_gc_mark (struct bfd_link_info *info,
2820                    asection *sec,
2821                    coff_gc_mark_hook_fn gc_mark_hook)
2822 {
2823   bfd_boolean ret = TRUE;
2824
2825   sec->gc_mark = 1;
2826
2827   /* Look through the section relocs.  */
2828   if ((sec->flags & SEC_RELOC) != 0
2829       && sec->reloc_count > 0)
2830     {
2831       struct coff_reloc_cookie cookie;
2832
2833       if (!init_reloc_cookie_for_section (&cookie, info, sec))
2834         ret = FALSE;
2835       else
2836         {
2837           for (; cookie.rel < cookie.relend; cookie.rel++)
2838             {
2839               if (!_bfd_coff_gc_mark_reloc (info, sec, gc_mark_hook, &cookie))
2840                 {
2841                   ret = FALSE;
2842                   break;
2843                 }
2844             }
2845           fini_reloc_cookie_for_section (&cookie, sec);
2846         }
2847     }
2848
2849   return ret;
2850 }
2851
2852 static bfd_boolean
2853 _bfd_coff_gc_mark_extra_sections (struct bfd_link_info *info,
2854                                   coff_gc_mark_hook_fn mark_hook ATTRIBUTE_UNUSED)
2855 {
2856   bfd *ibfd;
2857
2858   for (ibfd = info->input_bfds; ibfd != NULL; ibfd = ibfd->link.next)
2859     {
2860       asection *isec;
2861       bfd_boolean some_kept;
2862
2863       if (bfd_get_flavour (ibfd) != bfd_target_elf_flavour)
2864         continue;
2865
2866       /* Ensure all linker created sections are kept, and see whether
2867          any other section is already marked.  */
2868       some_kept = FALSE;
2869       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
2870         {
2871           if ((isec->flags & SEC_LINKER_CREATED) != 0)
2872             isec->gc_mark = 1;
2873           else if (isec->gc_mark)
2874             some_kept = TRUE;
2875         }
2876
2877       /* If no section in this file will be kept, then we can
2878          toss out debug sections.  */
2879       if (!some_kept)
2880         continue;
2881
2882       /* Keep debug and special sections like .comment when they are
2883          not part of a group, or when we have single-member groups.  */
2884       for (isec = ibfd->sections; isec != NULL; isec = isec->next)
2885         if ((isec->flags & SEC_DEBUGGING) != 0
2886             || (isec->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
2887           isec->gc_mark = 1;
2888     }
2889   return TRUE;
2890 }
2891
2892 /* Sweep symbols in swept sections.  Called via coff_link_hash_traverse.  */
2893
2894 static bfd_boolean
2895 coff_gc_sweep_symbol (struct coff_link_hash_entry *h,
2896                       void *data ATTRIBUTE_UNUSED)
2897 {
2898   if (h->root.type == bfd_link_hash_warning)
2899     h = (struct coff_link_hash_entry *) h->root.u.i.link;
2900
2901   if ((h->root.type == bfd_link_hash_defined
2902        || h->root.type == bfd_link_hash_defweak)
2903       && !h->root.u.def.section->gc_mark
2904       && !(h->root.u.def.section->owner->flags & DYNAMIC))
2905     {
2906       /* Do our best to hide the symbol.  */
2907       h->root.u.def.section = bfd_und_section_ptr;
2908       h->symbol_class = C_HIDDEN;
2909     }
2910
2911   return TRUE;
2912 }
2913
2914 /* The sweep phase of garbage collection.  Remove all garbage sections.  */
2915
2916 typedef bfd_boolean (*gc_sweep_hook_fn)
2917   (bfd *, struct bfd_link_info *, asection *, const struct internal_reloc *);
2918
2919 static bfd_boolean
2920 coff_gc_sweep (bfd *abfd ATTRIBUTE_UNUSED, struct bfd_link_info *info)
2921 {
2922   bfd *sub;
2923
2924   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
2925     {
2926       asection *o;
2927
2928       if (bfd_get_flavour (sub) != bfd_target_coff_flavour)
2929         continue;
2930
2931       for (o = sub->sections; o != NULL; o = o->next)
2932         {
2933             /* Keep debug and special sections.  */
2934           if ((o->flags & (SEC_DEBUGGING | SEC_LINKER_CREATED)) != 0
2935               || (o->flags & (SEC_ALLOC | SEC_LOAD | SEC_RELOC)) == 0)
2936             o->gc_mark = 1;
2937           else if (CONST_STRNEQ (o->name, ".idata")
2938                    || CONST_STRNEQ (o->name, ".pdata")
2939                    || CONST_STRNEQ (o->name, ".xdata")
2940                    || CONST_STRNEQ (o->name, ".rsrc"))
2941             o->gc_mark = 1;
2942
2943           if (o->gc_mark)
2944             continue;
2945
2946           /* Skip sweeping sections already excluded.  */
2947           if (o->flags & SEC_EXCLUDE)
2948             continue;
2949
2950           /* Since this is early in the link process, it is simple
2951              to remove a section from the output.  */
2952           o->flags |= SEC_EXCLUDE;
2953
2954           if (info->print_gc_sections && o->size != 0)
2955             _bfd_error_handler (_("Removing unused section '%s' in file '%B'"), sub, o->name);
2956
2957 #if 0
2958           /* But we also have to update some of the relocation
2959              info we collected before.  */
2960           if (gc_sweep_hook
2961               && (o->flags & SEC_RELOC) != 0
2962               && o->reloc_count > 0
2963               && !bfd_is_abs_section (o->output_section))
2964             {
2965               struct internal_reloc *internal_relocs;
2966               bfd_boolean r;
2967
2968               internal_relocs
2969                 = _bfd_coff_link_read_relocs (o->owner, o, NULL, NULL,
2970                                              info->keep_memory);
2971               if (internal_relocs == NULL)
2972                 return FALSE;
2973
2974               r = (*gc_sweep_hook) (o->owner, info, o, internal_relocs);
2975
2976               if (coff_section_data (o)->relocs != internal_relocs)
2977                 free (internal_relocs);
2978
2979               if (!r)
2980                 return FALSE;
2981             }
2982 #endif
2983         }
2984     }
2985
2986   /* Remove the symbols that were in the swept sections from the dynamic
2987      symbol table.  */
2988   coff_link_hash_traverse (coff_hash_table (info), coff_gc_sweep_symbol,
2989                            NULL);
2990
2991   return TRUE;
2992 }
2993
2994 /* Keep all sections containing symbols undefined on the command-line,
2995    and the section containing the entry symbol.  */
2996
2997 static void
2998 _bfd_coff_gc_keep (struct bfd_link_info *info)
2999 {
3000   struct bfd_sym_chain *sym;
3001
3002   for (sym = info->gc_sym_list; sym != NULL; sym = sym->next)
3003     {
3004       struct coff_link_hash_entry *h;
3005
3006       h = coff_link_hash_lookup (coff_hash_table (info), sym->name,
3007                                 FALSE, FALSE, FALSE);
3008
3009       if (h != NULL
3010           && (h->root.type == bfd_link_hash_defined
3011               || h->root.type == bfd_link_hash_defweak)
3012           && !bfd_is_abs_section (h->root.u.def.section))
3013         h->root.u.def.section->flags |= SEC_KEEP;
3014     }
3015 }
3016
3017 /* Do mark and sweep of unused sections.  */
3018
3019 bfd_boolean
3020 bfd_coff_gc_sections (bfd *abfd ATTRIBUTE_UNUSED, struct bfd_link_info *info)
3021 {
3022   bfd *sub;
3023
3024   /* FIXME: Should we implement this? */
3025 #if 0
3026   const bfd_coff_backend_data *bed = coff_backend_info (abfd);
3027
3028   if (!bed->can_gc_sections
3029       || !is_coff_hash_table (info->hash))
3030     {
3031       (*_bfd_error_handler)(_("Warning: gc-sections option ignored"));
3032       return TRUE;
3033     }
3034 #endif
3035
3036   _bfd_coff_gc_keep (info);
3037
3038   /* Grovel through relocs to find out who stays ...  */
3039   for (sub = info->input_bfds; sub != NULL; sub = sub->link.next)
3040     {
3041       asection *o;
3042
3043       if (bfd_get_flavour (sub) != bfd_target_coff_flavour)
3044         continue;
3045
3046       for (o = sub->sections; o != NULL; o = o->next)
3047         {
3048           if (((o->flags & (SEC_EXCLUDE | SEC_KEEP)) == SEC_KEEP
3049                || CONST_STRNEQ (o->name, ".vectors")
3050                || CONST_STRNEQ (o->name, ".ctors")
3051                || CONST_STRNEQ (o->name, ".dtors"))
3052               && !o->gc_mark)
3053             {
3054               if (!_bfd_coff_gc_mark (info, o, _bfd_coff_gc_mark_hook))
3055                 return FALSE;
3056             }
3057         }
3058     }
3059
3060   /* Allow the backend to mark additional target specific sections.  */
3061   _bfd_coff_gc_mark_extra_sections (info, _bfd_coff_gc_mark_hook);
3062
3063   /* ... and mark SEC_EXCLUDE for those that go.  */
3064   return coff_gc_sweep (abfd, info);
3065 }