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