1/* Support for the generic parts of most COFF variants, for BFD.
2   Copyright (C) 1990-2022 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,
23			sac@cygnus.com.  */
24/*
25SECTION
26	coff backends
27
28	BFD supports a number of different flavours of coff format.
29	The major differences between formats are the sizes and
30	alignments of fields in structures on disk, and the occasional
31	extra field.
32
33	Coff in all its varieties is implemented with a few common
34	files and a number of implementation specific files. For
35	example, the i386 coff format is implemented in the file
36	@file{coff-i386.c}.  This file @code{#include}s
37	@file{coff/i386.h} which defines the external structure of the
38	coff format for the i386, and @file{coff/internal.h} which
39	defines the internal structure. @file{coff-i386.c} also
40	defines the relocations used by the i386 coff format
41	@xref{Relocations}.
42
43SUBSECTION
44	Porting to a new version of coff
45
46	The recommended method is to select from the existing
47	implementations the version of coff which is most like the one
48	you want to use.  For example, we'll say that i386 coff is
49	the one you select, and that your coff flavour is called foo.
50	Copy @file{i386coff.c} to @file{foocoff.c}, copy
51	@file{../include/coff/i386.h} to @file{../include/coff/foo.h},
52	and add the lines to @file{targets.c} and @file{Makefile.in}
53	so that your new back end is used. Alter the shapes of the
54	structures in @file{../include/coff/foo.h} so that they match
55	what you need. You will probably also have to add
56	@code{#ifdef}s to the code in @file{coff/internal.h} and
57	@file{coffcode.h} if your version of coff is too wild.
58
59	You can verify that your new BFD backend works quite simply by
60	building @file{objdump} from the @file{binutils} directory,
61	and making sure that its version of what's going on and your
62	host system's idea (assuming it has the pretty standard coff
63	dump utility, usually called @code{att-dump} or just
64	@code{dump}) are the same.  Then clean up your code, and send
65	what you've done to Cygnus. Then your stuff will be in the
66	next release, and you won't have to keep integrating it.
67
68SUBSECTION
69	How the coff backend works
70
71SUBSUBSECTION
72	File layout
73
74	The Coff backend is split into generic routines that are
75	applicable to any Coff target and routines that are specific
76	to a particular target.  The target-specific routines are
77	further split into ones which are basically the same for all
78	Coff targets except that they use the external symbol format
79	or use different values for certain constants.
80
81	The generic routines are in @file{coffgen.c}.  These routines
82	work for any Coff target.  They use some hooks into the target
83	specific code; the hooks are in a @code{bfd_coff_backend_data}
84	structure, one of which exists for each target.
85
86	The essentially similar target-specific routines are in
87	@file{coffcode.h}.  This header file includes executable C code.
88	The various Coff targets first include the appropriate Coff
89	header file, make any special defines that are needed, and
90	then include @file{coffcode.h}.
91
92	Some of the Coff targets then also have additional routines in
93	the target source file itself.
94
95SUBSUBSECTION
96	Coff long section names
97
98	In the standard Coff object format, section names are limited to
99	the eight bytes available in the @code{s_name} field of the
100	@code{SCNHDR} section header structure.  The format requires the
101	field to be NUL-padded, but not necessarily NUL-terminated, so
102	the longest section names permitted are a full eight characters.
103
104	The Microsoft PE variants of the Coff object file format add
105	an extension to support the use of long section names.  This
106	extension is defined in section 4 of the Microsoft PE/COFF
107	specification (rev 8.1).  If a section name is too long to fit
108	into the section header's @code{s_name} field, it is instead
109	placed into the string table, and the @code{s_name} field is
110	filled with a slash ("/") followed by the ASCII decimal
111	representation of the offset of the full name relative to the
112	string table base.
113
114	Note that this implies that the extension can only be used in object
115	files, as executables do not contain a string table.  The standard
116	specifies that long section names from objects emitted into executable
117	images are to be truncated.
118
119	However, as a GNU extension, BFD can generate executable images
120	that contain a string table and long section names.  This
121	would appear to be technically valid, as the standard only says
122	that Coff debugging information is deprecated, not forbidden,
123	and in practice it works, although some tools that parse PE files
124	expecting the MS standard format may become confused; @file{PEview} is
125	one known example.
126
127	The functionality is supported in BFD by code implemented under
128	the control of the macro @code{COFF_LONG_SECTION_NAMES}.  If not
129	defined, the format does not support long section names in any way.
130	If defined, it is used to initialise a flag,
131	@code{_bfd_coff_long_section_names}, and a hook function pointer,
132	@code{_bfd_coff_set_long_section_names}, in the Coff backend data
133	structure.  The flag controls the generation of long section names
134	in output BFDs at runtime; if it is false, as it will be by default
135	when generating an executable image, long section names are truncated;
136	if true, the long section names extension is employed.  The hook
137	points to a function that allows the value of the flag to be altered
138	at runtime, on formats that support long section names at all; on
139	other formats it points to a stub that returns an error indication.
140
141	With input BFDs, the flag is set according to whether any long section
142	names are detected while reading the section headers.  For a completely
143	new BFD, the flag is set to the default for the target format.  This
144	information can be used by a client of the BFD library when deciding
145	what output format to generate, and means that a BFD that is opened
146	for read and subsequently converted to a writeable BFD and modified
147	in-place will retain whatever format it had on input.
148
149	If @code{COFF_LONG_SECTION_NAMES} is simply defined (blank), or is
150	defined to the value "1", then long section names are enabled by
151	default; if it is defined to the value zero, they are disabled by
152	default (but still accepted in input BFDs).  The header @file{coffcode.h}
153	defines a macro, @code{COFF_DEFAULT_LONG_SECTION_NAMES}, which is
154	used in the backends to initialise the backend data structure fields
155	appropriately; see the comments for further detail.
156
157SUBSUBSECTION
158	Bit twiddling
159
160	Each flavour of coff supported in BFD has its own header file
161	describing the external layout of the structures. There is also
162	an internal description of the coff layout, in
163	@file{coff/internal.h}. A major function of the
164	coff backend is swapping the bytes and twiddling the bits to
165	translate the external form of the structures into the normal
166	internal form. This is all performed in the
167	@code{bfd_swap}_@i{thing}_@i{direction} routines. Some
168	elements are different sizes between different versions of
169	coff; it is the duty of the coff version specific include file
170	to override the definitions of various packing routines in
171	@file{coffcode.h}. E.g., the size of line number entry in coff is
172	sometimes 16 bits, and sometimes 32 bits. @code{#define}ing
173	@code{PUT_LNSZ_LNNO} and @code{GET_LNSZ_LNNO} will select the
174	correct one. No doubt, some day someone will find a version of
175	coff which has a varying field size not catered to at the
176	moment. To port BFD, that person will have to add more @code{#defines}.
177	Three of the bit twiddling routines are exported to
178	@code{gdb}; @code{coff_swap_aux_in}, @code{coff_swap_sym_in}
179	and @code{coff_swap_lineno_in}. @code{GDB} reads the symbol
180	table on its own, but uses BFD to fix things up.  More of the
181	bit twiddlers are exported for @code{gas};
182	@code{coff_swap_aux_out}, @code{coff_swap_sym_out},
183	@code{coff_swap_lineno_out}, @code{coff_swap_reloc_out},
184	@code{coff_swap_filehdr_out}, @code{coff_swap_aouthdr_out},
185	@code{coff_swap_scnhdr_out}. @code{Gas} currently keeps track
186	of all the symbol table and reloc drudgery itself, thereby
187	saving the internal BFD overhead, but uses BFD to swap things
188	on the way out, making cross ports much safer.  Doing so also
189	allows BFD (and thus the linker) to use the same header files
190	as @code{gas}, which makes one avenue to disaster disappear.
191
192SUBSUBSECTION
193	Symbol reading
194
195	The simple canonical form for symbols used by BFD is not rich
196	enough to keep all the information available in a coff symbol
197	table. The back end gets around this problem by keeping the original
198	symbol table around, "behind the scenes".
199
200	When a symbol table is requested (through a call to
201	@code{bfd_canonicalize_symtab}), a request gets through to
202	@code{coff_get_normalized_symtab}. This reads the symbol table from
203	the coff file and swaps all the structures inside into the
204	internal form. It also fixes up all the pointers in the table
205	(represented in the file by offsets from the first symbol in
206	the table) into physical pointers to elements in the new
207	internal table. This involves some work since the meanings of
208	fields change depending upon context: a field that is a
209	pointer to another structure in the symbol table at one moment
210	may be the size in bytes of a structure at the next.  Another
211	pass is made over the table. All symbols which mark file names
212	(<<C_FILE>> symbols) are modified so that the internal
213	string points to the value in the auxent (the real filename)
214	rather than the normal text associated with the symbol
215	(@code{".file"}).
216
217	At this time the symbol names are moved around. Coff stores
218	all symbols less than nine characters long physically
219	within the symbol table; longer strings are kept at the end of
220	the file in the string table. This pass moves all strings
221	into memory and replaces them with pointers to the strings.
222
223	The symbol table is massaged once again, this time to create
224	the canonical table used by the BFD application. Each symbol
225	is inspected in turn, and a decision made (using the
226	@code{sclass} field) about the various flags to set in the
227	@code{asymbol}.  @xref{Symbols}. The generated canonical table
228	shares strings with the hidden internal symbol table.
229
230	Any linenumbers are read from the coff file too, and attached
231	to the symbols which own the functions the linenumbers belong to.
232
233SUBSUBSECTION
234	Symbol writing
235
236	Writing a symbol to a coff file which didn't come from a coff
237	file will lose any debugging information. The @code{asymbol}
238	structure remembers the BFD from which the symbol was taken, and on
239	output the back end makes sure that the same destination target as
240	source target is present.
241
242	When the symbols have come from a coff file then all the
243	debugging information is preserved.
244
245	Symbol tables are provided for writing to the back end in a
246	vector of pointers to pointers. This allows applications like
247	the linker to accumulate and output large symbol tables
248	without having to do too much byte copying.
249
250	This function runs through the provided symbol table and
251	patches each symbol marked as a file place holder
252	(@code{C_FILE}) to point to the next file place holder in the
253	list. It also marks each @code{offset} field in the list with
254	the offset from the first symbol of the current symbol.
255
256	Another function of this procedure is to turn the canonical
257	value form of BFD into the form used by coff. Internally, BFD
258	expects symbol values to be offsets from a section base; so a
259	symbol physically at 0x120, but in a section starting at
260	0x100, would have the value 0x20. Coff expects symbols to
261	contain their final value, so symbols have their values
262	changed at this point to reflect their sum with their owning
263	section.  This transformation uses the
264	<<output_section>> field of the @code{asymbol}'s
265	@code{asection} @xref{Sections}.
266
267	o <<coff_mangle_symbols>>
268
269	This routine runs though the provided symbol table and uses
270	the offsets generated by the previous pass and the pointers
271	generated when the symbol table was read in to create the
272	structured hierarchy required by coff. It changes each pointer
273	to a symbol into the index into the symbol table of the asymbol.
274
275	o <<coff_write_symbols>>
276
277	This routine runs through the symbol table and patches up the
278	symbols from their internal form into the coff way, calls the
279	bit twiddlers, and writes out the table to the file.
280
281*/
282
283/*
284INTERNAL_DEFINITION
285	coff_symbol_type
286
287DESCRIPTION
288	The hidden information for an <<asymbol>> is described in a
289	<<combined_entry_type>>:
290
291CODE_FRAGMENT
292.
293.typedef struct coff_ptr_struct
294.{
295.  {* Remembers the offset from the first symbol in the file for
296.     this symbol. Generated by coff_renumber_symbols.  *}
297.  unsigned int offset;
298.
299.  {* Should the value of this symbol be renumbered.  Used for
300.     XCOFF C_BSTAT symbols.  Set by coff_slurp_symbol_table.  *}
301.  unsigned int fix_value : 1;
302.
303.  {* Should the tag field of this symbol be renumbered.
304.     Created by coff_pointerize_aux.  *}
305.  unsigned int fix_tag : 1;
306.
307.  {* Should the endidx field of this symbol be renumbered.
308.     Created by coff_pointerize_aux.  *}
309.  unsigned int fix_end : 1;
310.
311.  {* Should the x_csect.x_scnlen field be renumbered.
312.     Created by coff_pointerize_aux.  *}
313.  unsigned int fix_scnlen : 1;
314.
315.  {* Fix up an XCOFF C_BINCL/C_EINCL symbol.  The value is the
316.     index into the line number entries.  Set by coff_slurp_symbol_table.  *}
317.  unsigned int fix_line : 1;
318.
319.  {* The container for the symbol structure as read and translated
320.     from the file.  *}
321.  union
322.  {
323.    union internal_auxent auxent;
324.    struct internal_syment syment;
325.  } u;
326.
327. {* Selector for the union above.  *}
328. bool is_sym;
329.
330. {* An extra pointer which can used by format based on COFF (like XCOFF)
331.    to provide extra information to their backend.  *}
332. void *extrap;
333.} combined_entry_type;
334.
335.
336.{* Each canonical asymbol really looks like this: *}
337.
338.typedef struct coff_symbol_struct
339.{
340.  {* The actual symbol which the rest of BFD works with *}
341.  asymbol symbol;
342.
343.  {* A pointer to the hidden information for this symbol *}
344.  combined_entry_type *native;
345.
346.  {* A pointer to the linenumber information for this symbol *}
347.  struct lineno_cache_entry *lineno;
348.
349.  {* Have the line numbers been relocated yet ? *}
350.  bool done_lineno;
351.} coff_symbol_type;
352
353*/
354
355#include "libiberty.h"
356
357#ifdef COFF_WITH_PE
358#include "peicode.h"
359#else
360#include "coffswap.h"
361#endif
362
363#define STRING_SIZE_SIZE 4
364
365#define DOT_DEBUG	".debug"
366#define DOT_ZDEBUG	".zdebug"
367#define GNU_LINKONCE_WI ".gnu.linkonce.wi."
368#define GNU_LINKONCE_WT ".gnu.linkonce.wt."
369#define DOT_RELOC	".reloc"
370
371#if defined(COFF_WITH_PE) || defined(COFF_GO32_EXE) || defined(COFF_GO32)
372# define COFF_WITH_EXTENDED_RELOC_COUNTER
373#endif
374
375#if defined (COFF_LONG_SECTION_NAMES)
376/* Needed to expand the inputs to BLANKOR1TOODD.  */
377#define COFFLONGSECTIONCATHELPER(x,y)    x ## y
378/* If the input macro Y is blank or '1', return an odd number; if it is
379   '0', return an even number.  Result undefined in all other cases.  */
380#define BLANKOR1TOODD(y)		 COFFLONGSECTIONCATHELPER(1,y)
381/* Defined to numerical 0 or 1 according to whether generation of long
382   section names is disabled or enabled by default.  */
383#define COFF_ENABLE_LONG_SECTION_NAMES   (BLANKOR1TOODD(COFF_LONG_SECTION_NAMES) & 1)
384/* Where long section names are supported, we allow them to be enabled
385   and disabled at runtime, so select an appropriate hook function for
386   _bfd_coff_set_long_section_names.  */
387#define COFF_LONG_SECTION_NAMES_SETTER   bfd_coff_set_long_section_names_allowed
388#else /* !defined (COFF_LONG_SECTION_NAMES) */
389/* If long section names are not supported, this stub disallows any
390   attempt to enable them at run-time.  */
391#define COFF_LONG_SECTION_NAMES_SETTER   bfd_coff_set_long_section_names_disallowed
392#endif /* defined (COFF_LONG_SECTION_NAMES) */
393
394/* Define a macro that can be used to initialise both the fields relating
395   to long section names in the backend data struct simultaneously.  */
396#if COFF_ENABLE_LONG_SECTION_NAMES
397#define COFF_DEFAULT_LONG_SECTION_NAMES  (true), COFF_LONG_SECTION_NAMES_SETTER
398#else /* !COFF_ENABLE_LONG_SECTION_NAMES */
399#define COFF_DEFAULT_LONG_SECTION_NAMES  (false), COFF_LONG_SECTION_NAMES_SETTER
400#endif /* COFF_ENABLE_LONG_SECTION_NAMES */
401
402#if defined (COFF_LONG_SECTION_NAMES)
403static bool bfd_coff_set_long_section_names_allowed
404  (bfd *, int);
405#else /* !defined (COFF_LONG_SECTION_NAMES) */
406static bool bfd_coff_set_long_section_names_disallowed
407  (bfd *, int);
408#endif /* defined (COFF_LONG_SECTION_NAMES) */
409static long sec_to_styp_flags
410  (const char *, flagword);
411static bool styp_to_sec_flags
412  (bfd *, void *, const char *, asection *, flagword *);
413static bool coff_bad_format_hook
414  (bfd *, void *);
415static void coff_set_custom_section_alignment
416  (bfd *, asection *, const struct coff_section_alignment_entry *,
417   const unsigned int);
418static bool coff_new_section_hook
419  (bfd *, asection *);
420static bool coff_set_arch_mach_hook
421  (bfd *, void *);
422static bool coff_write_relocs
423  (bfd *, int);
424static bool coff_set_flags
425  (bfd *, unsigned int *, unsigned short *);
426static bool coff_set_arch_mach
427  (bfd *, enum bfd_architecture, unsigned long) ATTRIBUTE_UNUSED;
428static bool coff_compute_section_file_positions
429  (bfd *);
430static bool coff_write_object_contents
431  (bfd *) ATTRIBUTE_UNUSED;
432static bool coff_set_section_contents
433  (bfd *, asection *, const void *, file_ptr, bfd_size_type);
434static bool coff_slurp_line_table
435  (bfd *, asection *);
436static bool coff_slurp_symbol_table
437  (bfd *);
438static enum coff_symbol_classification coff_classify_symbol
439  (bfd *, struct internal_syment *);
440static bool coff_slurp_reloc_table
441  (bfd *, asection *, asymbol **);
442static long coff_canonicalize_reloc
443  (bfd *, asection *, arelent **, asymbol **);
444#ifndef coff_mkobject_hook
445static void * coff_mkobject_hook
446  (bfd *, void *,  void *);
447#endif
448#ifdef COFF_WITH_PE
449static flagword handle_COMDAT
450  (bfd *, flagword, void *, const char *, asection *);
451#endif
452#ifdef TICOFF
453static bool ticoff0_bad_format_hook
454  (bfd *, void * );
455static bool ticoff1_bad_format_hook
456  (bfd *, void * );
457#endif
458
459/* void warning(); */
460
461#if defined (COFF_LONG_SECTION_NAMES)
462static bool
463bfd_coff_set_long_section_names_allowed (bfd *abfd, int enable)
464{
465  coff_backend_info (abfd)->_bfd_coff_long_section_names = enable;
466  return true;
467}
468#else /* !defined (COFF_LONG_SECTION_NAMES) */
469static bool
470bfd_coff_set_long_section_names_disallowed (bfd *abfd, int enable)
471{
472  (void) abfd;
473  (void) enable;
474  return false;
475}
476#endif /* defined (COFF_LONG_SECTION_NAMES) */
477
478/* Return a word with STYP_* (scnhdr.s_flags) flags set to represent
479   the incoming SEC_* flags.  The inverse of this function is
480   styp_to_sec_flags().  NOTE: If you add to/change this routine, you
481   should probably mirror the changes in styp_to_sec_flags().  */
482
483#ifndef COFF_WITH_PE
484
485/* Macros for setting debugging flags.  */
486
487#ifdef STYP_DEBUG
488#define STYP_XCOFF_DEBUG STYP_DEBUG
489#else
490#define STYP_XCOFF_DEBUG STYP_INFO
491#endif
492
493#ifdef COFF_ALIGN_IN_S_FLAGS
494#define STYP_DEBUG_INFO STYP_DSECT
495#else
496#define STYP_DEBUG_INFO STYP_INFO
497#endif
498
499static long
500sec_to_styp_flags (const char *sec_name, flagword sec_flags)
501{
502  long styp_flags = 0;
503
504  if (!strcmp (sec_name, _TEXT))
505    {
506      styp_flags = STYP_TEXT;
507    }
508  else if (!strcmp (sec_name, _DATA))
509    {
510      styp_flags = STYP_DATA;
511    }
512  else if (!strcmp (sec_name, _BSS))
513    {
514      styp_flags = STYP_BSS;
515#ifdef _COMMENT
516    }
517  else if (!strcmp (sec_name, _COMMENT))
518    {
519      styp_flags = STYP_INFO;
520#endif /* _COMMENT */
521#ifdef _LIB
522    }
523  else if (!strcmp (sec_name, _LIB))
524    {
525      styp_flags = STYP_LIB;
526#endif /* _LIB */
527#ifdef _LIT
528    }
529  else if (!strcmp (sec_name, _LIT))
530    {
531      styp_flags = STYP_LIT;
532#endif /* _LIT */
533    }
534  else if (startswith (sec_name, DOT_DEBUG)
535	   || startswith (sec_name, DOT_ZDEBUG))
536    {
537      /* Handle the XCOFF debug section and DWARF2 debug sections.  */
538      if (!sec_name[6])
539	styp_flags = STYP_XCOFF_DEBUG;
540      else
541	styp_flags = STYP_DEBUG_INFO;
542    }
543  else if (startswith (sec_name, ".stab"))
544    {
545      styp_flags = STYP_DEBUG_INFO;
546    }
547#ifdef COFF_LONG_SECTION_NAMES
548  else if (startswith (sec_name, GNU_LINKONCE_WI)
549	   || startswith (sec_name, GNU_LINKONCE_WT))
550    {
551      styp_flags = STYP_DEBUG_INFO;
552    }
553#endif
554#ifdef RS6000COFF_C
555  else if (!strcmp (sec_name, _TDATA))
556    {
557      styp_flags = STYP_TDATA;
558    }
559  else if (!strcmp (sec_name, _TBSS))
560    {
561      styp_flags = STYP_TBSS;
562    }
563  else if (!strcmp (sec_name, _PAD))
564    {
565      styp_flags = STYP_PAD;
566    }
567  else if (!strcmp (sec_name, _LOADER))
568    {
569      styp_flags = STYP_LOADER;
570    }
571  else if (!strcmp (sec_name, _EXCEPT))
572    {
573      styp_flags = STYP_EXCEPT;
574    }
575  else if (!strcmp (sec_name, _TYPCHK))
576    {
577      styp_flags = STYP_TYPCHK;
578    }
579  else if (sec_flags & SEC_DEBUGGING)
580    {
581      int i;
582
583      for (i = 0; i < XCOFF_DWSECT_NBR_NAMES; i++)
584	if (!strcmp (sec_name, xcoff_dwsect_names[i].xcoff_name))
585	  {
586	    styp_flags = STYP_DWARF | xcoff_dwsect_names[i].flag;
587	    break;
588	  }
589    }
590#endif
591  /* Try and figure out what it should be */
592  else if (sec_flags & SEC_CODE)
593    {
594      styp_flags = STYP_TEXT;
595    }
596  else if (sec_flags & SEC_DATA)
597    {
598      styp_flags = STYP_DATA;
599    }
600  else if (sec_flags & SEC_READONLY)
601    {
602#ifdef STYP_LIT			/* 29k readonly text/data section */
603      styp_flags = STYP_LIT;
604#else
605      styp_flags = STYP_TEXT;
606#endif /* STYP_LIT */
607    }
608  else if (sec_flags & SEC_LOAD)
609    {
610      styp_flags = STYP_TEXT;
611    }
612  else if (sec_flags & SEC_ALLOC)
613    {
614      styp_flags = STYP_BSS;
615    }
616
617#ifdef STYP_CLINK
618  if (sec_flags & SEC_TIC54X_CLINK)
619    styp_flags |= STYP_CLINK;
620#endif
621
622#ifdef STYP_BLOCK
623  if (sec_flags & SEC_TIC54X_BLOCK)
624    styp_flags |= STYP_BLOCK;
625#endif
626
627#ifdef STYP_NOLOAD
628  if ((sec_flags & (SEC_NEVER_LOAD | SEC_COFF_SHARED_LIBRARY)) != 0)
629    styp_flags |= STYP_NOLOAD;
630#endif
631
632  return styp_flags;
633}
634
635#else /* COFF_WITH_PE */
636
637/* The PE version; see above for the general comments.  The non-PE
638   case seems to be more guessing, and breaks PE format; specifically,
639   .rdata is readonly, but it sure ain't text.  Really, all this
640   should be set up properly in gas (or whatever assembler is in use),
641   and honor whatever objcopy/strip, etc. sent us as input.  */
642
643static long
644sec_to_styp_flags (const char *sec_name, flagword sec_flags)
645{
646  long styp_flags = 0;
647  bool is_dbg = false;
648
649  if (startswith (sec_name, DOT_DEBUG)
650      || startswith (sec_name, DOT_ZDEBUG)
651#ifdef COFF_LONG_SECTION_NAMES
652      || startswith (sec_name, GNU_LINKONCE_WI)
653      || startswith (sec_name, GNU_LINKONCE_WT)
654#endif
655      || startswith (sec_name, ".stab"))
656    is_dbg = true;
657
658  /* caution: there are at least three groups of symbols that have
659     very similar bits and meanings: IMAGE_SCN*, SEC_*, and STYP_*.
660     SEC_* are the BFD internal flags, used for generic BFD
661     information.  STYP_* are the COFF section flags which appear in
662     COFF files.  IMAGE_SCN_* are the PE section flags which appear in
663     PE files.  The STYP_* flags and the IMAGE_SCN_* flags overlap,
664     but there are more IMAGE_SCN_* flags.  */
665
666  /* FIXME: There is no gas syntax to specify the debug section flag.  */
667  if (is_dbg)
668    {
669      sec_flags &= (SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD
670		    | SEC_LINK_DUPLICATES_SAME_CONTENTS
671		    | SEC_LINK_DUPLICATES_SAME_SIZE);
672      sec_flags |= SEC_DEBUGGING | SEC_READONLY;
673    }
674
675  /* skip LOAD */
676  /* READONLY later */
677  /* skip RELOC */
678  if ((sec_flags & SEC_CODE) != 0)
679    styp_flags |= IMAGE_SCN_CNT_CODE;
680  if ((sec_flags & (SEC_DATA | SEC_DEBUGGING)) != 0)
681    styp_flags |= IMAGE_SCN_CNT_INITIALIZED_DATA;
682  if ((sec_flags & SEC_ALLOC) != 0 && (sec_flags & SEC_LOAD) == 0)
683    styp_flags |= IMAGE_SCN_CNT_UNINITIALIZED_DATA;  /* ==STYP_BSS */
684  /* skip ROM */
685  /* skip constRUCTOR */
686  /* skip CONTENTS */
687#ifndef COFF_IMAGE_WITH_PE
688  /* I don't think any of the IMAGE_SCN_LNK_* flags set below should be set
689     when the output is PE. Only object files should have them, for the linker
690     to consume.  */
691  if ((sec_flags & SEC_IS_COMMON) != 0)
692    styp_flags |= IMAGE_SCN_LNK_COMDAT;
693#endif
694  if ((sec_flags & SEC_DEBUGGING) != 0)
695    styp_flags |= IMAGE_SCN_MEM_DISCARDABLE;
696  if ((sec_flags & (SEC_EXCLUDE | SEC_NEVER_LOAD)) != 0 && !is_dbg)
697#ifdef COFF_IMAGE_WITH_PE
698    styp_flags |= IMAGE_SCN_MEM_DISCARDABLE;
699#else
700    styp_flags |= IMAGE_SCN_LNK_REMOVE;
701#endif
702  /* skip IN_MEMORY */
703  /* skip SORT */
704#ifndef COFF_IMAGE_WITH_PE
705  if (sec_flags & SEC_LINK_ONCE)
706    styp_flags |= IMAGE_SCN_LNK_COMDAT;
707  if ((sec_flags
708       & (SEC_LINK_DUPLICATES_DISCARD | SEC_LINK_DUPLICATES_SAME_CONTENTS
709	  | SEC_LINK_DUPLICATES_SAME_SIZE)) != 0)
710    styp_flags |= IMAGE_SCN_LNK_COMDAT;
711#endif
712
713  /* skip LINKER_CREATED */
714
715  if ((sec_flags & SEC_COFF_NOREAD) == 0)
716    styp_flags |= IMAGE_SCN_MEM_READ;     /* Invert NOREAD for read.  */
717  if ((sec_flags & SEC_READONLY) == 0)
718    styp_flags |= IMAGE_SCN_MEM_WRITE;    /* Invert READONLY for write.  */
719  if (sec_flags & SEC_CODE)
720    styp_flags |= IMAGE_SCN_MEM_EXECUTE;  /* CODE->EXECUTE.  */
721  if (sec_flags & SEC_COFF_SHARED)
722    styp_flags |= IMAGE_SCN_MEM_SHARED;   /* Shared remains meaningful.  */
723
724  return styp_flags;
725}
726
727#endif /* COFF_WITH_PE */
728
729/* Return a word with SEC_* flags set to represent the incoming STYP_*
730   flags (from scnhdr.s_flags).  The inverse of this function is
731   sec_to_styp_flags().  NOTE: If you add to/change this routine, you
732   should probably mirror the changes in sec_to_styp_flags().  */
733
734#ifndef COFF_WITH_PE
735
736static bool
737styp_to_sec_flags (bfd *abfd,
738		   void * hdr,
739		   const char *name,
740		   asection *section ATTRIBUTE_UNUSED,
741		   flagword *flags_ptr)
742{
743  struct internal_scnhdr *internal_s = (struct internal_scnhdr *) hdr;
744  unsigned long styp_flags = internal_s->s_flags;
745  flagword sec_flags = 0;
746
747#ifdef STYP_BLOCK
748  if (styp_flags & STYP_BLOCK)
749    sec_flags |= SEC_TIC54X_BLOCK;
750#endif
751
752#ifdef STYP_CLINK
753  if (styp_flags & STYP_CLINK)
754    sec_flags |= SEC_TIC54X_CLINK;
755#endif
756
757#ifdef STYP_NOLOAD
758  if (styp_flags & STYP_NOLOAD)
759    sec_flags |= SEC_NEVER_LOAD;
760#endif /* STYP_NOLOAD */
761
762  /* For 386 COFF, at least, an unloadable text or data section is
763     actually a shared library section.  */
764  if (styp_flags & STYP_TEXT)
765    {
766      if (sec_flags & SEC_NEVER_LOAD)
767	sec_flags |= SEC_CODE | SEC_COFF_SHARED_LIBRARY;
768      else
769	sec_flags |= SEC_CODE | SEC_LOAD | SEC_ALLOC;
770    }
771  else if (styp_flags & STYP_DATA)
772    {
773      if (sec_flags & SEC_NEVER_LOAD)
774	sec_flags |= SEC_DATA | SEC_COFF_SHARED_LIBRARY;
775      else
776	sec_flags |= SEC_DATA | SEC_LOAD | SEC_ALLOC;
777    }
778  else if (styp_flags & STYP_BSS)
779    {
780#ifdef BSS_NOLOAD_IS_SHARED_LIBRARY
781      if (sec_flags & SEC_NEVER_LOAD)
782	sec_flags |= SEC_ALLOC | SEC_COFF_SHARED_LIBRARY;
783      else
784#endif
785	sec_flags |= SEC_ALLOC;
786    }
787  else if (styp_flags & STYP_INFO)
788    {
789      /* We mark these as SEC_DEBUGGING, but only if COFF_PAGE_SIZE is
790	 defined.  coff_compute_section_file_positions uses
791	 COFF_PAGE_SIZE to ensure that the low order bits of the
792	 section VMA and the file offset match.  If we don't know
793	 COFF_PAGE_SIZE, we can't ensure the correct correspondence,
794	 and demand page loading of the file will fail.  */
795#if defined (COFF_PAGE_SIZE) && !defined (COFF_ALIGN_IN_S_FLAGS)
796      sec_flags |= SEC_DEBUGGING;
797#endif
798    }
799  else if (styp_flags & STYP_PAD)
800    sec_flags = 0;
801#ifdef RS6000COFF_C
802  else if (styp_flags & STYP_TDATA)
803    {
804      if (sec_flags & SEC_NEVER_LOAD)
805	sec_flags |= SEC_DATA | SEC_THREAD_LOCAL | SEC_COFF_SHARED_LIBRARY;
806      else
807	sec_flags |= SEC_DATA | SEC_THREAD_LOCAL | SEC_LOAD | SEC_ALLOC;
808    }
809  else if (styp_flags & STYP_TBSS)
810    {
811#ifdef BSS_NOLOAD_IS_SHARED_LIBRARY
812      if (sec_flags & SEC_NEVER_LOAD)
813	sec_flags |= SEC_ALLOC | SEC_THREAD_LOCAL | SEC_COFF_SHARED_LIBRARY;
814      else
815#endif
816	sec_flags |= SEC_ALLOC | SEC_THREAD_LOCAL;
817    }
818  else if (styp_flags & STYP_EXCEPT)
819    sec_flags |= SEC_LOAD;
820  else if (styp_flags & STYP_LOADER)
821    sec_flags |= SEC_LOAD;
822  else if (styp_flags & STYP_TYPCHK)
823    sec_flags |= SEC_LOAD;
824  else if (styp_flags & STYP_DWARF)
825    sec_flags |= SEC_DEBUGGING;
826#endif
827  else if (strcmp (name, _TEXT) == 0)
828    {
829      if (sec_flags & SEC_NEVER_LOAD)
830	sec_flags |= SEC_CODE | SEC_COFF_SHARED_LIBRARY;
831      else
832	sec_flags |= SEC_CODE | SEC_LOAD | SEC_ALLOC;
833    }
834  else if (strcmp (name, _DATA) == 0)
835    {
836      if (sec_flags & SEC_NEVER_LOAD)
837	sec_flags |= SEC_DATA | SEC_COFF_SHARED_LIBRARY;
838      else
839	sec_flags |= SEC_DATA | SEC_LOAD | SEC_ALLOC;
840    }
841  else if (strcmp (name, _BSS) == 0)
842    {
843#ifdef BSS_NOLOAD_IS_SHARED_LIBRARY
844      if (sec_flags & SEC_NEVER_LOAD)
845	sec_flags |= SEC_ALLOC | SEC_COFF_SHARED_LIBRARY;
846      else
847#endif
848	sec_flags |= SEC_ALLOC;
849    }
850  else if (startswith (name, DOT_DEBUG)
851	   || startswith (name, DOT_ZDEBUG)
852#ifdef _COMMENT
853	   || strcmp (name, _COMMENT) == 0
854#endif
855#ifdef COFF_LONG_SECTION_NAMES
856	   || startswith (name, GNU_LINKONCE_WI)
857	   || startswith (name, GNU_LINKONCE_WT)
858#endif
859	   || startswith (name, ".stab"))
860    {
861#ifdef COFF_PAGE_SIZE
862      sec_flags |= SEC_DEBUGGING;
863#endif
864    }
865#ifdef _LIB
866  else if (strcmp (name, _LIB) == 0)
867    ;
868#endif
869#ifdef _LIT
870  else if (strcmp (name, _LIT) == 0)
871    sec_flags = SEC_LOAD | SEC_ALLOC | SEC_READONLY;
872#endif
873  else
874    sec_flags |= SEC_ALLOC | SEC_LOAD;
875
876#ifdef STYP_LIT			/* A29k readonly text/data section type.  */
877  if ((styp_flags & STYP_LIT) == STYP_LIT)
878    sec_flags = (SEC_LOAD | SEC_ALLOC | SEC_READONLY);
879#endif /* STYP_LIT */
880
881#ifdef STYP_OTHER_LOAD		/* Other loaded sections.  */
882  if (styp_flags & STYP_OTHER_LOAD)
883    sec_flags = (SEC_LOAD | SEC_ALLOC);
884#endif /* STYP_SDATA */
885
886  if ((bfd_applicable_section_flags (abfd) & SEC_SMALL_DATA) != 0
887      && (startswith (name, ".sbss")
888	  || startswith (name, ".sdata")))
889    sec_flags |= SEC_SMALL_DATA;
890
891#if defined (COFF_LONG_SECTION_NAMES) && defined (COFF_SUPPORT_GNU_LINKONCE)
892  /* As a GNU extension, if the name begins with .gnu.linkonce, we
893     only link a single copy of the section.  This is used to support
894     g++.  g++ will emit each template expansion in its own section.
895     The symbols will be defined as weak, so that multiple definitions
896     are permitted.  The GNU linker extension is to actually discard
897     all but one of the sections.  */
898  if (startswith (name, ".gnu.linkonce"))
899    sec_flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
900#endif
901
902  if (flags_ptr == NULL)
903    return false;
904
905  * flags_ptr = sec_flags;
906  return true;
907}
908
909#else /* COFF_WITH_PE */
910
911static flagword
912handle_COMDAT (bfd * abfd,
913	       flagword sec_flags,
914	       void * hdr,
915	       const char *name,
916	       asection *section)
917{
918  struct internal_scnhdr *internal_s = (struct internal_scnhdr *) hdr;
919  bfd_byte *esymstart, *esym, *esymend;
920  int seen_state = 0;
921  char *target_name = NULL;
922
923  sec_flags |= SEC_LINK_ONCE;
924
925  /* Unfortunately, the PE format stores essential information in
926     the symbol table, of all places.  We need to extract that
927     information now, so that objdump and the linker will know how
928     to handle the section without worrying about the symbols.  We
929     can't call slurp_symtab, because the linker doesn't want the
930     swapped symbols.  */
931
932  /* COMDAT sections are special.  The first symbol is the section
933     symbol, which tells what kind of COMDAT section it is.  The
934     second symbol is the "comdat symbol" - the one with the
935     unique name.  GNU uses the section symbol for the unique
936     name; MS uses ".text" for every comdat section.  Sigh.  - DJ */
937
938  /* This is not mirrored in sec_to_styp_flags(), but there
939     doesn't seem to be a need to, either, and it would at best be
940     rather messy.  */
941
942  if (! _bfd_coff_get_external_symbols (abfd))
943    return sec_flags;
944
945  esymstart = esym = (bfd_byte *) obj_coff_external_syms (abfd);
946  esymend = esym + obj_raw_syment_count (abfd) * bfd_coff_symesz (abfd);
947
948  while (esym < esymend)
949    {
950      struct internal_syment isym;
951      char buf[SYMNMLEN + 1];
952      const char *symname;
953
954      bfd_coff_swap_sym_in (abfd, esym, & isym);
955
956      BFD_ASSERT (sizeof (internal_s->s_name) <= SYMNMLEN);
957
958      if (isym.n_scnum == section->target_index)
959	{
960	  /* According to the MSVC documentation, the first
961	     TWO entries with the section # are both of
962	     interest to us.  The first one is the "section
963	     symbol" (section name).  The second is the comdat
964	     symbol name.  Here, we've found the first
965	     qualifying entry; we distinguish it from the
966	     second with a state flag.
967
968	     In the case of gas-generated (at least until that
969	     is fixed) .o files, it isn't necessarily the
970	     second one.  It may be some other later symbol.
971
972	     Since gas also doesn't follow MS conventions and
973	     emits the section similar to .text$<name>, where
974	     <something> is the name we're looking for, we
975	     distinguish the two as follows:
976
977	     If the section name is simply a section name (no
978	     $) we presume it's MS-generated, and look at
979	     precisely the second symbol for the comdat name.
980	     If the section name has a $, we assume it's
981	     gas-generated, and look for <something> (whatever
982	     follows the $) as the comdat symbol.  */
983
984	  /* All 3 branches use this.  */
985	  symname = _bfd_coff_internal_syment_name (abfd, &isym, buf);
986
987	  /* PR 17512 file: 078-11867-0.004  */
988	  if (symname == NULL)
989	    {
990	      _bfd_error_handler (_("%pB: unable to load COMDAT section name"),
991				  abfd);
992	      break;
993	    }
994
995	  switch (seen_state)
996	    {
997	    case 0:
998	      {
999		/* The first time we've seen the symbol.  */
1000		union internal_auxent aux;
1001
1002		/* If it isn't the stuff we're expecting, die;
1003		   The MS documentation is vague, but it
1004		   appears that the second entry serves BOTH
1005		   as the comdat symbol and the defining
1006		   symbol record (either C_STAT or C_EXT,
1007		   possibly with an aux entry with debug
1008		   information if it's a function.)  It
1009		   appears the only way to find the second one
1010		   is to count.  (On Intel, they appear to be
1011		   adjacent, but on Alpha, they have been
1012		   found separated.)
1013
1014		   Here, we think we've found the first one,
1015		   but there's some checking we can do to be
1016		   sure.  */
1017
1018		if (! ((isym.n_sclass == C_STAT
1019			|| isym.n_sclass == C_EXT)
1020		       && BTYPE (isym.n_type) == T_NULL
1021		       && isym.n_value == 0))
1022		  {
1023		    /* Malformed input files can trigger this test.
1024		       cf PR 21781.  */
1025		    _bfd_error_handler (_("%pB: error: unexpected symbol '%s' in COMDAT section"),
1026					abfd, symname);
1027		    goto breakloop;
1028		  }
1029
1030		/* FIXME LATER: MSVC generates section names
1031		   like .text for comdats.  Gas generates
1032		   names like .text$foo__Fv (in the case of a
1033		   function).  See comment above for more.  */
1034
1035		if (isym.n_sclass == C_STAT && strcmp (name, symname) != 0)
1036		  /* xgettext:c-format */
1037		  _bfd_error_handler (_("%pB: warning: COMDAT symbol '%s'"
1038					" does not match section name '%s'"),
1039				      abfd, symname, name);
1040
1041		seen_state = 1;
1042
1043		/* PR 17512: file: e2cfe54f.  */
1044		if (esym + bfd_coff_symesz (abfd) >= esymend)
1045		  {
1046		    /* xgettext:c-format */
1047		    _bfd_error_handler (_("%pB: warning: no symbol for"
1048					  " section '%s' found"),
1049					abfd, symname);
1050		    break;
1051		  }
1052		/* This is the section symbol.  */
1053		bfd_coff_swap_aux_in (abfd, (esym + bfd_coff_symesz (abfd)),
1054				      isym.n_type, isym.n_sclass,
1055				      0, isym.n_numaux, & aux);
1056
1057		target_name = strchr (name, '$');
1058		if (target_name != NULL)
1059		  {
1060		    /* Gas mode.  */
1061		    seen_state = 2;
1062		    /* Skip the `$'.  */
1063		    target_name += 1;
1064		  }
1065
1066		/* FIXME: Microsoft uses NODUPLICATES and
1067		   ASSOCIATIVE, but gnu uses ANY and
1068		   SAME_SIZE.  Unfortunately, gnu doesn't do
1069		   the comdat symbols right.  So, until we can
1070		   fix it to do the right thing, we are
1071		   temporarily disabling comdats for the MS
1072		   types (they're used in DLLs and C++, but we
1073		   don't support *their* C++ libraries anyway
1074		   - DJ.  */
1075
1076		/* Cygwin does not follow the MS style, and
1077		   uses ANY and SAME_SIZE where NODUPLICATES
1078		   and ASSOCIATIVE should be used.  For
1079		   Interix, we just do the right thing up
1080		   front.  */
1081
1082		switch (aux.x_scn.x_comdat)
1083		  {
1084		  case IMAGE_COMDAT_SELECT_NODUPLICATES:
1085#ifdef STRICT_PE_FORMAT
1086		    sec_flags |= SEC_LINK_DUPLICATES_ONE_ONLY;
1087#else
1088		    sec_flags &= ~SEC_LINK_ONCE;
1089#endif
1090		    break;
1091
1092		  case IMAGE_COMDAT_SELECT_ANY:
1093		    sec_flags |= SEC_LINK_DUPLICATES_DISCARD;
1094		    break;
1095
1096		  case IMAGE_COMDAT_SELECT_SAME_SIZE:
1097		    sec_flags |= SEC_LINK_DUPLICATES_SAME_SIZE;
1098		    break;
1099
1100		  case IMAGE_COMDAT_SELECT_EXACT_MATCH:
1101		    /* Not yet fully implemented ??? */
1102		    sec_flags |= SEC_LINK_DUPLICATES_SAME_CONTENTS;
1103		    break;
1104
1105		    /* debug$S gets this case; other
1106		       implications ??? */
1107
1108		    /* There may be no symbol... we'll search
1109		       the whole table... Is this the right
1110		       place to play this game? Or should we do
1111		       it when reading it in.  */
1112		  case IMAGE_COMDAT_SELECT_ASSOCIATIVE:
1113#ifdef STRICT_PE_FORMAT
1114		    /* FIXME: This is not currently implemented.  */
1115		    sec_flags |= SEC_LINK_DUPLICATES_DISCARD;
1116#else
1117		    sec_flags &= ~SEC_LINK_ONCE;
1118#endif
1119		    break;
1120
1121		  default:  /* 0 means "no symbol" */
1122		    /* debug$F gets this case; other
1123		       implications ??? */
1124		    sec_flags |= SEC_LINK_DUPLICATES_DISCARD;
1125		    break;
1126		  }
1127	      }
1128	      break;
1129
1130	    case 2:
1131	      /* Gas mode: the first matching on partial name.  */
1132
1133#ifndef TARGET_UNDERSCORE
1134#define TARGET_UNDERSCORE 0
1135#endif
1136	      /* Is this the name we're looking for ?  */
1137	      if (strcmp (target_name,
1138			  symname + (TARGET_UNDERSCORE ? 1 : 0)) != 0)
1139		{
1140		  /* Not the name we're looking for */
1141		  esym += (isym.n_numaux + 1) * bfd_coff_symesz (abfd);
1142		  continue;
1143		}
1144	      /* Fall through.  */
1145	    case 1:
1146	      /* MSVC mode: the lexically second symbol (or
1147		 drop through from the above).  */
1148	      {
1149		char *newname;
1150		size_t amt;
1151
1152		/* This must the second symbol with the
1153		   section #.  It is the actual symbol name.
1154		   Intel puts the two adjacent, but Alpha (at
1155		   least) spreads them out.  */
1156
1157		amt = sizeof (struct coff_comdat_info);
1158		coff_section_data (abfd, section)->comdat
1159		  = (struct coff_comdat_info *) bfd_alloc (abfd, amt);
1160		if (coff_section_data (abfd, section)->comdat == NULL)
1161		  abort ();
1162
1163		coff_section_data (abfd, section)->comdat->symbol =
1164		  (esym - esymstart) / bfd_coff_symesz (abfd);
1165
1166		amt = strlen (symname) + 1;
1167		newname = (char *) bfd_alloc (abfd, amt);
1168		if (newname == NULL)
1169		  abort ();
1170
1171		strcpy (newname, symname);
1172		coff_section_data (abfd, section)->comdat->name
1173		  = newname;
1174	      }
1175
1176	      goto breakloop;
1177	    }
1178	}
1179
1180      esym += (isym.n_numaux + 1) * bfd_coff_symesz (abfd);
1181    }
1182
1183 breakloop:
1184  return sec_flags;
1185}
1186
1187
1188/* The PE version; see above for the general comments.
1189
1190   Since to set the SEC_LINK_ONCE and associated flags, we have to
1191   look at the symbol table anyway, we return the symbol table index
1192   of the symbol being used as the COMDAT symbol.  This is admittedly
1193   ugly, but there's really nowhere else that we have access to the
1194   required information.  FIXME: Is the COMDAT symbol index used for
1195   any purpose other than objdump?  */
1196
1197static bool
1198styp_to_sec_flags (bfd *abfd,
1199		   void * hdr,
1200		   const char *name,
1201		   asection *section,
1202		   flagword *flags_ptr)
1203{
1204  struct internal_scnhdr *internal_s = (struct internal_scnhdr *) hdr;
1205  unsigned long styp_flags = internal_s->s_flags;
1206  flagword sec_flags;
1207  bool result = true;
1208  bool is_dbg = false;
1209
1210  if (startswith (name, DOT_DEBUG)
1211      || startswith (name, DOT_ZDEBUG)
1212#ifdef COFF_LONG_SECTION_NAMES
1213      || startswith (name, GNU_LINKONCE_WI)
1214      || startswith (name, GNU_LINKONCE_WT)
1215      /* FIXME: These definitions ought to be in a header file.  */
1216#define GNU_DEBUGLINK		".gnu_debuglink"
1217#define GNU_DEBUGALTLINK	".gnu_debugaltlink"
1218      || startswith (name, GNU_DEBUGLINK)
1219      || startswith (name, GNU_DEBUGALTLINK)
1220#endif
1221      || startswith (name, ".stab"))
1222    is_dbg = true;
1223  /* Assume read only unless IMAGE_SCN_MEM_WRITE is specified.  */
1224  sec_flags = SEC_READONLY;
1225
1226  /* If section disallows read, then set the NOREAD flag. */
1227  if ((styp_flags & IMAGE_SCN_MEM_READ) == 0)
1228    sec_flags |= SEC_COFF_NOREAD;
1229
1230  /* Process each flag bit in styp_flags in turn.  */
1231  while (styp_flags)
1232    {
1233      unsigned long flag = styp_flags & - styp_flags;
1234      char * unhandled = NULL;
1235
1236      styp_flags &= ~ flag;
1237
1238      /* We infer from the distinct read/write/execute bits the settings
1239	 of some of the bfd flags; the actual values, should we need them,
1240	 are also in pei_section_data (abfd, section)->pe_flags.  */
1241
1242      switch (flag)
1243	{
1244	case STYP_DSECT:
1245	  unhandled = "STYP_DSECT";
1246	  break;
1247	case STYP_GROUP:
1248	  unhandled = "STYP_GROUP";
1249	  break;
1250	case STYP_COPY:
1251	  unhandled = "STYP_COPY";
1252	  break;
1253	case STYP_OVER:
1254	  unhandled = "STYP_OVER";
1255	  break;
1256#ifdef SEC_NEVER_LOAD
1257	case STYP_NOLOAD:
1258	  sec_flags |= SEC_NEVER_LOAD;
1259	  break;
1260#endif
1261	case IMAGE_SCN_MEM_READ:
1262	  sec_flags &= ~SEC_COFF_NOREAD;
1263	  break;
1264	case IMAGE_SCN_TYPE_NO_PAD:
1265	  /* Skip.  */
1266	  break;
1267	case IMAGE_SCN_LNK_OTHER:
1268	  unhandled = "IMAGE_SCN_LNK_OTHER";
1269	  break;
1270	case IMAGE_SCN_MEM_NOT_CACHED:
1271	  unhandled = "IMAGE_SCN_MEM_NOT_CACHED";
1272	  break;
1273	case IMAGE_SCN_MEM_NOT_PAGED:
1274	  /* Generate a warning message rather using the 'unhandled'
1275	     variable as this will allow some .sys files generate by
1276	     other toolchains to be processed.  See bugzilla issue 196.  */
1277	  /* xgettext:c-format */
1278	  _bfd_error_handler (_("%pB: warning: ignoring section flag"
1279				" %s in section %s"),
1280			      abfd, "IMAGE_SCN_MEM_NOT_PAGED", name);
1281	  break;
1282	case IMAGE_SCN_MEM_EXECUTE:
1283	  sec_flags |= SEC_CODE;
1284	  break;
1285	case IMAGE_SCN_MEM_WRITE:
1286	  sec_flags &= ~ SEC_READONLY;
1287	  break;
1288	case IMAGE_SCN_MEM_DISCARDABLE:
1289	  /* The MS PE spec says that debug sections are DISCARDABLE,
1290	     but the presence of a DISCARDABLE flag does not necessarily
1291	     mean that a given section contains debug information.  Thus
1292	     we only set the SEC_DEBUGGING flag on sections that we
1293	     recognise as containing debug information.  */
1294	     if (is_dbg
1295#ifdef _COMMENT
1296	      || strcmp (name, _COMMENT) == 0
1297#endif
1298	      )
1299	    {
1300	      sec_flags |= SEC_DEBUGGING | SEC_READONLY;
1301	    }
1302	  break;
1303	case IMAGE_SCN_MEM_SHARED:
1304	  sec_flags |= SEC_COFF_SHARED;
1305	  break;
1306	case IMAGE_SCN_LNK_REMOVE:
1307	  if (!is_dbg)
1308	    sec_flags |= SEC_EXCLUDE;
1309	  break;
1310	case IMAGE_SCN_CNT_CODE:
1311	  sec_flags |= SEC_CODE | SEC_ALLOC | SEC_LOAD;
1312	  break;
1313	case IMAGE_SCN_CNT_INITIALIZED_DATA:
1314	  if (is_dbg)
1315	    sec_flags |= SEC_DEBUGGING;
1316	  else
1317	    sec_flags |= SEC_DATA | SEC_ALLOC | SEC_LOAD;
1318	  break;
1319	case IMAGE_SCN_CNT_UNINITIALIZED_DATA:
1320	  sec_flags |= SEC_ALLOC;
1321	  break;
1322	case IMAGE_SCN_LNK_INFO:
1323	  /* We mark these as SEC_DEBUGGING, but only if COFF_PAGE_SIZE is
1324	     defined.  coff_compute_section_file_positions uses
1325	     COFF_PAGE_SIZE to ensure that the low order bits of the
1326	     section VMA and the file offset match.  If we don't know
1327	     COFF_PAGE_SIZE, we can't ensure the correct correspondence,
1328	     and demand page loading of the file will fail.  */
1329#ifdef COFF_PAGE_SIZE
1330	  sec_flags |= SEC_DEBUGGING;
1331#endif
1332	  break;
1333	case IMAGE_SCN_LNK_COMDAT:
1334	  /* COMDAT gets very special treatment.  */
1335	  sec_flags = handle_COMDAT (abfd, sec_flags, hdr, name, section);
1336	  break;
1337	default:
1338	  /* Silently ignore for now.  */
1339	  break;
1340	}
1341
1342      /* If the section flag was not handled, report it here.  */
1343      if (unhandled != NULL)
1344	{
1345	  _bfd_error_handler
1346	    /* xgettext:c-format */
1347	    (_("%pB (%s): section flag %s (%#lx) ignored"),
1348	     abfd, name, unhandled, flag);
1349	  result = false;
1350	}
1351    }
1352
1353  if ((bfd_applicable_section_flags (abfd) & SEC_SMALL_DATA) != 0
1354      && (startswith (name, ".sbss")
1355	  || startswith (name, ".sdata")))
1356    sec_flags |= SEC_SMALL_DATA;
1357
1358#if defined (COFF_LONG_SECTION_NAMES) && defined (COFF_SUPPORT_GNU_LINKONCE)
1359  /* As a GNU extension, if the name begins with .gnu.linkonce, we
1360     only link a single copy of the section.  This is used to support
1361     g++.  g++ will emit each template expansion in its own section.
1362     The symbols will be defined as weak, so that multiple definitions
1363     are permitted.  The GNU linker extension is to actually discard
1364     all but one of the sections.  */
1365  if (startswith (name, ".gnu.linkonce"))
1366    sec_flags |= SEC_LINK_ONCE | SEC_LINK_DUPLICATES_DISCARD;
1367#endif
1368
1369  if (flags_ptr)
1370    * flags_ptr = sec_flags;
1371
1372  return result;
1373}
1374
1375#endif /* COFF_WITH_PE */
1376
1377#define	get_index(symbol)	((symbol)->udata.i)
1378
1379/*
1380INTERNAL_DEFINITION
1381	bfd_coff_backend_data
1382
1383CODE_FRAGMENT
1384
1385.{* COFF symbol classifications.  *}
1386.
1387.enum coff_symbol_classification
1388.{
1389.  {* Global symbol.  *}
1390.  COFF_SYMBOL_GLOBAL,
1391.  {* Common symbol.  *}
1392.  COFF_SYMBOL_COMMON,
1393.  {* Undefined symbol.  *}
1394.  COFF_SYMBOL_UNDEFINED,
1395.  {* Local symbol.  *}
1396.  COFF_SYMBOL_LOCAL,
1397.  {* PE section symbol.  *}
1398.  COFF_SYMBOL_PE_SECTION
1399.};
1400.
1401.typedef asection * (*coff_gc_mark_hook_fn)
1402.  (asection *, struct bfd_link_info *, struct internal_reloc *,
1403.   struct coff_link_hash_entry *, struct internal_syment *);
1404.
1405Special entry points for gdb to swap in coff symbol table parts:
1406.typedef struct
1407.{
1408.  void (*_bfd_coff_swap_aux_in)
1409.    (bfd *, void *, int, int, int, int, void *);
1410.
1411.  void (*_bfd_coff_swap_sym_in)
1412.    (bfd *, void *, void *);
1413.
1414.  void (*_bfd_coff_swap_lineno_in)
1415.    (bfd *, void *, void *);
1416.
1417.  unsigned int (*_bfd_coff_swap_aux_out)
1418.    (bfd *, void *, int, int, int, int, void *);
1419.
1420.  unsigned int (*_bfd_coff_swap_sym_out)
1421.    (bfd *, void *, void *);
1422.
1423.  unsigned int (*_bfd_coff_swap_lineno_out)
1424.    (bfd *, void *, void *);
1425.
1426.  unsigned int (*_bfd_coff_swap_reloc_out)
1427.    (bfd *, void *, void *);
1428.
1429.  unsigned int (*_bfd_coff_swap_filehdr_out)
1430.    (bfd *, void *, void *);
1431.
1432.  unsigned int (*_bfd_coff_swap_aouthdr_out)
1433.    (bfd *, void *, void *);
1434.
1435.  unsigned int (*_bfd_coff_swap_scnhdr_out)
1436.    (bfd *, void *, void *);
1437.
1438.  unsigned int _bfd_filhsz;
1439.  unsigned int _bfd_aoutsz;
1440.  unsigned int _bfd_scnhsz;
1441.  unsigned int _bfd_symesz;
1442.  unsigned int _bfd_auxesz;
1443.  unsigned int _bfd_relsz;
1444.  unsigned int _bfd_linesz;
1445.  unsigned int _bfd_filnmlen;
1446.  bool _bfd_coff_long_filenames;
1447.
1448.  bool _bfd_coff_long_section_names;
1449.  bool (*_bfd_coff_set_long_section_names)
1450.    (bfd *, int);
1451.
1452.  unsigned int _bfd_coff_default_section_alignment_power;
1453.  bool _bfd_coff_force_symnames_in_strings;
1454.  unsigned int _bfd_coff_debug_string_prefix_length;
1455.  unsigned int _bfd_coff_max_nscns;
1456.
1457.  void (*_bfd_coff_swap_filehdr_in)
1458.    (bfd *, void *, void *);
1459.
1460.  void (*_bfd_coff_swap_aouthdr_in)
1461.    (bfd *, void *, void *);
1462.
1463.  void (*_bfd_coff_swap_scnhdr_in)
1464.    (bfd *, void *, void *);
1465.
1466.  void (*_bfd_coff_swap_reloc_in)
1467.    (bfd *abfd, void *, void *);
1468.
1469.  bool (*_bfd_coff_bad_format_hook)
1470.    (bfd *, void *);
1471.
1472.  bool (*_bfd_coff_set_arch_mach_hook)
1473.    (bfd *, void *);
1474.
1475.  void * (*_bfd_coff_mkobject_hook)
1476.    (bfd *, void *, void *);
1477.
1478.  bool (*_bfd_styp_to_sec_flags_hook)
1479.    (bfd *, void *, const char *, asection *, flagword *);
1480.
1481.  void (*_bfd_set_alignment_hook)
1482.    (bfd *, asection *, void *);
1483.
1484.  bool (*_bfd_coff_slurp_symbol_table)
1485.    (bfd *);
1486.
1487.  bool (*_bfd_coff_symname_in_debug)
1488.    (bfd *, struct internal_syment *);
1489.
1490.  bool (*_bfd_coff_pointerize_aux_hook)
1491.    (bfd *, combined_entry_type *, combined_entry_type *,
1492.     unsigned int, combined_entry_type *);
1493.
1494.  bool (*_bfd_coff_print_aux)
1495.    (bfd *, FILE *, combined_entry_type *, combined_entry_type *,
1496.     combined_entry_type *, unsigned int);
1497.
1498.  void (*_bfd_coff_reloc16_extra_cases)
1499.    (bfd *, struct bfd_link_info *, struct bfd_link_order *, arelent *,
1500.     bfd_byte *, unsigned int *, unsigned int *);
1501.
1502.  int (*_bfd_coff_reloc16_estimate)
1503.    (bfd *, asection *, arelent *, unsigned int,
1504.     struct bfd_link_info *);
1505.
1506.  enum coff_symbol_classification (*_bfd_coff_classify_symbol)
1507.    (bfd *, struct internal_syment *);
1508.
1509.  bool (*_bfd_coff_compute_section_file_positions)
1510.    (bfd *);
1511.
1512.  bool (*_bfd_coff_start_final_link)
1513.    (bfd *, struct bfd_link_info *);
1514.
1515.  bool (*_bfd_coff_relocate_section)
1516.    (bfd *, struct bfd_link_info *, bfd *, asection *, bfd_byte *,
1517.     struct internal_reloc *, struct internal_syment *, asection **);
1518.
1519.  reloc_howto_type *(*_bfd_coff_rtype_to_howto)
1520.    (bfd *, asection *, struct internal_reloc *,
1521.     struct coff_link_hash_entry *, struct internal_syment *, bfd_vma *);
1522.
1523.  bool (*_bfd_coff_adjust_symndx)
1524.    (bfd *, struct bfd_link_info *, bfd *, asection *,
1525.     struct internal_reloc *, bool *);
1526.
1527.  bool (*_bfd_coff_link_add_one_symbol)
1528.    (struct bfd_link_info *, bfd *, const char *, flagword,
1529.     asection *, bfd_vma, const char *, bool, bool,
1530.     struct bfd_link_hash_entry **);
1531.
1532.  bool (*_bfd_coff_link_output_has_begun)
1533.    (bfd *, struct coff_final_link_info *);
1534.
1535.  bool (*_bfd_coff_final_link_postscript)
1536.    (bfd *, struct coff_final_link_info *);
1537.
1538.  bool (*_bfd_coff_print_pdata)
1539.    (bfd *, void *);
1540.
1541.} bfd_coff_backend_data;
1542.
1543.#define coff_backend_info(abfd) \
1544.  ((bfd_coff_backend_data *) (abfd)->xvec->backend_data)
1545.
1546.#define bfd_coff_swap_aux_in(a,e,t,c,ind,num,i) \
1547.  ((coff_backend_info (a)->_bfd_coff_swap_aux_in) (a,e,t,c,ind,num,i))
1548.
1549.#define bfd_coff_swap_sym_in(a,e,i) \
1550.  ((coff_backend_info (a)->_bfd_coff_swap_sym_in) (a,e,i))
1551.
1552.#define bfd_coff_swap_lineno_in(a,e,i) \
1553.  ((coff_backend_info ( a)->_bfd_coff_swap_lineno_in) (a,e,i))
1554.
1555.#define bfd_coff_swap_reloc_out(abfd, i, o) \
1556.  ((coff_backend_info (abfd)->_bfd_coff_swap_reloc_out) (abfd, i, o))
1557.
1558.#define bfd_coff_swap_lineno_out(abfd, i, o) \
1559.  ((coff_backend_info (abfd)->_bfd_coff_swap_lineno_out) (abfd, i, o))
1560.
1561.#define bfd_coff_swap_aux_out(a,i,t,c,ind,num,o) \
1562.  ((coff_backend_info (a)->_bfd_coff_swap_aux_out) (a,i,t,c,ind,num,o))
1563.
1564.#define bfd_coff_swap_sym_out(abfd, i,o) \
1565.  ((coff_backend_info (abfd)->_bfd_coff_swap_sym_out) (abfd, i, o))
1566.
1567.#define bfd_coff_swap_scnhdr_out(abfd, i,o) \
1568.  ((coff_backend_info (abfd)->_bfd_coff_swap_scnhdr_out) (abfd, i, o))
1569.
1570.#define bfd_coff_swap_filehdr_out(abfd, i,o) \
1571.  ((coff_backend_info (abfd)->_bfd_coff_swap_filehdr_out) (abfd, i, o))
1572.
1573.#define bfd_coff_swap_aouthdr_out(abfd, i,o) \
1574.  ((coff_backend_info (abfd)->_bfd_coff_swap_aouthdr_out) (abfd, i, o))
1575.
1576.#define bfd_coff_filhsz(abfd) (coff_backend_info (abfd)->_bfd_filhsz)
1577.#define bfd_coff_aoutsz(abfd) (coff_backend_info (abfd)->_bfd_aoutsz)
1578.#define bfd_coff_scnhsz(abfd) (coff_backend_info (abfd)->_bfd_scnhsz)
1579.#define bfd_coff_symesz(abfd) (coff_backend_info (abfd)->_bfd_symesz)
1580.#define bfd_coff_auxesz(abfd) (coff_backend_info (abfd)->_bfd_auxesz)
1581.#define bfd_coff_relsz(abfd)  (coff_backend_info (abfd)->_bfd_relsz)
1582.#define bfd_coff_linesz(abfd) (coff_backend_info (abfd)->_bfd_linesz)
1583.#define bfd_coff_filnmlen(abfd) (coff_backend_info (abfd)->_bfd_filnmlen)
1584.#define bfd_coff_long_filenames(abfd) \
1585.  (coff_backend_info (abfd)->_bfd_coff_long_filenames)
1586.#define bfd_coff_long_section_names(abfd) \
1587.  (coff_backend_info (abfd)->_bfd_coff_long_section_names)
1588.#define bfd_coff_set_long_section_names(abfd, enable) \
1589.  ((coff_backend_info (abfd)->_bfd_coff_set_long_section_names) (abfd, enable))
1590.#define bfd_coff_default_section_alignment_power(abfd) \
1591.  (coff_backend_info (abfd)->_bfd_coff_default_section_alignment_power)
1592.#define bfd_coff_max_nscns(abfd) \
1593.  (coff_backend_info (abfd)->_bfd_coff_max_nscns)
1594.
1595.#define bfd_coff_swap_filehdr_in(abfd, i,o) \
1596.  ((coff_backend_info (abfd)->_bfd_coff_swap_filehdr_in) (abfd, i, o))
1597.
1598.#define bfd_coff_swap_aouthdr_in(abfd, i,o) \
1599.  ((coff_backend_info (abfd)->_bfd_coff_swap_aouthdr_in) (abfd, i, o))
1600.
1601.#define bfd_coff_swap_scnhdr_in(abfd, i,o) \
1602.  ((coff_backend_info (abfd)->_bfd_coff_swap_scnhdr_in) (abfd, i, o))
1603.
1604.#define bfd_coff_swap_reloc_in(abfd, i, o) \
1605.  ((coff_backend_info (abfd)->_bfd_coff_swap_reloc_in) (abfd, i, o))
1606.
1607.#define bfd_coff_bad_format_hook(abfd, filehdr) \
1608.  ((coff_backend_info (abfd)->_bfd_coff_bad_format_hook) (abfd, filehdr))
1609.
1610.#define bfd_coff_set_arch_mach_hook(abfd, filehdr)\
1611.  ((coff_backend_info (abfd)->_bfd_coff_set_arch_mach_hook) (abfd, filehdr))
1612.#define bfd_coff_mkobject_hook(abfd, filehdr, aouthdr)\
1613.  ((coff_backend_info (abfd)->_bfd_coff_mkobject_hook)\
1614.   (abfd, filehdr, aouthdr))
1615.
1616.#define bfd_coff_styp_to_sec_flags_hook(abfd, scnhdr, name, section, flags_ptr)\
1617.  ((coff_backend_info (abfd)->_bfd_styp_to_sec_flags_hook)\
1618.   (abfd, scnhdr, name, section, flags_ptr))
1619.
1620.#define bfd_coff_set_alignment_hook(abfd, sec, scnhdr)\
1621.  ((coff_backend_info (abfd)->_bfd_set_alignment_hook) (abfd, sec, scnhdr))
1622.
1623.#define bfd_coff_slurp_symbol_table(abfd)\
1624.  ((coff_backend_info (abfd)->_bfd_coff_slurp_symbol_table) (abfd))
1625.
1626.#define bfd_coff_symname_in_debug(abfd, sym)\
1627.  ((coff_backend_info (abfd)->_bfd_coff_symname_in_debug) (abfd, sym))
1628.
1629.#define bfd_coff_force_symnames_in_strings(abfd)\
1630.  (coff_backend_info (abfd)->_bfd_coff_force_symnames_in_strings)
1631.
1632.#define bfd_coff_debug_string_prefix_length(abfd)\
1633.  (coff_backend_info (abfd)->_bfd_coff_debug_string_prefix_length)
1634.
1635.#define bfd_coff_print_aux(abfd, file, base, symbol, aux, indaux)\
1636.  ((coff_backend_info (abfd)->_bfd_coff_print_aux)\
1637.   (abfd, file, base, symbol, aux, indaux))
1638.
1639.#define bfd_coff_reloc16_extra_cases(abfd, link_info, link_order,\
1640.				      reloc, data, src_ptr, dst_ptr)\
1641.  ((coff_backend_info (abfd)->_bfd_coff_reloc16_extra_cases)\
1642.   (abfd, link_info, link_order, reloc, data, src_ptr, dst_ptr))
1643.
1644.#define bfd_coff_reloc16_estimate(abfd, section, reloc, shrink, link_info)\
1645.  ((coff_backend_info (abfd)->_bfd_coff_reloc16_estimate)\
1646.   (abfd, section, reloc, shrink, link_info))
1647.
1648.#define bfd_coff_classify_symbol(abfd, sym)\
1649.  ((coff_backend_info (abfd)->_bfd_coff_classify_symbol)\
1650.   (abfd, sym))
1651.
1652.#define bfd_coff_compute_section_file_positions(abfd)\
1653.  ((coff_backend_info (abfd)->_bfd_coff_compute_section_file_positions)\
1654.   (abfd))
1655.
1656.#define bfd_coff_start_final_link(obfd, info)\
1657.  ((coff_backend_info (obfd)->_bfd_coff_start_final_link)\
1658.   (obfd, info))
1659.#define bfd_coff_relocate_section(obfd,info,ibfd,o,con,rel,isyms,secs)\
1660.  ((coff_backend_info (ibfd)->_bfd_coff_relocate_section)\
1661.   (obfd, info, ibfd, o, con, rel, isyms, secs))
1662.#define bfd_coff_rtype_to_howto(abfd, sec, rel, h, sym, addendp)\
1663.  ((coff_backend_info (abfd)->_bfd_coff_rtype_to_howto)\
1664.   (abfd, sec, rel, h, sym, addendp))
1665.#define bfd_coff_adjust_symndx(obfd, info, ibfd, sec, rel, adjustedp)\
1666.  ((coff_backend_info (abfd)->_bfd_coff_adjust_symndx)\
1667.   (obfd, info, ibfd, sec, rel, adjustedp))
1668.#define bfd_coff_link_add_one_symbol(info, abfd, name, flags, section,\
1669.				      value, string, cp, coll, hashp)\
1670.  ((coff_backend_info (abfd)->_bfd_coff_link_add_one_symbol)\
1671.   (info, abfd, name, flags, section, value, string, cp, coll, hashp))
1672.
1673.#define bfd_coff_link_output_has_begun(a,p) \
1674.  ((coff_backend_info (a)->_bfd_coff_link_output_has_begun) (a, p))
1675.#define bfd_coff_final_link_postscript(a,p) \
1676.  ((coff_backend_info (a)->_bfd_coff_final_link_postscript) (a, p))
1677.
1678.#define bfd_coff_have_print_pdata(a) \
1679.  (coff_backend_info (a)->_bfd_coff_print_pdata)
1680.#define bfd_coff_print_pdata(a,p) \
1681.  ((coff_backend_info (a)->_bfd_coff_print_pdata) (a, p))
1682.
1683.{* Macro: Returns true if the bfd is a PE executable as opposed to a
1684.   PE object file.  *}
1685.#define bfd_pei_p(abfd) \
1686.  (startswith ((abfd)->xvec->name, "pei-"))
1687*/
1688
1689/* See whether the magic number matches.  */
1690
1691static bool
1692coff_bad_format_hook (bfd * abfd ATTRIBUTE_UNUSED, void * filehdr)
1693{
1694  struct internal_filehdr *internal_f = (struct internal_filehdr *) filehdr;
1695
1696  if (BADMAG (*internal_f))
1697    return false;
1698
1699  return true;
1700}
1701
1702#ifdef TICOFF
1703static bool
1704ticoff0_bad_format_hook (bfd *abfd ATTRIBUTE_UNUSED, void * filehdr)
1705{
1706  struct internal_filehdr *internal_f = (struct internal_filehdr *) filehdr;
1707
1708  if (COFF0_BADMAG (*internal_f))
1709    return false;
1710
1711  return true;
1712}
1713#endif
1714
1715#ifdef TICOFF
1716static bool
1717ticoff1_bad_format_hook (bfd *abfd ATTRIBUTE_UNUSED, void * filehdr)
1718{
1719  struct internal_filehdr *internal_f = (struct internal_filehdr *) filehdr;
1720
1721  if (COFF1_BADMAG (*internal_f))
1722    return false;
1723
1724  return true;
1725}
1726#endif
1727
1728/* Check whether this section uses an alignment other than the
1729   default.  */
1730
1731static void
1732coff_set_custom_section_alignment (bfd *abfd ATTRIBUTE_UNUSED,
1733				   asection *section,
1734				   const struct coff_section_alignment_entry *alignment_table,
1735				   const unsigned int table_size)
1736{
1737  const unsigned int default_alignment = COFF_DEFAULT_SECTION_ALIGNMENT_POWER;
1738  unsigned int i;
1739
1740  for (i = 0; i < table_size; ++i)
1741    {
1742      const char *secname = bfd_section_name (section);
1743
1744      if (alignment_table[i].comparison_length == (unsigned int) -1
1745	  ? strcmp (alignment_table[i].name, secname) == 0
1746	  : strncmp (alignment_table[i].name, secname,
1747		     alignment_table[i].comparison_length) == 0)
1748	break;
1749    }
1750  if (i >= table_size)
1751    return;
1752
1753  if (alignment_table[i].default_alignment_min != COFF_ALIGNMENT_FIELD_EMPTY
1754      && default_alignment < alignment_table[i].default_alignment_min)
1755    return;
1756
1757  if (alignment_table[i].default_alignment_max != COFF_ALIGNMENT_FIELD_EMPTY
1758#if COFF_DEFAULT_SECTION_ALIGNMENT_POWER != 0
1759      && default_alignment > alignment_table[i].default_alignment_max
1760#endif
1761      )
1762    return;
1763
1764  section->alignment_power = alignment_table[i].alignment_power;
1765}
1766
1767/* Custom section alignment records.  */
1768
1769static const struct coff_section_alignment_entry
1770coff_section_alignment_table[] =
1771{
1772#ifdef COFF_SECTION_ALIGNMENT_ENTRIES
1773  COFF_SECTION_ALIGNMENT_ENTRIES,
1774#endif
1775  /* There must not be any gaps between .stabstr sections.  */
1776  { COFF_SECTION_NAME_PARTIAL_MATCH (".stabstr"),
1777    1, COFF_ALIGNMENT_FIELD_EMPTY, 0 },
1778  /* The .stab section must be aligned to 2**2 at most, to avoid gaps.  */
1779  { COFF_SECTION_NAME_PARTIAL_MATCH (".stab"),
1780    3, COFF_ALIGNMENT_FIELD_EMPTY, 2 },
1781  /* Similarly for the .ctors and .dtors sections.  */
1782  { COFF_SECTION_NAME_EXACT_MATCH (".ctors"),
1783    3, COFF_ALIGNMENT_FIELD_EMPTY, 2 },
1784  { COFF_SECTION_NAME_EXACT_MATCH (".dtors"),
1785    3, COFF_ALIGNMENT_FIELD_EMPTY, 2 }
1786};
1787
1788static const unsigned int coff_section_alignment_table_size =
1789  sizeof coff_section_alignment_table / sizeof coff_section_alignment_table[0];
1790
1791/* Initialize a section structure with information peculiar to this
1792   particular implementation of COFF.  */
1793
1794static bool
1795coff_new_section_hook (bfd * abfd, asection * section)
1796{
1797  combined_entry_type *native;
1798  size_t amt;
1799  unsigned char sclass = C_STAT;
1800
1801  section->alignment_power = COFF_DEFAULT_SECTION_ALIGNMENT_POWER;
1802
1803#ifdef RS6000COFF_C
1804  if (bfd_xcoff_text_align_power (abfd) != 0
1805      && strcmp (bfd_section_name (section), ".text") == 0)
1806    section->alignment_power = bfd_xcoff_text_align_power (abfd);
1807  else if (bfd_xcoff_data_align_power (abfd) != 0
1808      && strcmp (bfd_section_name (section), ".data") == 0)
1809    section->alignment_power = bfd_xcoff_data_align_power (abfd);
1810  else
1811    {
1812      int i;
1813
1814      for (i = 0; i < XCOFF_DWSECT_NBR_NAMES; i++)
1815	if (strcmp (bfd_section_name (section),
1816		    xcoff_dwsect_names[i].xcoff_name) == 0)
1817	  {
1818	    section->alignment_power = 0;
1819	    sclass = C_DWARF;
1820	    break;
1821	  }
1822    }
1823#endif
1824
1825  /* Set up the section symbol.  */
1826  if (!_bfd_generic_new_section_hook (abfd, section))
1827    return false;
1828
1829  /* Allocate aux records for section symbols, to store size and
1830     related info.
1831
1832     @@ The 10 is a guess at a plausible maximum number of aux entries
1833     (but shouldn't be a constant).  */
1834  amt = sizeof (combined_entry_type) * 10;
1835  native = (combined_entry_type *) bfd_zalloc (abfd, amt);
1836  if (native == NULL)
1837    return false;
1838
1839  /* We don't need to set up n_name, n_value, or n_scnum in the native
1840     symbol information, since they'll be overridden by the BFD symbol
1841     anyhow.  However, we do need to set the type and storage class,
1842     in case this symbol winds up getting written out.  The value 0
1843     for n_numaux is already correct.  */
1844
1845  native->is_sym = true;
1846  native->u.syment.n_type = T_NULL;
1847  native->u.syment.n_sclass = sclass;
1848
1849  coffsymbol (section->symbol)->native = native;
1850
1851  coff_set_custom_section_alignment (abfd, section,
1852				     coff_section_alignment_table,
1853				     coff_section_alignment_table_size);
1854
1855  return true;
1856}
1857
1858#ifdef COFF_ALIGN_IN_SECTION_HEADER
1859
1860/* Set the alignment of a BFD section.  */
1861
1862static void
1863coff_set_alignment_hook (bfd * abfd ATTRIBUTE_UNUSED,
1864			 asection * section,
1865			 void * scnhdr)
1866{
1867  struct internal_scnhdr *hdr = (struct internal_scnhdr *) scnhdr;
1868  unsigned int i;
1869
1870#ifdef COFF_DECODE_ALIGNMENT
1871  i = COFF_DECODE_ALIGNMENT(hdr->s_flags);
1872#endif
1873  section->alignment_power = i;
1874
1875#ifdef coff_set_section_load_page
1876  coff_set_section_load_page (section, hdr->s_page);
1877#endif
1878}
1879
1880#else /* ! COFF_ALIGN_IN_SECTION_HEADER */
1881#ifdef COFF_WITH_PE
1882
1883static void
1884coff_set_alignment_hook (bfd * abfd ATTRIBUTE_UNUSED,
1885			 asection * section,
1886			 void * scnhdr)
1887{
1888  struct internal_scnhdr *hdr = (struct internal_scnhdr *) scnhdr;
1889  size_t amt;
1890  unsigned int alignment_power_const
1891    = hdr->s_flags & IMAGE_SCN_ALIGN_POWER_BIT_MASK;
1892
1893  switch (alignment_power_const)
1894    {
1895    case IMAGE_SCN_ALIGN_8192BYTES:
1896    case IMAGE_SCN_ALIGN_4096BYTES:
1897    case IMAGE_SCN_ALIGN_2048BYTES:
1898    case IMAGE_SCN_ALIGN_1024BYTES:
1899    case IMAGE_SCN_ALIGN_512BYTES:
1900    case IMAGE_SCN_ALIGN_256BYTES:
1901    case IMAGE_SCN_ALIGN_128BYTES:
1902    case IMAGE_SCN_ALIGN_64BYTES:
1903    case IMAGE_SCN_ALIGN_32BYTES:
1904    case IMAGE_SCN_ALIGN_16BYTES:
1905    case IMAGE_SCN_ALIGN_8BYTES:
1906    case IMAGE_SCN_ALIGN_4BYTES:
1907    case IMAGE_SCN_ALIGN_2BYTES:
1908    case IMAGE_SCN_ALIGN_1BYTES:
1909      section->alignment_power
1910	= IMAGE_SCN_ALIGN_POWER_NUM (alignment_power_const);
1911      break;
1912    default:
1913      break;
1914    }
1915
1916  /* In a PE image file, the s_paddr field holds the virtual size of a
1917     section, while the s_size field holds the raw size.  We also keep
1918     the original section flag value, since not every bit can be
1919     mapped onto a generic BFD section bit.  */
1920  if (coff_section_data (abfd, section) == NULL)
1921    {
1922      amt = sizeof (struct coff_section_tdata);
1923      section->used_by_bfd = bfd_zalloc (abfd, amt);
1924      if (section->used_by_bfd == NULL)
1925	/* FIXME: Return error.  */
1926	abort ();
1927    }
1928
1929  if (pei_section_data (abfd, section) == NULL)
1930    {
1931      amt = sizeof (struct pei_section_tdata);
1932      coff_section_data (abfd, section)->tdata = bfd_zalloc (abfd, amt);
1933      if (coff_section_data (abfd, section)->tdata == NULL)
1934	/* FIXME: Return error.  */
1935	abort ();
1936    }
1937  pei_section_data (abfd, section)->virt_size = hdr->s_paddr;
1938  pei_section_data (abfd, section)->pe_flags = hdr->s_flags;
1939
1940  section->lma = hdr->s_vaddr;
1941
1942  /* Check for extended relocs.  */
1943  if (hdr->s_flags & IMAGE_SCN_LNK_NRELOC_OVFL)
1944    {
1945      struct external_reloc dst;
1946      struct internal_reloc n;
1947      file_ptr oldpos = bfd_tell (abfd);
1948      bfd_size_type relsz = bfd_coff_relsz (abfd);
1949
1950      if (bfd_seek (abfd, (file_ptr) hdr->s_relptr, 0) != 0)
1951	return;
1952      if (bfd_bread (& dst, relsz, abfd) != relsz)
1953	return;
1954
1955      bfd_coff_swap_reloc_in (abfd, &dst, &n);
1956      if (bfd_seek (abfd, oldpos, 0) != 0)
1957	return;
1958      if (n.r_vaddr < 0x10000)
1959	{
1960	  _bfd_error_handler (_("%pB: overflow reloc count too small"), abfd);
1961	  bfd_set_error (bfd_error_bad_value);
1962	  return;
1963	}
1964      section->reloc_count = hdr->s_nreloc = n.r_vaddr - 1;
1965      section->rel_filepos += relsz;
1966    }
1967  else if (hdr->s_nreloc == 0xffff)
1968    _bfd_error_handler
1969      (_("%pB: warning: claims to have 0xffff relocs, without overflow"),
1970       abfd);
1971}
1972#undef ALIGN_SET
1973#undef ELIFALIGN_SET
1974
1975#else /* ! COFF_WITH_PE */
1976#ifdef RS6000COFF_C
1977
1978/* We grossly abuse this function to handle XCOFF overflow headers.
1979   When we see one, we correct the reloc and line number counts in the
1980   real header, and remove the section we just created.  */
1981
1982static void
1983coff_set_alignment_hook (bfd *abfd, asection *section, void * scnhdr)
1984{
1985  struct internal_scnhdr *hdr = (struct internal_scnhdr *) scnhdr;
1986  asection *real_sec;
1987
1988  if ((hdr->s_flags & STYP_OVRFLO) == 0)
1989    return;
1990
1991  real_sec = coff_section_from_bfd_index (abfd, (int) hdr->s_nreloc);
1992  if (real_sec == NULL)
1993    return;
1994
1995  real_sec->reloc_count = hdr->s_paddr;
1996  real_sec->lineno_count = hdr->s_vaddr;
1997
1998  if (!bfd_section_removed_from_list (abfd, section))
1999    {
2000      bfd_section_list_remove (abfd, section);
2001      --abfd->section_count;
2002    }
2003}
2004
2005#else /* ! RS6000COFF_C */
2006#if defined (COFF_GO32_EXE) || defined (COFF_GO32)
2007
2008static void
2009coff_set_alignment_hook (bfd * abfd, asection * section, void * scnhdr)
2010{
2011  struct internal_scnhdr *hdr = (struct internal_scnhdr *) scnhdr;
2012
2013  /* Check for extended relocs.  */
2014  if (hdr->s_flags & IMAGE_SCN_LNK_NRELOC_OVFL)
2015    {
2016      struct external_reloc dst;
2017      struct internal_reloc n;
2018      const file_ptr oldpos = bfd_tell (abfd);
2019      const bfd_size_type relsz = bfd_coff_relsz (abfd);
2020
2021      if (bfd_seek (abfd, (file_ptr) hdr->s_relptr, 0) != 0)
2022	return;
2023      if (bfd_bread (& dst, relsz, abfd) != relsz)
2024	return;
2025
2026      bfd_coff_swap_reloc_in (abfd, &dst, &n);
2027      if (bfd_seek (abfd, oldpos, 0) != 0)
2028	return;
2029      section->reloc_count = hdr->s_nreloc = n.r_vaddr - 1;
2030      section->rel_filepos += relsz;
2031    }
2032  else if (hdr->s_nreloc == 0xffff)
2033    _bfd_error_handler
2034      (_("%pB: warning: claims to have 0xffff relocs, without overflow"),
2035       abfd);
2036}
2037
2038#else /* ! COFF_GO32_EXE && ! COFF_GO32 */
2039
2040static void
2041coff_set_alignment_hook (bfd *abfd ATTRIBUTE_UNUSED,
2042			 asection *section ATTRIBUTE_UNUSED,
2043			 void *scnhdr ATTRIBUTE_UNUSED)
2044{
2045}
2046
2047#endif /* ! COFF_GO32_EXE && ! COFF_GO32 */
2048#endif /* ! RS6000COFF_C */
2049#endif /* ! COFF_WITH_PE */
2050#endif /* ! COFF_ALIGN_IN_SECTION_HEADER */
2051
2052#ifndef coff_mkobject
2053
2054static bool
2055coff_mkobject (bfd * abfd)
2056{
2057  coff_data_type *coff;
2058  size_t amt = sizeof (coff_data_type);
2059
2060  abfd->tdata.coff_obj_data = bfd_zalloc (abfd, amt);
2061  if (abfd->tdata.coff_obj_data == NULL)
2062    return false;
2063  coff = coff_data (abfd);
2064  coff->symbols = NULL;
2065  coff->conversion_table = NULL;
2066  coff->raw_syments = NULL;
2067  coff->relocbase = 0;
2068  coff->local_toc_sym_map = 0;
2069
2070/*  make_abs_section(abfd);*/
2071
2072  return true;
2073}
2074#endif
2075
2076/* Create the COFF backend specific information.  */
2077
2078#ifndef coff_mkobject_hook
2079static void *
2080coff_mkobject_hook (bfd * abfd,
2081		    void * filehdr,
2082		    void * aouthdr ATTRIBUTE_UNUSED)
2083{
2084  struct internal_filehdr *internal_f = (struct internal_filehdr *) filehdr;
2085  coff_data_type *coff;
2086
2087  if (! coff_mkobject (abfd))
2088    return NULL;
2089
2090  coff = coff_data (abfd);
2091
2092  coff->sym_filepos = internal_f->f_symptr;
2093
2094  /* These members communicate important constants about the symbol
2095     table to GDB's symbol-reading code.  These `constants'
2096     unfortunately vary among coff implementations...  */
2097  coff->local_n_btmask = N_BTMASK;
2098  coff->local_n_btshft = N_BTSHFT;
2099  coff->local_n_tmask = N_TMASK;
2100  coff->local_n_tshift = N_TSHIFT;
2101  coff->local_symesz = bfd_coff_symesz (abfd);
2102  coff->local_auxesz = bfd_coff_auxesz (abfd);
2103  coff->local_linesz = bfd_coff_linesz (abfd);
2104
2105  coff->timestamp = internal_f->f_timdat;
2106
2107  obj_raw_syment_count (abfd) =
2108    obj_conv_table_size (abfd) =
2109      internal_f->f_nsyms;
2110
2111#ifdef RS6000COFF_C
2112  if ((internal_f->f_flags & F_SHROBJ) != 0)
2113    abfd->flags |= DYNAMIC;
2114  if (aouthdr != NULL && internal_f->f_opthdr >= bfd_coff_aoutsz (abfd))
2115    {
2116      struct internal_aouthdr *internal_a =
2117	(struct internal_aouthdr *) aouthdr;
2118      struct xcoff_tdata *xcoff;
2119
2120      xcoff = xcoff_data (abfd);
2121# ifdef U803XTOCMAGIC
2122      xcoff->xcoff64 = internal_f->f_magic == U803XTOCMAGIC;
2123# else
2124      xcoff->xcoff64 = 0;
2125# endif
2126      xcoff->full_aouthdr = true;
2127      xcoff->toc = internal_a->o_toc;
2128      xcoff->sntoc = internal_a->o_sntoc;
2129      xcoff->snentry = internal_a->o_snentry;
2130      bfd_xcoff_text_align_power (abfd) = internal_a->o_algntext;
2131      bfd_xcoff_data_align_power (abfd) = internal_a->o_algndata;
2132      xcoff->modtype = internal_a->o_modtype;
2133      xcoff->cputype = internal_a->o_cputype;
2134      xcoff->maxdata = internal_a->o_maxdata;
2135      xcoff->maxstack = internal_a->o_maxstack;
2136    }
2137#endif
2138
2139#ifdef ARM
2140  /* Set the flags field from the COFF header read in.  */
2141  if (! _bfd_coff_arm_set_private_flags (abfd, internal_f->f_flags))
2142    coff->flags = 0;
2143#endif
2144
2145#ifdef COFF_WITH_PE
2146  /* FIXME: I'm not sure this is ever executed, since peicode.h
2147     defines coff_mkobject_hook.  */
2148  if ((internal_f->f_flags & IMAGE_FILE_DEBUG_STRIPPED) == 0)
2149    abfd->flags |= HAS_DEBUG;
2150#endif
2151
2152  return coff;
2153}
2154#endif
2155
2156/* Determine the machine architecture and type.  FIXME: This is target
2157   dependent because the magic numbers are defined in the target
2158   dependent header files.  But there is no particular need for this.
2159   If the magic numbers were moved to a separate file, this function
2160   would be target independent and would also be much more successful
2161   at linking together COFF files for different architectures.  */
2162
2163static bool
2164coff_set_arch_mach_hook (bfd *abfd, void * filehdr)
2165{
2166  unsigned long machine;
2167  enum bfd_architecture arch;
2168  struct internal_filehdr *internal_f = (struct internal_filehdr *) filehdr;
2169
2170  /* Zero selects the default machine for an arch.  */
2171  machine = 0;
2172  switch (internal_f->f_magic)
2173    {
2174#ifdef I386MAGIC
2175    case I386MAGIC:
2176    case I386PTXMAGIC:
2177    case I386AIXMAGIC:		/* Danbury PS/2 AIX C Compiler.  */
2178    case LYNXCOFFMAGIC:
2179    case I386_APPLE_MAGIC:
2180    case I386_FREEBSD_MAGIC:
2181    case I386_LINUX_MAGIC:
2182    case I386_NETBSD_MAGIC:
2183      arch = bfd_arch_i386;
2184      break;
2185#endif
2186#ifdef AMD64MAGIC
2187    case AMD64MAGIC:
2188    case AMD64_APPLE_MAGIC:
2189    case AMD64_FREEBSD_MAGIC:
2190    case AMD64_LINUX_MAGIC:
2191    case AMD64_NETBSD_MAGIC:
2192      arch = bfd_arch_i386;
2193      machine = bfd_mach_x86_64;
2194      break;
2195#endif
2196#ifdef IA64MAGIC
2197    case IA64MAGIC:
2198      arch = bfd_arch_ia64;
2199      break;
2200#endif
2201#ifdef ARMMAGIC
2202    case ARMMAGIC:
2203    case ARMPEMAGIC:
2204    case THUMBPEMAGIC:
2205      arch = bfd_arch_arm;
2206      machine = bfd_arm_get_mach_from_notes (abfd, ARM_NOTE_SECTION);
2207      if (machine == bfd_mach_arm_unknown)
2208	{
2209	  switch (internal_f->f_flags & F_ARM_ARCHITECTURE_MASK)
2210	    {
2211	    case F_ARM_2:  machine = bfd_mach_arm_2;  break;
2212	    case F_ARM_2a: machine = bfd_mach_arm_2a; break;
2213	    case F_ARM_3:  machine = bfd_mach_arm_3;  break;
2214	    default:
2215	    case F_ARM_3M: machine = bfd_mach_arm_3M; break;
2216	    case F_ARM_4:  machine = bfd_mach_arm_4;  break;
2217	    case F_ARM_4T: machine = bfd_mach_arm_4T; break;
2218	      /* The COFF header does not have enough bits available
2219		 to cover all the different ARM architectures.  So
2220		 we interpret F_ARM_5, the highest flag value to mean
2221		 "the highest ARM architecture known to BFD" which is
2222		 currently the XScale.  */
2223	    case F_ARM_5:  machine = bfd_mach_arm_XScale;  break;
2224	    }
2225	}
2226      break;
2227#endif
2228#ifdef AARCH64MAGIC
2229    case AARCH64MAGIC:
2230      arch = bfd_arch_aarch64;
2231      machine = internal_f->f_flags & F_AARCH64_ARCHITECTURE_MASK;
2232      break;
2233#endif
2234#ifdef LOONGARCH64MAGIC
2235    case LOONGARCH64MAGIC:
2236      arch = bfd_arch_loongarch;
2237      machine = internal_f->f_flags & F_LOONGARCH64_ARCHITECTURE_MASK;
2238      break;
2239#endif
2240#ifdef Z80MAGIC
2241    case Z80MAGIC:
2242      arch = bfd_arch_z80;
2243      switch (internal_f->f_flags & F_MACHMASK)
2244	{
2245	case bfd_mach_z80strict << 12:
2246	case bfd_mach_z80 << 12:
2247	case bfd_mach_z80n << 12:
2248	case bfd_mach_z80full << 12:
2249	case bfd_mach_r800 << 12:
2250	case bfd_mach_gbz80 << 12:
2251	case bfd_mach_z180 << 12:
2252	case bfd_mach_ez80_z80 << 12:
2253	case bfd_mach_ez80_adl << 12:
2254	  machine = ((unsigned)internal_f->f_flags & F_MACHMASK) >> 12;
2255	  break;
2256	default:
2257	  return false;
2258	}
2259      break;
2260#endif
2261#ifdef Z8KMAGIC
2262    case Z8KMAGIC:
2263      arch = bfd_arch_z8k;
2264      switch (internal_f->f_flags & F_MACHMASK)
2265	{
2266	case F_Z8001:
2267	  machine = bfd_mach_z8001;
2268	  break;
2269	case F_Z8002:
2270	  machine = bfd_mach_z8002;
2271	  break;
2272	default:
2273	  return false;
2274	}
2275      break;
2276#endif
2277
2278#ifdef RS6000COFF_C
2279#ifdef XCOFF64
2280    case U64_TOCMAGIC:
2281    case U803XTOCMAGIC:
2282#else
2283    case U802ROMAGIC:
2284    case U802WRMAGIC:
2285    case U802TOCMAGIC:
2286#endif
2287      {
2288	int cputype;
2289
2290	if (xcoff_data (abfd)->cputype != -1)
2291	  cputype = xcoff_data (abfd)->cputype & 0xff;
2292	else
2293	  {
2294	    /* We did not get a value from the a.out header.  If the
2295	       file has not been stripped, we may be able to get the
2296	       architecture information from the first symbol, if it
2297	       is a .file symbol.  */
2298	    if (obj_raw_syment_count (abfd) == 0)
2299	      cputype = 0;
2300	    else
2301	      {
2302		bfd_byte *buf;
2303		struct internal_syment sym;
2304		bfd_size_type amt = bfd_coff_symesz (abfd);
2305
2306		if (bfd_seek (abfd, obj_sym_filepos (abfd), SEEK_SET) != 0)
2307		  return false;
2308		buf = _bfd_malloc_and_read (abfd, amt, amt);
2309		if (buf == NULL)
2310		  return false;
2311		bfd_coff_swap_sym_in (abfd, buf, & sym);
2312		if (sym.n_sclass == C_FILE)
2313		  cputype = sym.n_type & 0xff;
2314		else
2315		  cputype = 0;
2316		free (buf);
2317	      }
2318	  }
2319
2320	/* FIXME: We don't handle all cases here.  */
2321	switch (cputype)
2322	  {
2323	  default:
2324	  case 0:
2325	    arch = bfd_xcoff_architecture (abfd);
2326	    machine = bfd_xcoff_machine (abfd);
2327	    break;
2328
2329	  case 1:
2330	    arch = bfd_arch_powerpc;
2331	    machine = bfd_mach_ppc_601;
2332	    break;
2333	  case 2: /* 64 bit PowerPC */
2334	    arch = bfd_arch_powerpc;
2335	    machine = bfd_mach_ppc_620;
2336	    break;
2337	  case 3:
2338	    arch = bfd_arch_powerpc;
2339	    machine = bfd_mach_ppc;
2340	    break;
2341	  case 4:
2342	    arch = bfd_arch_rs6000;
2343	    machine = bfd_mach_rs6k;
2344	    break;
2345	  }
2346      }
2347      break;
2348#endif
2349
2350#ifdef SH_ARCH_MAGIC_BIG
2351    case SH_ARCH_MAGIC_BIG:
2352    case SH_ARCH_MAGIC_LITTLE:
2353#ifdef COFF_WITH_PE
2354    case SH_ARCH_MAGIC_WINCE:
2355#endif
2356      arch = bfd_arch_sh;
2357      break;
2358#endif
2359
2360#ifdef MIPS_ARCH_MAGIC_WINCE
2361    case MIPS_ARCH_MAGIC_WINCE:
2362      arch = bfd_arch_mips;
2363      break;
2364#endif
2365
2366#ifdef SPARCMAGIC
2367    case SPARCMAGIC:
2368#ifdef LYNXCOFFMAGIC
2369    case LYNXCOFFMAGIC:
2370#endif
2371      arch = bfd_arch_sparc;
2372      break;
2373#endif
2374
2375#ifdef TIC30MAGIC
2376    case TIC30MAGIC:
2377      arch = bfd_arch_tic30;
2378      break;
2379#endif
2380
2381#ifdef TICOFF0MAGIC
2382#ifdef TICOFF_TARGET_ARCH
2383      /* This TI COFF section should be used by all new TI COFF v0 targets.  */
2384    case TICOFF0MAGIC:
2385      arch = TICOFF_TARGET_ARCH;
2386      machine = TICOFF_TARGET_MACHINE_GET (internal_f->f_flags);
2387      break;
2388#endif
2389#endif
2390
2391#ifdef TICOFF1MAGIC
2392      /* This TI COFF section should be used by all new TI COFF v1/2 targets.  */
2393      /* TI COFF1 and COFF2 use the target_id field to specify which arch.  */
2394    case TICOFF1MAGIC:
2395    case TICOFF2MAGIC:
2396      switch (internal_f->f_target_id)
2397	{
2398#ifdef TI_TARGET_ID
2399	case TI_TARGET_ID:
2400	  arch = TICOFF_TARGET_ARCH;
2401	  machine = TICOFF_TARGET_MACHINE_GET (internal_f->f_flags);
2402	  break;
2403#endif
2404	default:
2405	  arch = bfd_arch_obscure;
2406	  _bfd_error_handler
2407	    (_("unrecognized TI COFF target id '0x%x'"),
2408	     internal_f->f_target_id);
2409	  break;
2410	}
2411      break;
2412#endif
2413
2414#ifdef MCOREMAGIC
2415    case MCOREMAGIC:
2416      arch = bfd_arch_mcore;
2417      break;
2418#endif
2419
2420    default:			/* Unreadable input file type.  */
2421      arch = bfd_arch_obscure;
2422      break;
2423    }
2424
2425  bfd_default_set_arch_mach (abfd, arch, machine);
2426  return true;
2427}
2428
2429static bool
2430symname_in_debug_hook (bfd *abfd ATTRIBUTE_UNUSED,
2431		       struct internal_syment *sym ATTRIBUTE_UNUSED)
2432{
2433#ifdef SYMNAME_IN_DEBUG
2434  return SYMNAME_IN_DEBUG (sym) != 0;
2435#else
2436  return false;
2437#endif
2438}
2439
2440#ifdef RS6000COFF_C
2441
2442#ifdef XCOFF64
2443#define FORCE_SYMNAMES_IN_STRINGS
2444#endif
2445
2446/* Handle the csect auxent of a C_EXT, C_AIX_WEAKEXT or C_HIDEXT symbol.  */
2447
2448static bool
2449coff_pointerize_aux_hook (bfd *abfd ATTRIBUTE_UNUSED,
2450			  combined_entry_type *table_base,
2451			  combined_entry_type *symbol,
2452			  unsigned int indaux,
2453			  combined_entry_type *aux)
2454{
2455  BFD_ASSERT (symbol->is_sym);
2456  int n_sclass = symbol->u.syment.n_sclass;
2457
2458  if (CSECT_SYM_P (n_sclass)
2459      && indaux + 1 == symbol->u.syment.n_numaux)
2460    {
2461      BFD_ASSERT (! aux->is_sym);
2462      if (SMTYP_SMTYP (aux->u.auxent.x_csect.x_smtyp) == XTY_LD)
2463	{
2464	  aux->u.auxent.x_csect.x_scnlen.p =
2465	    table_base + aux->u.auxent.x_csect.x_scnlen.l;
2466	  aux->fix_scnlen = 1;
2467	}
2468
2469      /* Return TRUE to indicate that the caller should not do any
2470	 further work on this auxent.  */
2471      return true;
2472    }
2473
2474  /* Return FALSE to indicate that this auxent should be handled by
2475     the caller.  */
2476  return false;
2477}
2478
2479#else
2480#define coff_pointerize_aux_hook 0
2481#endif /* ! RS6000COFF_C */
2482
2483/* Print an aux entry.  This returns TRUE if it has printed it.  */
2484
2485static bool
2486coff_print_aux (bfd *abfd ATTRIBUTE_UNUSED,
2487		FILE *file ATTRIBUTE_UNUSED,
2488		combined_entry_type *table_base ATTRIBUTE_UNUSED,
2489		combined_entry_type *symbol ATTRIBUTE_UNUSED,
2490		combined_entry_type *aux ATTRIBUTE_UNUSED,
2491		unsigned int indaux ATTRIBUTE_UNUSED)
2492{
2493  BFD_ASSERT (symbol->is_sym);
2494  BFD_ASSERT (! aux->is_sym);
2495#ifdef RS6000COFF_C
2496  if (CSECT_SYM_P (symbol->u.syment.n_sclass)
2497      && indaux + 1 == symbol->u.syment.n_numaux)
2498    {
2499      /* This is a csect entry.  */
2500      fprintf (file, "AUX ");
2501      if (SMTYP_SMTYP (aux->u.auxent.x_csect.x_smtyp) != XTY_LD)
2502	{
2503	  BFD_ASSERT (! aux->fix_scnlen);
2504	  fprintf (file, "val %5" PRId64,
2505		   (int64_t) aux->u.auxent.x_csect.x_scnlen.l);
2506	}
2507      else
2508	{
2509	  fprintf (file, "indx ");
2510	  if (! aux->fix_scnlen)
2511	    fprintf (file, "%4" PRId64,
2512		     (int64_t) aux->u.auxent.x_csect.x_scnlen.l);
2513	  else
2514	    fprintf (file, "%4ld",
2515		     (long) (aux->u.auxent.x_csect.x_scnlen.p - table_base));
2516	}
2517      fprintf (file,
2518	       " prmhsh %ld snhsh %u typ %d algn %d clss %u stb %ld snstb %u",
2519	       aux->u.auxent.x_csect.x_parmhash,
2520	       (unsigned int) aux->u.auxent.x_csect.x_snhash,
2521	       SMTYP_SMTYP (aux->u.auxent.x_csect.x_smtyp),
2522	       SMTYP_ALIGN (aux->u.auxent.x_csect.x_smtyp),
2523	       (unsigned int) aux->u.auxent.x_csect.x_smclas,
2524	       aux->u.auxent.x_csect.x_stab,
2525	       (unsigned int) aux->u.auxent.x_csect.x_snstab);
2526      return true;
2527    }
2528#endif
2529
2530  /* Return FALSE to indicate that no special action was taken.  */
2531  return false;
2532}
2533
2534/*
2535SUBSUBSECTION
2536	Writing relocations
2537
2538	To write relocations, the back end steps though the
2539	canonical relocation table and create an
2540	@code{internal_reloc}. The symbol index to use is removed from
2541	the @code{offset} field in the symbol table supplied.  The
2542	address comes directly from the sum of the section base
2543	address and the relocation offset; the type is dug directly
2544	from the howto field.  Then the @code{internal_reloc} is
2545	swapped into the shape of an @code{external_reloc} and written
2546	out to disk.
2547
2548*/
2549
2550#ifdef TARG_AUX
2551
2552
2553/* AUX's ld wants relocations to be sorted.  */
2554static int
2555compare_arelent_ptr (const void * x, const void * y)
2556{
2557  const arelent **a = (const arelent **) x;
2558  const arelent **b = (const arelent **) y;
2559  bfd_size_type aadr = (*a)->address;
2560  bfd_size_type badr = (*b)->address;
2561
2562  return (aadr < badr ? -1 : badr < aadr ? 1 : 0);
2563}
2564
2565#endif /* TARG_AUX */
2566
2567static bool
2568coff_write_relocs (bfd * abfd, int first_undef)
2569{
2570  asection *s;
2571
2572  for (s = abfd->sections; s != NULL; s = s->next)
2573    {
2574      unsigned int i;
2575      struct external_reloc dst;
2576      arelent **p;
2577
2578#ifndef TARG_AUX
2579      p = s->orelocation;
2580#else
2581      {
2582	/* Sort relocations before we write them out.  */
2583	bfd_size_type amt;
2584
2585	amt = s->reloc_count;
2586	amt *= sizeof (arelent *);
2587	p = bfd_malloc (amt);
2588	if (p == NULL)
2589	  {
2590	    if (s->reloc_count > 0)
2591	      return false;
2592	  }
2593	else
2594	  {
2595	    memcpy (p, s->orelocation, (size_t) amt);
2596	    qsort (p, s->reloc_count, sizeof (arelent *), compare_arelent_ptr);
2597	  }
2598      }
2599#endif
2600
2601      if (bfd_seek (abfd, s->rel_filepos, SEEK_SET) != 0)
2602	return false;
2603
2604#ifdef COFF_WITH_EXTENDED_RELOC_COUNTER
2605      if ((obj_pe (abfd) || obj_go32 (abfd)) && s->reloc_count >= 0xffff)
2606	{
2607	  /* Encode real count here as first reloc.  */
2608	  struct internal_reloc n;
2609
2610	  memset (& n, 0, sizeof (n));
2611	  /* Add one to count *this* reloc (grr).  */
2612	  n.r_vaddr = s->reloc_count + 1;
2613	  coff_swap_reloc_out (abfd, &n, &dst);
2614	  if (bfd_bwrite (& dst, (bfd_size_type) bfd_coff_relsz (abfd),
2615			  abfd) != bfd_coff_relsz (abfd))
2616	    return false;
2617	}
2618#endif
2619
2620      for (i = 0; i < s->reloc_count; i++)
2621	{
2622	  struct internal_reloc n;
2623	  arelent *q = p[i];
2624
2625	  memset (& n, 0, sizeof (n));
2626
2627	  /* Now we've renumbered the symbols we know where the
2628	     undefined symbols live in the table.  Check the reloc
2629	     entries for symbols who's output bfd isn't the right one.
2630	     This is because the symbol was undefined (which means
2631	     that all the pointers are never made to point to the same
2632	     place). This is a bad thing,'cause the symbols attached
2633	     to the output bfd are indexed, so that the relocation
2634	     entries know which symbol index they point to.  So we
2635	     have to look up the output symbol here.  */
2636
2637	  if (q->sym_ptr_ptr[0] != NULL && q->sym_ptr_ptr[0]->the_bfd != abfd)
2638	    {
2639	      int j;
2640	      const char *sname = q->sym_ptr_ptr[0]->name;
2641	      asymbol **outsyms = abfd->outsymbols;
2642
2643	      for (j = first_undef; outsyms[j]; j++)
2644		{
2645		  const char *intable = outsyms[j]->name;
2646
2647		  if (strcmp (intable, sname) == 0)
2648		    {
2649		      /* Got a hit, so repoint the reloc.  */
2650		      q->sym_ptr_ptr = outsyms + j;
2651		      break;
2652		    }
2653		}
2654	    }
2655
2656	  n.r_vaddr = q->address + s->vma;
2657
2658#ifdef R_IHCONST
2659	  /* The 29k const/consth reloc pair is a real kludge.  The consth
2660	     part doesn't have a symbol; it has an offset.  So rebuilt
2661	     that here.  */
2662	  if (q->howto->type == R_IHCONST)
2663	    n.r_symndx = q->addend;
2664	  else
2665#endif
2666	    if (q->sym_ptr_ptr && q->sym_ptr_ptr[0] != NULL)
2667	      {
2668#ifdef SECTION_RELATIVE_ABSOLUTE_SYMBOL_P
2669		if (SECTION_RELATIVE_ABSOLUTE_SYMBOL_P (q, s))
2670#else
2671		if ((*q->sym_ptr_ptr)->section == bfd_abs_section_ptr
2672		    && ((*q->sym_ptr_ptr)->flags & BSF_SECTION_SYM) != 0)
2673#endif
2674		  /* This is a relocation relative to the absolute symbol.  */
2675		  n.r_symndx = -1;
2676		else
2677		  {
2678		    n.r_symndx = get_index ((*(q->sym_ptr_ptr)));
2679		    /* Check to see if the symbol reloc points to a symbol
2680		       we don't have in our symbol table.  */
2681		    if (n.r_symndx > obj_conv_table_size (abfd))
2682		      {
2683			bfd_set_error (bfd_error_bad_value);
2684			/* xgettext:c-format */
2685			_bfd_error_handler (_("%pB: reloc against a non-existent"
2686					      " symbol index: %ld"),
2687					    abfd, n.r_symndx);
2688			return false;
2689		      }
2690		  }
2691	      }
2692
2693#ifdef SWAP_OUT_RELOC_OFFSET
2694	  n.r_offset = q->addend;
2695#endif
2696
2697#ifdef SELECT_RELOC
2698	  /* Work out reloc type from what is required.  */
2699	  if (q->howto)
2700	    SELECT_RELOC (n, q->howto);
2701#else
2702	  if (q->howto)
2703	    n.r_type = q->howto->type;
2704#endif
2705	  coff_swap_reloc_out (abfd, &n, &dst);
2706
2707	  if (bfd_bwrite (& dst, (bfd_size_type) bfd_coff_relsz (abfd),
2708			 abfd) != bfd_coff_relsz (abfd))
2709	    return false;
2710	}
2711
2712#ifdef TARG_AUX
2713      free (p);
2714#endif
2715    }
2716
2717  return true;
2718}
2719
2720/* Set flags and magic number of a coff file from architecture and machine
2721   type.  Result is TRUE if we can represent the arch&type, FALSE if not.  */
2722
2723static bool
2724coff_set_flags (bfd * abfd,
2725		unsigned int *magicp ATTRIBUTE_UNUSED,
2726		unsigned short *flagsp ATTRIBUTE_UNUSED)
2727{
2728  switch (bfd_get_arch (abfd))
2729    {
2730#ifdef Z80MAGIC
2731    case bfd_arch_z80:
2732      *magicp = Z80MAGIC;
2733      switch (bfd_get_mach (abfd))
2734	{
2735	case bfd_mach_z80strict:
2736	case bfd_mach_z80:
2737	case bfd_mach_z80n:
2738	case bfd_mach_z80full:
2739	case bfd_mach_r800:
2740	case bfd_mach_gbz80:
2741	case bfd_mach_z180:
2742	case bfd_mach_ez80_z80:
2743	case bfd_mach_ez80_adl:
2744	  *flagsp = bfd_get_mach (abfd) << 12;
2745	  break;
2746	default:
2747	  return false;
2748	}
2749      return true;
2750#endif
2751
2752#ifdef Z8KMAGIC
2753    case bfd_arch_z8k:
2754      *magicp = Z8KMAGIC;
2755
2756      switch (bfd_get_mach (abfd))
2757	{
2758	case bfd_mach_z8001: *flagsp = F_Z8001;	break;
2759	case bfd_mach_z8002: *flagsp = F_Z8002;	break;
2760	default:	     return false;
2761	}
2762      return true;
2763#endif
2764
2765#ifdef TIC30MAGIC
2766    case bfd_arch_tic30:
2767      *magicp = TIC30MAGIC;
2768      return true;
2769#endif
2770
2771#ifdef TICOFF_DEFAULT_MAGIC
2772    case TICOFF_TARGET_ARCH:
2773      /* If there's no indication of which version we want, use the default.  */
2774      if (!abfd->xvec )
2775	*magicp = TICOFF_DEFAULT_MAGIC;
2776      else
2777	{
2778	  /* We may want to output in a different COFF version.  */
2779	  switch (abfd->xvec->name[4])
2780	    {
2781	    case '0':
2782	      *magicp = TICOFF0MAGIC;
2783	      break;
2784	    case '1':
2785	      *magicp = TICOFF1MAGIC;
2786	      break;
2787	    case '2':
2788	      *magicp = TICOFF2MAGIC;
2789	      break;
2790	    default:
2791	      return false;
2792	    }
2793	}
2794      TICOFF_TARGET_MACHINE_SET (flagsp, bfd_get_mach (abfd));
2795      return true;
2796#endif
2797
2798#ifdef AARCH64MAGIC
2799    case bfd_arch_aarch64:
2800      * magicp = AARCH64MAGIC;
2801      return true;
2802#endif
2803
2804#ifdef LOONGARCH64MAGIC
2805    case bfd_arch_loongarch:
2806      * magicp = LOONGARCH64MAGIC;
2807      return true;
2808#endif
2809
2810#ifdef ARMMAGIC
2811    case bfd_arch_arm:
2812#ifdef ARM_WINCE
2813      * magicp = ARMPEMAGIC;
2814#else
2815      * magicp = ARMMAGIC;
2816#endif
2817      * flagsp = 0;
2818      if (APCS_SET (abfd))
2819	{
2820	  if (APCS_26_FLAG (abfd))
2821	    * flagsp |= F_APCS26;
2822
2823	  if (APCS_FLOAT_FLAG (abfd))
2824	    * flagsp |= F_APCS_FLOAT;
2825
2826	  if (PIC_FLAG (abfd))
2827	    * flagsp |= F_PIC;
2828	}
2829      if (INTERWORK_SET (abfd) && INTERWORK_FLAG (abfd))
2830	* flagsp |= F_INTERWORK;
2831      switch (bfd_get_mach (abfd))
2832	{
2833	case bfd_mach_arm_2:  * flagsp |= F_ARM_2;  break;
2834	case bfd_mach_arm_2a: * flagsp |= F_ARM_2a; break;
2835	case bfd_mach_arm_3:  * flagsp |= F_ARM_3;  break;
2836	case bfd_mach_arm_3M: * flagsp |= F_ARM_3M; break;
2837	case bfd_mach_arm_4:  * flagsp |= F_ARM_4;  break;
2838	case bfd_mach_arm_4T: * flagsp |= F_ARM_4T; break;
2839	case bfd_mach_arm_5:  * flagsp |= F_ARM_5;  break;
2840	  /* FIXME: we do not have F_ARM vaues greater than F_ARM_5.
2841	     See also the comment in coff_set_arch_mach_hook().  */
2842	case bfd_mach_arm_5T: * flagsp |= F_ARM_5;  break;
2843	case bfd_mach_arm_5TE: * flagsp |= F_ARM_5; break;
2844	case bfd_mach_arm_XScale: * flagsp |= F_ARM_5; break;
2845	}
2846      return true;
2847#endif
2848
2849#if defined(I386MAGIC) || defined(AMD64MAGIC)
2850    case bfd_arch_i386:
2851#if defined(I386MAGIC)
2852      *magicp = I386MAGIC;
2853#endif
2854#if defined LYNXOS
2855      /* Just overwrite the usual value if we're doing Lynx.  */
2856      *magicp = LYNXCOFFMAGIC;
2857#endif
2858#if defined AMD64MAGIC
2859      *magicp = AMD64MAGIC;
2860#endif
2861      return true;
2862#endif
2863
2864#ifdef IA64MAGIC
2865    case bfd_arch_ia64:
2866      *magicp = IA64MAGIC;
2867      return true;
2868#endif
2869
2870#ifdef SH_ARCH_MAGIC_BIG
2871    case bfd_arch_sh:
2872#ifdef COFF_IMAGE_WITH_PE
2873      *magicp = SH_ARCH_MAGIC_WINCE;
2874#else
2875      if (bfd_big_endian (abfd))
2876	*magicp = SH_ARCH_MAGIC_BIG;
2877      else
2878	*magicp = SH_ARCH_MAGIC_LITTLE;
2879#endif
2880      return true;
2881#endif
2882
2883#ifdef MIPS_ARCH_MAGIC_WINCE
2884    case bfd_arch_mips:
2885      *magicp = MIPS_ARCH_MAGIC_WINCE;
2886      return true;
2887#endif
2888
2889#ifdef SPARCMAGIC
2890    case bfd_arch_sparc:
2891      *magicp = SPARCMAGIC;
2892#ifdef LYNXOS
2893      /* Just overwrite the usual value if we're doing Lynx.  */
2894      *magicp = LYNXCOFFMAGIC;
2895#endif
2896      return true;
2897#endif
2898
2899#ifdef RS6000COFF_C
2900    case bfd_arch_rs6000:
2901    case bfd_arch_powerpc:
2902      BFD_ASSERT (bfd_get_flavour (abfd) == bfd_target_xcoff_flavour);
2903      *magicp = bfd_xcoff_magic_number (abfd);
2904      return true;
2905#endif
2906
2907#ifdef MCOREMAGIC
2908    case bfd_arch_mcore:
2909      * magicp = MCOREMAGIC;
2910      return true;
2911#endif
2912
2913    default:			/* Unknown architecture.  */
2914      break;
2915    }
2916
2917  return false;
2918}
2919
2920static bool
2921coff_set_arch_mach (bfd * abfd,
2922		    enum bfd_architecture arch,
2923		    unsigned long machine)
2924{
2925  unsigned dummy1;
2926  unsigned short dummy2;
2927
2928  if (! bfd_default_set_arch_mach (abfd, arch, machine))
2929    return false;
2930
2931  if (arch != bfd_arch_unknown
2932      && ! coff_set_flags (abfd, &dummy1, &dummy2))
2933    return false;		/* We can't represent this type.  */
2934
2935  return true;			/* We're easy...  */
2936}
2937
2938#ifdef COFF_IMAGE_WITH_PE
2939
2940/* This is used to sort sections by VMA, as required by PE image
2941   files.  */
2942
2943static int
2944sort_by_secaddr (const void * arg1, const void * arg2)
2945{
2946  const asection *a = *(const asection **) arg1;
2947  const asection *b = *(const asection **) arg2;
2948
2949  if (a->vma < b->vma)
2950    return -1;
2951  else if (a->vma > b->vma)
2952    return 1;
2953
2954  return 0;
2955}
2956
2957#endif /* COFF_IMAGE_WITH_PE */
2958
2959/* Calculate the file position for each section.  */
2960
2961#define ALIGN_SECTIONS_IN_FILE
2962#ifdef TICOFF
2963#undef ALIGN_SECTIONS_IN_FILE
2964#endif
2965
2966static bool
2967coff_compute_section_file_positions (bfd * abfd)
2968{
2969  asection *current;
2970  file_ptr sofar = bfd_coff_filhsz (abfd);
2971  bool align_adjust;
2972  unsigned int target_index;
2973#ifdef ALIGN_SECTIONS_IN_FILE
2974  asection *previous = NULL;
2975  file_ptr old_sofar;
2976#endif
2977
2978#ifdef COFF_IMAGE_WITH_PE
2979  unsigned int page_size;
2980
2981  if (coff_data (abfd)->link_info
2982      || (pe_data (abfd) && pe_data (abfd)->pe_opthdr.FileAlignment))
2983    {
2984      page_size = pe_data (abfd)->pe_opthdr.FileAlignment;
2985
2986      /* If no file alignment has been set, default to one.
2987	 This repairs 'ld -r' for arm-wince-pe target.  */
2988      if (page_size == 0)
2989	page_size = 1;
2990    }
2991  else
2992    page_size = PE_DEF_FILE_ALIGNMENT;
2993#else
2994#ifdef COFF_PAGE_SIZE
2995  unsigned int page_size = COFF_PAGE_SIZE;
2996#endif
2997#endif
2998
2999#ifdef RS6000COFF_C
3000  /* On XCOFF, if we have symbols, set up the .debug section.  */
3001  if (bfd_get_symcount (abfd) > 0)
3002    {
3003      bfd_size_type sz;
3004      bfd_size_type i, symcount;
3005      asymbol **symp;
3006
3007      sz = 0;
3008      symcount = bfd_get_symcount (abfd);
3009      for (symp = abfd->outsymbols, i = 0; i < symcount; symp++, i++)
3010	{
3011	  coff_symbol_type *cf;
3012
3013	  cf = coff_symbol_from (*symp);
3014	  if (cf != NULL
3015	      && cf->native != NULL
3016	      && cf->native->is_sym
3017	      && SYMNAME_IN_DEBUG (&cf->native->u.syment))
3018	    {
3019	      size_t len;
3020
3021	      len = strlen (bfd_asymbol_name (*symp));
3022	      if (len > SYMNMLEN || bfd_coff_force_symnames_in_strings (abfd))
3023		sz += len + 1 + bfd_coff_debug_string_prefix_length (abfd);
3024	    }
3025	}
3026      if (sz > 0)
3027	{
3028	  asection *dsec;
3029
3030	  dsec = bfd_make_section_old_way (abfd, DOT_DEBUG);
3031	  if (dsec == NULL)
3032	    abort ();
3033	  dsec->size = sz;
3034	  dsec->flags |= SEC_HAS_CONTENTS;
3035	}
3036    }
3037#endif
3038
3039  if (bfd_get_start_address (abfd))
3040    /*  A start address may have been added to the original file. In this
3041	case it will need an optional header to record it.  */
3042    abfd->flags |= EXEC_P;
3043
3044  if (abfd->flags & EXEC_P)
3045    sofar += bfd_coff_aoutsz (abfd);
3046#ifdef RS6000COFF_C
3047  else if (xcoff_data (abfd)->full_aouthdr)
3048    sofar += bfd_coff_aoutsz (abfd);
3049  else
3050    sofar += SMALL_AOUTSZ;
3051#endif
3052
3053  sofar += abfd->section_count * bfd_coff_scnhsz (abfd);
3054
3055#ifdef RS6000COFF_C
3056  /* XCOFF handles overflows in the reloc and line number count fields
3057     by allocating a new section header to hold the correct counts.  */
3058  for (current = abfd->sections; current != NULL; current = current->next)
3059    if (current->reloc_count >= 0xffff || current->lineno_count >= 0xffff)
3060      sofar += bfd_coff_scnhsz (abfd);
3061#endif
3062
3063#ifdef COFF_IMAGE_WITH_PE
3064  {
3065    /* PE requires the sections to be in memory order when listed in
3066       the section headers.  It also does not like empty loadable
3067       sections.  The sections apparently do not have to be in the
3068       right order in the image file itself, but we do need to get the
3069       target_index values right.  */
3070
3071    unsigned int count;
3072    asection **section_list;
3073    unsigned int i;
3074    bfd_size_type amt;
3075
3076#ifdef COFF_PAGE_SIZE
3077    /* Clear D_PAGED if section / file alignment aren't suitable for
3078       paging at COFF_PAGE_SIZE granularity.  */
3079   if (pe_data (abfd)->pe_opthdr.SectionAlignment < COFF_PAGE_SIZE
3080       || page_size < COFF_PAGE_SIZE)
3081     abfd->flags &= ~D_PAGED;
3082#endif
3083
3084    count = 0;
3085    for (current = abfd->sections; current != NULL; current = current->next)
3086      ++count;
3087
3088    /* We allocate an extra cell to simplify the final loop.  */
3089    amt = sizeof (struct asection *) * (count + 1);
3090    section_list = (asection **) bfd_malloc (amt);
3091    if (section_list == NULL)
3092      return false;
3093
3094    i = 0;
3095    for (current = abfd->sections; current != NULL; current = current->next)
3096      {
3097	section_list[i] = current;
3098	++i;
3099      }
3100    section_list[i] = NULL;
3101
3102    qsort (section_list, count, sizeof (asection *), sort_by_secaddr);
3103
3104    /* Rethread the linked list into sorted order; at the same time,
3105       assign target_index values.  */
3106    target_index = 1;
3107    abfd->sections = NULL;
3108    abfd->section_last = NULL;
3109    for (i = 0; i < count; i++)
3110      {
3111	current = section_list[i];
3112	bfd_section_list_append (abfd, current);
3113
3114	/* Later, if the section has zero size, we'll be throwing it
3115	   away, so we don't want to number it now.  Note that having
3116	   a zero size and having real contents are different
3117	   concepts: .bss has no contents, but (usually) non-zero
3118	   size.  */
3119	if (current->size == 0)
3120	  {
3121	    /* Discard.  However, it still might have (valid) symbols
3122	       in it, so arbitrarily set it to section 1 (indexing is
3123	       1-based here; usually .text).  __end__ and other
3124	       contents of .endsection really have this happen.
3125	       FIXME: This seems somewhat dubious.  */
3126	    current->target_index = 1;
3127	  }
3128	else
3129	  current->target_index = target_index++;
3130      }
3131
3132    free (section_list);
3133  }
3134#else /* ! COFF_IMAGE_WITH_PE */
3135  {
3136    /* Set the target_index field.  */
3137    target_index = 1;
3138    for (current = abfd->sections; current != NULL; current = current->next)
3139      current->target_index = target_index++;
3140  }
3141#endif /* ! COFF_IMAGE_WITH_PE */
3142
3143  if (target_index >= bfd_coff_max_nscns (abfd))
3144    {
3145      bfd_set_error (bfd_error_file_too_big);
3146      _bfd_error_handler
3147	/* xgettext:c-format */
3148	(_("%pB: too many sections (%d)"), abfd, target_index);
3149      return false;
3150    }
3151
3152  align_adjust = false;
3153  for (current = abfd->sections;
3154       current != NULL;
3155       current = current->next)
3156    {
3157#ifdef COFF_IMAGE_WITH_PE
3158      /* With PE we have to pad each section to be a multiple of its
3159	 page size too, and remember both sizes.  */
3160      if (coff_section_data (abfd, current) == NULL)
3161	{
3162	  size_t amt = sizeof (struct coff_section_tdata);
3163
3164	  current->used_by_bfd = bfd_zalloc (abfd, amt);
3165	  if (current->used_by_bfd == NULL)
3166	    return false;
3167	}
3168      if (pei_section_data (abfd, current) == NULL)
3169	{
3170	  size_t amt = sizeof (struct pei_section_tdata);
3171
3172	  coff_section_data (abfd, current)->tdata = bfd_zalloc (abfd, amt);
3173	  if (coff_section_data (abfd, current)->tdata == NULL)
3174	    return false;
3175	}
3176      if (pei_section_data (abfd, current)->virt_size == 0)
3177	pei_section_data (abfd, current)->virt_size = current->size;
3178#endif
3179
3180      /* Only deal with sections which have contents.  */
3181      if (!(current->flags & SEC_HAS_CONTENTS))
3182	continue;
3183
3184      current->rawsize = current->size;
3185
3186#ifdef COFF_IMAGE_WITH_PE
3187      /* Make sure we skip empty sections in a PE image.  */
3188      if (current->size == 0)
3189	continue;
3190#endif
3191
3192      /* Align the sections in the file to the same boundary on
3193	 which they are aligned in virtual memory.  */
3194#ifdef ALIGN_SECTIONS_IN_FILE
3195      if ((abfd->flags & EXEC_P) != 0)
3196	{
3197	  /* Make sure this section is aligned on the right boundary - by
3198	     padding the previous section up if necessary.  */
3199	  old_sofar = sofar;
3200
3201#ifdef COFF_IMAGE_WITH_PE
3202	  sofar = BFD_ALIGN (sofar, page_size);
3203#else
3204	  sofar = BFD_ALIGN (sofar, (bfd_vma) 1 << current->alignment_power);
3205#endif
3206
3207#ifdef RS6000COFF_C
3208	  /* Make sure the file offset and the vma of .text/.data are at the
3209	     same page offset, so that the file can be mmap'ed without being
3210	     relocated.  Failing that, AIX is able to load and execute the
3211	     program, but it will be silently relocated (possible as
3212	     executables are PIE).  But the relocation is slightly costly and
3213	     complexify the use of addr2line or gdb.  So better to avoid it,
3214	     like does the native linker.  Usually gnu ld makes sure that
3215	     the vma of .text is the file offset so this issue shouldn't
3216	     appear unless you are stripping such an executable.
3217
3218	     AIX loader checks the text section alignment of (vma - filepos),
3219	     and the native linker doesn't try to align the text sections.
3220	     For example:
3221
3222	     0 .text	     000054cc  10000128	 10000128  00000128  2**5
3223			     CONTENTS, ALLOC, LOAD, CODE
3224
3225	     Don't perform the above tweak if the previous one is .tdata,
3226	     as it will increase the memory allocated for every threads
3227	     created and not just improve performances with gdb.
3228	  */
3229
3230	  if ((!strcmp (current->name, _TEXT)
3231	       || !strcmp (current->name, _DATA))
3232	      && (previous == NULL || strcmp(previous->name, _TDATA)))
3233	    {
3234	      bfd_vma align = 4096;
3235	      bfd_vma sofar_off = sofar % align;
3236	      bfd_vma vma_off = current->vma % align;
3237
3238	      if (vma_off > sofar_off)
3239		sofar += vma_off - sofar_off;
3240	      else if (vma_off < sofar_off)
3241		sofar += align + vma_off - sofar_off;
3242	    }
3243#endif
3244	  if (previous != NULL)
3245	    previous->size += sofar - old_sofar;
3246	}
3247
3248#endif
3249
3250      /* In demand paged files the low order bits of the file offset
3251	 must match the low order bits of the virtual address.  */
3252#ifdef COFF_PAGE_SIZE
3253      if ((abfd->flags & D_PAGED) != 0
3254	  && (current->flags & SEC_ALLOC) != 0)
3255	sofar += (current->vma - (bfd_vma) sofar) % page_size;
3256#endif
3257      current->filepos = sofar;
3258
3259#ifdef COFF_IMAGE_WITH_PE
3260      /* Set the padded size.  */
3261      current->size = (current->size + page_size - 1) & -page_size;
3262#endif
3263
3264      sofar += current->size;
3265
3266#ifdef ALIGN_SECTIONS_IN_FILE
3267      /* Make sure that this section is of the right size too.  */
3268      if ((abfd->flags & EXEC_P) == 0)
3269	{
3270	  bfd_size_type old_size;
3271
3272	  old_size = current->size;
3273	  current->size = BFD_ALIGN (current->size,
3274				     (bfd_vma) 1 << current->alignment_power);
3275	  align_adjust = current->size != old_size;
3276	  sofar += current->size - old_size;
3277	}
3278      else
3279	{
3280	  old_sofar = sofar;
3281#ifdef COFF_IMAGE_WITH_PE
3282	  sofar = BFD_ALIGN (sofar, page_size);
3283#else
3284	  sofar = BFD_ALIGN (sofar, (bfd_vma) 1 << current->alignment_power);
3285#endif
3286	  align_adjust = sofar != old_sofar;
3287	  current->size += sofar - old_sofar;
3288	}
3289#endif
3290
3291#ifdef COFF_IMAGE_WITH_PE
3292      /* For PE we need to make sure we pad out to the aligned
3293	 size, in case the caller only writes out data to the
3294	 unaligned size.  */
3295      if (pei_section_data (abfd, current)->virt_size < current->size)
3296	align_adjust = true;
3297#endif
3298
3299#ifdef _LIB
3300      /* Force .lib sections to start at zero.  The vma is then
3301	 incremented in coff_set_section_contents.  This is right for
3302	 SVR3.2.  */
3303      if (strcmp (current->name, _LIB) == 0)
3304	bfd_set_section_vma (current, 0);
3305#endif
3306
3307#ifdef ALIGN_SECTIONS_IN_FILE
3308      previous = current;
3309#endif
3310    }
3311
3312  /* It is now safe to write to the output file.  If we needed an
3313     alignment adjustment for the last section, then make sure that
3314     there is a byte at offset sofar.  If there are no symbols and no
3315     relocs, then nothing follows the last section.  If we don't force
3316     the last byte out, then the file may appear to be truncated.  */
3317  if (align_adjust)
3318    {
3319      bfd_byte b;
3320
3321      b = 0;
3322      if (bfd_seek (abfd, sofar - 1, SEEK_SET) != 0
3323	  || bfd_bwrite (&b, (bfd_size_type) 1, abfd) != 1)
3324	return false;
3325    }
3326
3327  /* Make sure the relocations are aligned.  We don't need to make
3328     sure that this byte exists, because it will only matter if there
3329     really are relocs.  */
3330  sofar = BFD_ALIGN (sofar,
3331		     (bfd_vma) 1 << COFF_DEFAULT_SECTION_ALIGNMENT_POWER);
3332
3333  obj_relocbase (abfd) = sofar;
3334  abfd->output_has_begun = true;
3335
3336  return true;
3337}
3338
3339#ifdef COFF_IMAGE_WITH_PE
3340
3341static bool
3342coff_read_word (bfd *abfd, unsigned int *value, unsigned int *pelength)
3343{
3344  unsigned char b[2];
3345  int status;
3346
3347  status = bfd_bread (b, (bfd_size_type) 2, abfd);
3348  if (status < 1)
3349    {
3350      *value = 0;
3351      return false;
3352    }
3353
3354  if (status == 1)
3355    *value = (unsigned int) b[0];
3356  else
3357    *value = (unsigned int) (b[0] + (b[1] << 8));
3358
3359  *pelength += status;
3360
3361  return true;
3362}
3363
3364static unsigned int
3365coff_compute_checksum (bfd *abfd, unsigned int *pelength)
3366{
3367  bool more_data;
3368  file_ptr filepos;
3369  unsigned int value;
3370  unsigned int total;
3371
3372  total = 0;
3373  *pelength = 0;
3374  filepos = (file_ptr) 0;
3375
3376  do
3377    {
3378      if (bfd_seek (abfd, filepos, SEEK_SET) != 0)
3379	return 0;
3380
3381      more_data = coff_read_word (abfd, &value, pelength);
3382      total += value;
3383      total = 0xffff & (total + (total >> 0x10));
3384      filepos += 2;
3385    }
3386  while (more_data);
3387
3388  return (0xffff & (total + (total >> 0x10)));
3389}
3390
3391static bool
3392coff_apply_checksum (bfd *abfd)
3393{
3394  unsigned int computed;
3395  unsigned int checksum = 0;
3396  unsigned int peheader;
3397  unsigned int pelength;
3398
3399  if (bfd_seek (abfd, 0x3c, SEEK_SET) != 0)
3400    return false;
3401
3402  if (!coff_read_word (abfd, &peheader, &pelength))
3403    return false;
3404
3405  if (bfd_seek (abfd, peheader + 0x58, SEEK_SET) != 0)
3406    return false;
3407
3408  checksum = 0;
3409  bfd_bwrite (&checksum, (bfd_size_type) 4, abfd);
3410
3411  if (bfd_seek (abfd, peheader, SEEK_SET) != 0)
3412    return false;
3413
3414  computed = coff_compute_checksum (abfd, &pelength);
3415
3416  checksum = computed + pelength;
3417
3418  if (bfd_seek (abfd, peheader + 0x58, SEEK_SET) != 0)
3419    return false;
3420
3421  bfd_bwrite (&checksum, (bfd_size_type) 4, abfd);
3422
3423  return true;
3424}
3425
3426#endif /* COFF_IMAGE_WITH_PE */
3427
3428static bool
3429coff_write_object_contents (bfd * abfd)
3430{
3431  asection *current;
3432  bool hasrelocs = false;
3433  bool haslinno = false;
3434#ifdef COFF_IMAGE_WITH_PE
3435  bool hasdebug = false;
3436#endif
3437  file_ptr scn_base;
3438  file_ptr reloc_base;
3439  file_ptr lineno_base;
3440  file_ptr sym_base;
3441  unsigned long reloc_size = 0, reloc_count = 0;
3442  unsigned long lnno_size = 0;
3443  bool long_section_names;
3444  asection *text_sec = NULL;
3445  asection *data_sec = NULL;
3446  asection *bss_sec = NULL;
3447#ifdef RS6000COFF_C
3448  asection *tdata_sec = NULL;
3449  asection *tbss_sec = NULL;
3450#endif
3451  struct internal_filehdr internal_f;
3452  struct internal_aouthdr internal_a;
3453#ifdef COFF_LONG_SECTION_NAMES
3454  size_t string_size = STRING_SIZE_SIZE;
3455#endif
3456
3457  bfd_set_error (bfd_error_system_call);
3458
3459  /* Make a pass through the symbol table to count line number entries and
3460     put them into the correct asections.  */
3461  lnno_size = coff_count_linenumbers (abfd) * bfd_coff_linesz (abfd);
3462
3463  if (! abfd->output_has_begun)
3464    {
3465      if (! coff_compute_section_file_positions (abfd))
3466	return false;
3467    }
3468
3469  reloc_base = obj_relocbase (abfd);
3470
3471  /* Work out the size of the reloc and linno areas.  */
3472
3473  for (current = abfd->sections; current != NULL; current =
3474       current->next)
3475    {
3476#ifdef COFF_WITH_EXTENDED_RELOC_COUNTER
3477      /* We store the actual reloc count in the first reloc's addr.  */
3478      if ((obj_pe (abfd) || obj_go32 (abfd)) && current->reloc_count >= 0xffff)
3479	reloc_count ++;
3480#endif
3481      reloc_count += current->reloc_count;
3482    }
3483
3484  reloc_size = reloc_count * bfd_coff_relsz (abfd);
3485
3486  lineno_base = reloc_base + reloc_size;
3487  sym_base = lineno_base + lnno_size;
3488
3489  /* Indicate in each section->line_filepos its actual file address.  */
3490  for (current = abfd->sections; current != NULL; current =
3491       current->next)
3492    {
3493      if (current->lineno_count)
3494	{
3495	  current->line_filepos = lineno_base;
3496	  current->moving_line_filepos = lineno_base;
3497	  lineno_base += current->lineno_count * bfd_coff_linesz (abfd);
3498	}
3499      else
3500	current->line_filepos = 0;
3501
3502      if (current->reloc_count)
3503	{
3504	  current->rel_filepos = reloc_base;
3505	  reloc_base += current->reloc_count * bfd_coff_relsz (abfd);
3506#ifdef COFF_WITH_EXTENDED_RELOC_COUNTER
3507	  /* Extra reloc to hold real count.  */
3508	  if ((obj_pe (abfd) || obj_go32 (abfd)) && current->reloc_count >= 0xffff)
3509	    reloc_base += bfd_coff_relsz (abfd);
3510#endif
3511	}
3512      else
3513	current->rel_filepos = 0;
3514    }
3515
3516  /* Write section headers to the file.  */
3517  internal_f.f_nscns = 0;
3518
3519  if ((abfd->flags & EXEC_P) != 0)
3520    scn_base = bfd_coff_filhsz (abfd) + bfd_coff_aoutsz (abfd);
3521  else
3522    {
3523      scn_base = bfd_coff_filhsz (abfd);
3524#ifdef RS6000COFF_C
3525#ifndef XCOFF64
3526      if (xcoff_data (abfd)->full_aouthdr)
3527	scn_base += bfd_coff_aoutsz (abfd);
3528      else
3529	scn_base += SMALL_AOUTSZ;
3530#endif
3531#endif
3532    }
3533
3534  if (bfd_seek (abfd, scn_base, SEEK_SET) != 0)
3535    return false;
3536
3537  long_section_names = false;
3538  for (current = abfd->sections;
3539       current != NULL;
3540       current = current->next)
3541    {
3542      struct internal_scnhdr section;
3543#ifdef COFF_IMAGE_WITH_PE
3544      bool is_reloc_section = false;
3545
3546      if (strcmp (current->name, DOT_RELOC) == 0)
3547	{
3548	  is_reloc_section = true;
3549	  hasrelocs = true;
3550	  pe_data (abfd)->has_reloc_section = 1;
3551	}
3552#endif
3553
3554      internal_f.f_nscns++;
3555
3556      strncpy (section.s_name, current->name, SCNNMLEN);
3557
3558#ifdef COFF_LONG_SECTION_NAMES
3559      /* Handle long section names as in PE.  This must be compatible
3560	 with the code in coff_write_symbols and _bfd_coff_final_link.  */
3561      if (bfd_coff_long_section_names (abfd))
3562	{
3563	  size_t len;
3564
3565	  len = strlen (current->name);
3566	  if (len > SCNNMLEN)
3567	    {
3568	      /* The s_name field is defined to be NUL-padded but need not be
3569		 NUL-terminated.  We use a temporary buffer so that we can still
3570		 sprintf all eight chars without splatting a terminating NUL
3571		 over the first byte of the following member (s_paddr).  */
3572	      /* PR 21096: The +20 is to stop a bogus warning from gcc7 about
3573		 a possible buffer overflow.  */
3574	      char s_name_buf[SCNNMLEN + 1 + 20];
3575
3576	      /* An inherent limitation of the /nnnnnnn notation used to indicate
3577		 the offset of the long name in the string table is that we
3578		 cannot address entries beyone the ten million byte boundary.  */
3579	      if (string_size >= 10000000)
3580		{
3581		  bfd_set_error (bfd_error_file_too_big);
3582		  _bfd_error_handler
3583		    /* xgettext:c-format */
3584		    (_("%pB: section %pA: string table overflow at offset %ld"),
3585		    abfd, current, (unsigned long) string_size);
3586		  return false;
3587		}
3588
3589	      /* We do not need to use snprintf here as we have already verfied
3590		 that string_size is not too big, plus we have an overlarge
3591		 buffer, just in case.  */
3592	      sprintf (s_name_buf, "/%lu", (unsigned long) string_size);
3593	      /* Then strncpy takes care of any padding for us.  */
3594	      strncpy (section.s_name, s_name_buf, SCNNMLEN);
3595	      string_size += len + 1;
3596	      long_section_names = true;
3597	    }
3598	}
3599#endif
3600
3601#ifdef _LIB
3602      /* Always set s_vaddr of .lib to 0.  This is right for SVR3.2
3603	 Ian Taylor <ian@cygnus.com>.  */
3604      if (strcmp (current->name, _LIB) == 0)
3605	section.s_vaddr = 0;
3606      else
3607#endif
3608      section.s_vaddr = current->vma;
3609      section.s_paddr = current->lma;
3610      section.s_size =  current->size;
3611#ifdef coff_get_section_load_page
3612      section.s_page = coff_get_section_load_page (current);
3613#else
3614      section.s_page = 0;
3615#endif
3616
3617#ifdef COFF_WITH_PE
3618      section.s_paddr = 0;
3619#endif
3620#ifdef COFF_IMAGE_WITH_PE
3621      /* Reminder: s_paddr holds the virtual size of the section.  */
3622      if (coff_section_data (abfd, current) != NULL
3623	  && pei_section_data (abfd, current) != NULL)
3624	section.s_paddr = pei_section_data (abfd, current)->virt_size;
3625      else
3626	section.s_paddr = 0;
3627#endif
3628
3629      /* If this section has no size or is unloadable then the scnptr
3630	 will be 0 too.  */
3631      if (current->size == 0
3632	  || (current->flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
3633	section.s_scnptr = 0;
3634      else
3635	section.s_scnptr = current->filepos;
3636
3637      section.s_relptr = current->rel_filepos;
3638      section.s_lnnoptr = current->line_filepos;
3639      section.s_nreloc = current->reloc_count;
3640      section.s_nlnno = current->lineno_count;
3641#ifndef COFF_IMAGE_WITH_PE
3642      /* In PEI, relocs come in the .reloc section.  */
3643      if (current->reloc_count != 0)
3644	hasrelocs = true;
3645#endif
3646      if (current->lineno_count != 0)
3647	haslinno = true;
3648#ifdef COFF_IMAGE_WITH_PE
3649      if ((current->flags & SEC_DEBUGGING) != 0
3650	  && ! is_reloc_section)
3651	hasdebug = true;
3652#endif
3653
3654#ifdef RS6000COFF_C
3655#ifndef XCOFF64
3656      /* Indicate the use of an XCOFF overflow section header.  */
3657      if (current->reloc_count >= 0xffff || current->lineno_count >= 0xffff)
3658	{
3659	  section.s_nreloc = 0xffff;
3660	  section.s_nlnno = 0xffff;
3661	}
3662#endif
3663#endif
3664
3665      section.s_flags = sec_to_styp_flags (current->name, current->flags);
3666
3667      if (!strcmp (current->name, _TEXT))
3668	text_sec = current;
3669      else if (!strcmp (current->name, _DATA))
3670	data_sec = current;
3671      else if (!strcmp (current->name, _BSS))
3672	bss_sec = current;
3673#ifdef RS6000COFF_C
3674      else if (!strcmp (current->name, _TDATA))
3675	tdata_sec = current;
3676      else if (!strcmp (current->name, _TBSS))
3677	tbss_sec = current;
3678#endif
3679
3680
3681#ifdef COFF_ENCODE_ALIGNMENT
3682      if (COFF_ENCODE_ALIGNMENT (abfd, section, current->alignment_power)
3683	  && (COFF_DECODE_ALIGNMENT (section.s_flags)
3684	      != current->alignment_power))
3685	{
3686	  bool warn = (coff_data (abfd)->link_info
3687		       && !bfd_link_relocatable (coff_data (abfd)->link_info));
3688
3689	  _bfd_error_handler
3690	    /* xgettext:c-format */
3691	    (_("%pB:%s section %s: alignment 2**%u not representable"),
3692	     abfd, warn ? " warning:" : "", current->name,
3693	     current->alignment_power);
3694	  if (!warn)
3695	    {
3696	      bfd_set_error (bfd_error_nonrepresentable_section);
3697	      return false;
3698	    }
3699	}
3700#endif
3701
3702#ifdef COFF_IMAGE_WITH_PE
3703      /* Suppress output of the sections if they are null.  ld
3704	 includes the bss and data sections even if there is no size
3705	 assigned to them.  NT loader doesn't like it if these section
3706	 headers are included if the sections themselves are not
3707	 needed.  See also coff_compute_section_file_positions.  */
3708      if (section.s_size == 0)
3709	internal_f.f_nscns--;
3710      else
3711#endif
3712	{
3713	  SCNHDR buff;
3714	  bfd_size_type amt = bfd_coff_scnhsz (abfd);
3715
3716	  if (bfd_coff_swap_scnhdr_out (abfd, &section, &buff) == 0
3717	      || bfd_bwrite (& buff, amt, abfd) != amt)
3718	    return false;
3719	}
3720
3721#ifdef COFF_WITH_PE
3722      /* PE stores COMDAT section information in the symbol table.  If
3723	 this section is supposed to have some COMDAT info, track down
3724	 the symbol in the symbol table and modify it.  */
3725      if ((current->flags & SEC_LINK_ONCE) != 0)
3726	{
3727	  unsigned int i, count;
3728	  asymbol **psym;
3729	  coff_symbol_type *csym = NULL;
3730	  asymbol **psymsec;
3731
3732	  psymsec = NULL;
3733	  count = bfd_get_symcount (abfd);
3734	  for (i = 0, psym = abfd->outsymbols; i < count; i++, psym++)
3735	    {
3736	      if ((*psym)->section != current)
3737		continue;
3738
3739	      /* Remember the location of the first symbol in this
3740		 section.  */
3741	      if (psymsec == NULL)
3742		psymsec = psym;
3743
3744	      /* See if this is the section symbol.  */
3745	      if (strcmp ((*psym)->name, current->name) == 0)
3746		{
3747		  csym = coff_symbol_from (*psym);
3748		  if (csym == NULL
3749		      || csym->native == NULL
3750		      || ! csym->native->is_sym
3751		      || csym->native->u.syment.n_numaux < 1
3752		      || csym->native->u.syment.n_sclass != C_STAT
3753		      || csym->native->u.syment.n_type != T_NULL)
3754		    continue;
3755
3756		  /* Here *PSYM is the section symbol for CURRENT.  */
3757
3758		  break;
3759		}
3760	    }
3761
3762	  /* Did we find it?
3763	     Note that we might not if we're converting the file from
3764	     some other object file format.  */
3765	  if (i < count)
3766	    {
3767	      combined_entry_type *aux;
3768
3769	      /* We don't touch the x_checksum field.  The
3770		 x_associated field is not currently supported.  */
3771
3772	      aux = csym->native + 1;
3773	      BFD_ASSERT (! aux->is_sym);
3774	      switch (current->flags & SEC_LINK_DUPLICATES)
3775		{
3776		case SEC_LINK_DUPLICATES_DISCARD:
3777		  aux->u.auxent.x_scn.x_comdat = IMAGE_COMDAT_SELECT_ANY;
3778		  break;
3779
3780		case SEC_LINK_DUPLICATES_ONE_ONLY:
3781		  aux->u.auxent.x_scn.x_comdat =
3782		    IMAGE_COMDAT_SELECT_NODUPLICATES;
3783		  break;
3784
3785		case SEC_LINK_DUPLICATES_SAME_SIZE:
3786		  aux->u.auxent.x_scn.x_comdat =
3787		    IMAGE_COMDAT_SELECT_SAME_SIZE;
3788		  break;
3789
3790		case SEC_LINK_DUPLICATES_SAME_CONTENTS:
3791		  aux->u.auxent.x_scn.x_comdat =
3792		    IMAGE_COMDAT_SELECT_EXACT_MATCH;
3793		  break;
3794		}
3795
3796	      /* The COMDAT symbol must be the first symbol from this
3797		 section in the symbol table.  In order to make this
3798		 work, we move the COMDAT symbol before the first
3799		 symbol we found in the search above.  It's OK to
3800		 rearrange the symbol table at this point, because
3801		 coff_renumber_symbols is going to rearrange it
3802		 further and fix up all the aux entries.  */
3803	      if (psym != psymsec)
3804		{
3805		  asymbol *hold;
3806		  asymbol **pcopy;
3807
3808		  hold = *psym;
3809		  for (pcopy = psym; pcopy > psymsec; pcopy--)
3810		    pcopy[0] = pcopy[-1];
3811		  *psymsec = hold;
3812		}
3813	    }
3814	}
3815#endif /* COFF_WITH_PE */
3816    }
3817
3818#ifdef RS6000COFF_C
3819#ifndef XCOFF64
3820  /* XCOFF handles overflows in the reloc and line number count fields
3821     by creating a new section header to hold the correct values.  */
3822  for (current = abfd->sections; current != NULL; current = current->next)
3823    {
3824      if (current->reloc_count >= 0xffff || current->lineno_count >= 0xffff)
3825	{
3826	  struct internal_scnhdr scnhdr;
3827	  SCNHDR buff;
3828	  bfd_size_type amt;
3829
3830	  internal_f.f_nscns++;
3831	  memcpy (scnhdr.s_name, ".ovrflo", 8);
3832	  scnhdr.s_paddr = current->reloc_count;
3833	  scnhdr.s_vaddr = current->lineno_count;
3834	  scnhdr.s_size = 0;
3835	  scnhdr.s_scnptr = 0;
3836	  scnhdr.s_relptr = current->rel_filepos;
3837	  scnhdr.s_lnnoptr = current->line_filepos;
3838	  scnhdr.s_nreloc = current->target_index;
3839	  scnhdr.s_nlnno = current->target_index;
3840	  scnhdr.s_flags = STYP_OVRFLO;
3841	  amt = bfd_coff_scnhsz (abfd);
3842	  if (bfd_coff_swap_scnhdr_out (abfd, &scnhdr, &buff) == 0
3843	      || bfd_bwrite (& buff, amt, abfd) != amt)
3844	    return false;
3845	}
3846    }
3847#endif
3848#endif
3849
3850#if defined (COFF_GO32_EXE) || defined (COFF_GO32)
3851  /* Pad section headers.  */
3852  if ((abfd->flags & EXEC_P) && abfd->sections != NULL)
3853    {
3854      file_ptr cur_ptr = scn_base
3855			 + abfd->section_count * bfd_coff_scnhsz (abfd);
3856      long fill_size = (abfd->sections->filepos - cur_ptr);
3857      bfd_byte *b = bfd_zmalloc (fill_size);
3858      if (b)
3859	{
3860	  bfd_bwrite (b, fill_size, abfd);
3861	  free (b);
3862	}
3863    }
3864#endif
3865
3866  /* OK, now set up the filehdr...  */
3867
3868  /* Don't include the internal abs section in the section count */
3869
3870  /* We will NOT put a fucking timestamp in the header here. Every time you
3871     put it back, I will come in and take it out again.  I'm sorry.  This
3872     field does not belong here.  We fill it with a 0 so it compares the
3873     same but is not a reasonable time. -- gnu@cygnus.com  */
3874  internal_f.f_timdat = 0;
3875  internal_f.f_flags = 0;
3876
3877  if (abfd->flags & EXEC_P)
3878    internal_f.f_opthdr = bfd_coff_aoutsz (abfd);
3879  else
3880    {
3881      internal_f.f_opthdr = 0;
3882#ifdef RS6000COFF_C
3883#ifndef XCOFF64
3884      if (xcoff_data (abfd)->full_aouthdr)
3885	internal_f.f_opthdr = bfd_coff_aoutsz (abfd);
3886      else
3887	internal_f.f_opthdr = SMALL_AOUTSZ;
3888#endif
3889#endif
3890    }
3891
3892  if (!hasrelocs)
3893    internal_f.f_flags |= F_RELFLG;
3894  if (!haslinno)
3895    internal_f.f_flags |= F_LNNO;
3896  if (abfd->flags & EXEC_P)
3897    internal_f.f_flags |= F_EXEC;
3898#ifdef COFF_IMAGE_WITH_PE
3899  if (! hasdebug)
3900    internal_f.f_flags |= IMAGE_FILE_DEBUG_STRIPPED;
3901  if (pe_data (abfd)->real_flags & IMAGE_FILE_LARGE_ADDRESS_AWARE)
3902    internal_f.f_flags |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
3903#endif
3904
3905#if !defined(COFF_WITH_pex64) && !defined(COFF_WITH_peAArch64) && !defined(COFF_WITH_peLoongArch64)
3906#ifdef COFF_WITH_PE
3907  internal_f.f_flags |= IMAGE_FILE_32BIT_MACHINE;
3908#else
3909  if (bfd_little_endian (abfd))
3910    internal_f.f_flags |= F_AR32WR;
3911  else
3912    internal_f.f_flags |= F_AR32W;
3913#endif
3914#endif
3915
3916#ifdef TI_TARGET_ID
3917  /* Target id is used in TI COFF v1 and later; COFF0 won't use this field,
3918     but it doesn't hurt to set it internally.  */
3919  internal_f.f_target_id = TI_TARGET_ID;
3920#endif
3921
3922  /* FIXME, should do something about the other byte orders and
3923     architectures.  */
3924
3925#ifdef RS6000COFF_C
3926  if ((abfd->flags & DYNAMIC) != 0)
3927    internal_f.f_flags |= F_SHROBJ;
3928  if (bfd_get_section_by_name (abfd, _LOADER) != NULL)
3929    internal_f.f_flags |= F_DYNLOAD;
3930#endif
3931
3932  memset (&internal_a, 0, sizeof internal_a);
3933
3934  /* Set up architecture-dependent stuff.  */
3935  {
3936    unsigned int magic = 0;
3937    unsigned short flags = 0;
3938
3939    coff_set_flags (abfd, &magic, &flags);
3940    internal_f.f_magic = magic;
3941    internal_f.f_flags |= flags;
3942    /* ...and the "opt"hdr...  */
3943
3944#ifdef TICOFF_AOUT_MAGIC
3945    internal_a.magic = TICOFF_AOUT_MAGIC;
3946#define __A_MAGIC_SET__
3947#endif
3948
3949#if defined(ARM)
3950#define __A_MAGIC_SET__
3951    internal_a.magic = ZMAGIC;
3952#endif
3953
3954#if defined(AARCH64)
3955#define __A_MAGIC_SET__
3956    internal_a.magic = ZMAGIC;
3957#endif
3958
3959#if defined(LOONGARCH64)
3960#define __A_MAGIC_SET__
3961    internal_a.magic = ZMAGIC;
3962#endif
3963
3964#if defined MCORE_PE
3965#define __A_MAGIC_SET__
3966    internal_a.magic = IMAGE_NT_OPTIONAL_HDR_MAGIC;
3967#endif
3968
3969#if defined(I386)
3970#define __A_MAGIC_SET__
3971#if defined LYNXOS
3972    internal_a.magic = LYNXCOFFMAGIC;
3973#elif defined AMD64
3974    internal_a.magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC;
3975#else
3976    internal_a.magic = ZMAGIC;
3977#endif
3978#endif /* I386 */
3979
3980#if defined(IA64)
3981#define __A_MAGIC_SET__
3982    internal_a.magic = PE32PMAGIC;
3983#endif /* IA64 */
3984
3985#if defined(SPARC)
3986#define __A_MAGIC_SET__
3987#if defined(LYNXOS)
3988    internal_a.magic = LYNXCOFFMAGIC;
3989#endif /* LYNXOS */
3990#endif /* SPARC */
3991
3992#ifdef RS6000COFF_C
3993#define __A_MAGIC_SET__
3994    internal_a.magic = (abfd->flags & D_PAGED) ? RS6K_AOUTHDR_ZMAGIC :
3995    (abfd->flags & WP_TEXT) ? RS6K_AOUTHDR_NMAGIC :
3996    RS6K_AOUTHDR_OMAGIC;
3997#endif
3998
3999#if defined(SH) && defined(COFF_WITH_PE)
4000#define __A_MAGIC_SET__
4001    internal_a.magic = SH_PE_MAGIC;
4002#endif
4003
4004#if defined(MIPS) && defined(COFF_WITH_PE)
4005#define __A_MAGIC_SET__
4006    internal_a.magic = MIPS_PE_MAGIC;
4007#endif
4008
4009#ifndef __A_MAGIC_SET__
4010#include "Your aouthdr magic number is not being set!"
4011#else
4012#undef __A_MAGIC_SET__
4013#endif
4014  }
4015
4016#ifdef RS6000COFF_C
4017  /* XCOFF 32bit needs this to have new behaviour for n_type field.  */
4018  internal_a.vstamp = 2;
4019#else
4020  /* FIXME: Does anybody ever set this to another value?  */
4021  internal_a.vstamp = 0;
4022#endif
4023
4024  /* Now should write relocs, strings, syms.  */
4025  obj_sym_filepos (abfd) = sym_base;
4026
4027  if (bfd_get_symcount (abfd) != 0)
4028    {
4029      int firstundef;
4030
4031      if (!coff_renumber_symbols (abfd, &firstundef))
4032	return false;
4033      coff_mangle_symbols (abfd);
4034      if (! coff_write_symbols (abfd))
4035	return false;
4036      if (! coff_write_linenumbers (abfd))
4037	return false;
4038      if (! coff_write_relocs (abfd, firstundef))
4039	return false;
4040    }
4041#ifdef COFF_LONG_SECTION_NAMES
4042  else if (long_section_names && ! obj_coff_strings_written (abfd))
4043    {
4044      /* If we have long section names we have to write out the string
4045	 table even if there are no symbols.  */
4046      if (! coff_write_symbols (abfd))
4047	return false;
4048    }
4049#endif
4050  /* If bfd_get_symcount (abfd) != 0, then we are not using the COFF
4051     backend linker, and obj_raw_syment_count is not valid until after
4052     coff_write_symbols is called.  */
4053  if (obj_raw_syment_count (abfd) != 0)
4054    {
4055      internal_f.f_symptr = sym_base;
4056#ifdef RS6000COFF_C
4057      /* AIX appears to require that F_RELFLG not be set if there are
4058	 local symbols but no relocations.  */
4059      internal_f.f_flags &=~ F_RELFLG;
4060#endif
4061    }
4062  else
4063    {
4064      if (long_section_names)
4065	internal_f.f_symptr = sym_base;
4066      else
4067	internal_f.f_symptr = 0;
4068      internal_f.f_flags |= F_LSYMS;
4069    }
4070
4071  if (text_sec)
4072    {
4073      internal_a.tsize = text_sec->size;
4074      internal_a.text_start = internal_a.tsize ? text_sec->vma : 0;
4075    }
4076  if (data_sec)
4077    {
4078      internal_a.dsize = data_sec->size;
4079      internal_a.data_start = internal_a.dsize ? data_sec->vma : 0;
4080    }
4081  if (bss_sec)
4082    {
4083      internal_a.bsize = bss_sec->size;
4084      if (internal_a.bsize && bss_sec->vma < internal_a.data_start)
4085	internal_a.data_start = bss_sec->vma;
4086    }
4087
4088  internal_a.entry = bfd_get_start_address (abfd);
4089  internal_f.f_nsyms = obj_raw_syment_count (abfd);
4090
4091#ifdef RS6000COFF_C
4092  if (xcoff_data (abfd)->full_aouthdr)
4093    {
4094      bfd_vma toc;
4095      asection *loader_sec;
4096
4097      internal_a.vstamp = 2;
4098
4099      internal_a.o_snentry = xcoff_data (abfd)->snentry;
4100      if (internal_a.o_snentry == 0)
4101	internal_a.entry = (bfd_vma) -1;
4102
4103      if (text_sec != NULL)
4104	{
4105	  internal_a.o_sntext = text_sec->target_index;
4106	  internal_a.o_algntext = bfd_section_alignment (text_sec);
4107	}
4108      else
4109	{
4110	  internal_a.o_sntext = 0;
4111	  internal_a.o_algntext = 0;
4112	}
4113      if (data_sec != NULL)
4114	{
4115	  internal_a.o_sndata = data_sec->target_index;
4116	  internal_a.o_algndata = bfd_section_alignment (data_sec);
4117	}
4118      else
4119	{
4120	  internal_a.o_sndata = 0;
4121	  internal_a.o_algndata = 0;
4122	}
4123      loader_sec = bfd_get_section_by_name (abfd, ".loader");
4124      if (loader_sec != NULL)
4125	internal_a.o_snloader = loader_sec->target_index;
4126      else
4127	internal_a.o_snloader = 0;
4128      if (bss_sec != NULL)
4129	internal_a.o_snbss = bss_sec->target_index;
4130      else
4131	internal_a.o_snbss = 0;
4132
4133      if (tdata_sec != NULL)
4134	{
4135	  internal_a.o_sntdata = tdata_sec->target_index;
4136	  /* TODO: o_flags should be set to RS6K_AOUTHDR_TLS_LE
4137	     if there is at least one R_TLS_LE relocations.  */
4138	  internal_a.o_flags = 0;
4139#ifdef XCOFF64
4140	  internal_a.o_x64flags = 0;
4141#endif
4142	}
4143      else
4144	{
4145	  internal_a.o_sntdata = 0;
4146	  internal_a.o_flags = 0;
4147#ifdef XCOFF64
4148	  internal_a.o_x64flags = 0;
4149#endif
4150	}
4151      if (tbss_sec != NULL)
4152	  internal_a.o_sntbss = tbss_sec->target_index;
4153      else
4154	  internal_a.o_sntbss = 0;
4155
4156      toc = xcoff_data (abfd)->toc;
4157      internal_a.o_toc = toc;
4158      internal_a.o_sntoc = xcoff_data (abfd)->sntoc;
4159
4160      internal_a.o_modtype = xcoff_data (abfd)->modtype;
4161      if (xcoff_data (abfd)->cputype != -1)
4162	internal_a.o_cputype = xcoff_data (abfd)->cputype;
4163      else
4164	{
4165	  switch (bfd_get_arch (abfd))
4166	    {
4167	    case bfd_arch_rs6000:
4168	      internal_a.o_cputype = 4;
4169	      break;
4170	    case bfd_arch_powerpc:
4171	      if (bfd_get_mach (abfd) == bfd_mach_ppc)
4172		internal_a.o_cputype = 3;
4173	      else if (bfd_get_mach (abfd) == bfd_mach_ppc_620)
4174		internal_a.o_cputype = 2;
4175	      else
4176		internal_a.o_cputype = 1;
4177	      break;
4178	    default:
4179	      abort ();
4180	    }
4181	}
4182      internal_a.o_maxstack = xcoff_data (abfd)->maxstack;
4183      internal_a.o_maxdata = xcoff_data (abfd)->maxdata;
4184    }
4185#endif
4186
4187#ifdef COFF_WITH_PE
4188  {
4189    /* After object contents are finalized so we can compute a reasonable hash,
4190       but before header is written so we can update it to point to debug directory.  */
4191    struct pe_tdata *pe = pe_data (abfd);
4192
4193    if (pe->build_id.after_write_object_contents != NULL)
4194      (*pe->build_id.after_write_object_contents) (abfd);
4195  }
4196#endif
4197
4198  /* Now write header.  */
4199  if (bfd_seek (abfd, (file_ptr) 0, SEEK_SET) != 0)
4200    return false;
4201
4202  {
4203    char * buff;
4204    bfd_size_type amount = bfd_coff_filhsz (abfd);
4205
4206    buff = (char *) bfd_malloc (amount);
4207    if (buff == NULL)
4208      return false;
4209
4210    bfd_coff_swap_filehdr_out (abfd, & internal_f, buff);
4211    amount = bfd_bwrite (buff, amount, abfd);
4212
4213    free (buff);
4214
4215    if (amount != bfd_coff_filhsz (abfd))
4216      return false;
4217  }
4218
4219  if (abfd->flags & EXEC_P)
4220    {
4221      /* Note that peicode.h fills in a PEAOUTHDR, not an AOUTHDR.
4222	 include/coff/pe.h sets AOUTSZ == sizeof (PEAOUTHDR)).  */
4223      char * buff;
4224      bfd_size_type amount = bfd_coff_aoutsz (abfd);
4225
4226      buff = (char *) bfd_malloc (amount);
4227      if (buff == NULL)
4228	return false;
4229
4230      coff_swap_aouthdr_out (abfd, & internal_a, buff);
4231      amount = bfd_bwrite (buff, amount, abfd);
4232
4233      free (buff);
4234
4235      if (amount != bfd_coff_aoutsz (abfd))
4236	return false;
4237
4238#ifdef COFF_IMAGE_WITH_PE
4239      if (! coff_apply_checksum (abfd))
4240	return false;
4241#endif
4242    }
4243#ifdef RS6000COFF_C
4244#ifndef XCOFF64
4245  else
4246    {
4247      AOUTHDR buff;
4248      size_t size;
4249
4250      /* XCOFF32 seems to always write at least a small a.out header.  */
4251      coff_swap_aouthdr_out (abfd, & internal_a, & buff);
4252      if (xcoff_data (abfd)->full_aouthdr)
4253	size = bfd_coff_aoutsz (abfd);
4254      else
4255	size = SMALL_AOUTSZ;
4256      if (bfd_bwrite (& buff, (bfd_size_type) size, abfd) != size)
4257	return false;
4258    }
4259#endif
4260#endif
4261
4262  return true;
4263}
4264
4265static bool
4266coff_set_section_contents (bfd * abfd,
4267			   sec_ptr section,
4268			   const void * location,
4269			   file_ptr offset,
4270			   bfd_size_type count)
4271{
4272  if (! abfd->output_has_begun)	/* Set by bfd.c handler.  */
4273    {
4274      if (! coff_compute_section_file_positions (abfd))
4275	return false;
4276    }
4277
4278#if defined(_LIB) && !defined(TARG_AUX)
4279   /* The physical address field of a .lib section is used to hold the
4280      number of shared libraries in the section.  This code counts the
4281      number of sections being written, and increments the lma field
4282      with the number.
4283
4284      I have found no documentation on the contents of this section.
4285      Experimentation indicates that the section contains zero or more
4286      records, each of which has the following structure:
4287
4288      - a (four byte) word holding the length of this record, in words,
4289      - a word that always seems to be set to "2",
4290      - the path to a shared library, null-terminated and then padded
4291	to a whole word boundary.
4292
4293      bfd_assert calls have been added to alert if an attempt is made
4294      to write a section which doesn't follow these assumptions.  The
4295      code has been tested on ISC 4.1 by me, and on SCO by Robert Lipe
4296      <robertl@arnet.com> (Thanks!).
4297
4298      Gvran Uddeborg <gvran@uddeborg.pp.se>.  */
4299    if (strcmp (section->name, _LIB) == 0)
4300      {
4301	bfd_byte *rec, *recend;
4302
4303	rec = (bfd_byte *) location;
4304	recend = rec + count;
4305	while (recend - rec >= 4)
4306	  {
4307	    size_t len = bfd_get_32 (abfd, rec);
4308	    if (len == 0 || len > (size_t) (recend - rec) / 4)
4309	      break;
4310	    rec += len * 4;
4311	    ++section->lma;
4312	  }
4313
4314	BFD_ASSERT (rec == recend);
4315      }
4316#endif
4317
4318  /* Don't write out bss sections - one way to do this is to
4319       see if the filepos has not been set.  */
4320  if (section->filepos == 0)
4321    return true;
4322
4323  if (bfd_seek (abfd, section->filepos + offset, SEEK_SET) != 0)
4324    return false;
4325
4326  if (count == 0)
4327    return true;
4328
4329  return bfd_bwrite (location, count, abfd) == count;
4330}
4331
4332static void *
4333buy_and_read (bfd *abfd, file_ptr where,
4334	      bfd_size_type nmemb, bfd_size_type size)
4335{
4336  size_t amt;
4337
4338  if (_bfd_mul_overflow (nmemb, size, &amt))
4339    {
4340      bfd_set_error (bfd_error_file_too_big);
4341      return NULL;
4342    }
4343  if (bfd_seek (abfd, where, SEEK_SET) != 0)
4344    return NULL;
4345  return _bfd_malloc_and_read (abfd, amt, amt);
4346}
4347
4348/*
4349SUBSUBSECTION
4350	Reading linenumbers
4351
4352	Creating the linenumber table is done by reading in the entire
4353	coff linenumber table, and creating another table for internal use.
4354
4355	A coff linenumber table is structured so that each function
4356	is marked as having a line number of 0. Each line within the
4357	function is an offset from the first line in the function. The
4358	base of the line number information for the table is stored in
4359	the symbol associated with the function.
4360
4361	Note: The PE format uses line number 0 for a flag indicating a
4362	new source file.
4363
4364	The information is copied from the external to the internal
4365	table, and each symbol which marks a function is marked by
4366	pointing its...
4367
4368	How does this work ?
4369*/
4370
4371static int
4372coff_sort_func_alent (const void * arg1, const void * arg2)
4373{
4374  const alent *al1 = *(const alent **) arg1;
4375  const alent *al2 = *(const alent **) arg2;
4376  const coff_symbol_type *s1 = (const coff_symbol_type *) (al1->u.sym);
4377  const coff_symbol_type *s2 = (const coff_symbol_type *) (al2->u.sym);
4378
4379  if (s1 == NULL || s2 == NULL)
4380    return 0;
4381  if (s1->symbol.value < s2->symbol.value)
4382    return -1;
4383  else if (s1->symbol.value > s2->symbol.value)
4384    return 1;
4385
4386  return 0;
4387}
4388
4389static bool
4390coff_slurp_line_table (bfd *abfd, asection *asect)
4391{
4392  LINENO *native_lineno;
4393  alent *lineno_cache;
4394  unsigned int counter;
4395  alent *cache_ptr;
4396  bfd_vma prev_offset = 0;
4397  bool ordered = true;
4398  unsigned int nbr_func;
4399  LINENO *src;
4400  bool have_func;
4401  bool ret = true;
4402  size_t amt;
4403
4404  if (asect->lineno_count == 0)
4405    return true;
4406
4407  BFD_ASSERT (asect->lineno == NULL);
4408
4409  native_lineno = (LINENO *) buy_and_read (abfd, asect->line_filepos,
4410					   asect->lineno_count,
4411					   bfd_coff_linesz (abfd));
4412  if (native_lineno == NULL)
4413    {
4414      _bfd_error_handler
4415	(_("%pB: warning: line number table read failed"), abfd);
4416      return false;
4417    }
4418
4419  if (_bfd_mul_overflow (asect->lineno_count + 1, sizeof (alent), &amt))
4420    {
4421      bfd_set_error (bfd_error_file_too_big);
4422      free (native_lineno);
4423      return false;
4424    }
4425  lineno_cache = (alent *) bfd_alloc (abfd, amt);
4426  if (lineno_cache == NULL)
4427    {
4428      free (native_lineno);
4429      return false;
4430    }
4431
4432  cache_ptr = lineno_cache;
4433  asect->lineno = lineno_cache;
4434  src = native_lineno;
4435  nbr_func = 0;
4436  have_func = false;
4437
4438  for (counter = 0; counter < asect->lineno_count; counter++, src++)
4439    {
4440      struct internal_lineno dst;
4441
4442      bfd_coff_swap_lineno_in (abfd, src, &dst);
4443      cache_ptr->line_number = dst.l_lnno;
4444      /* Appease memory checkers that get all excited about
4445	 uninitialised memory when copying alents if u.offset is
4446	 larger than u.sym.  (64-bit BFD on 32-bit host.)  */
4447      memset (&cache_ptr->u, 0, sizeof (cache_ptr->u));
4448
4449      if (cache_ptr->line_number == 0)
4450	{
4451	  combined_entry_type * ent;
4452	  unsigned long symndx;
4453	  coff_symbol_type *sym;
4454
4455	  have_func = false;
4456	  symndx = dst.l_addr.l_symndx;
4457	  if (symndx >= obj_raw_syment_count (abfd))
4458	    {
4459	      _bfd_error_handler
4460		/* xgettext:c-format */
4461		(_("%pB: warning: illegal symbol index 0x%lx in line number entry %d"),
4462		 abfd, symndx, counter);
4463	      cache_ptr->line_number = -1;
4464	      ret = false;
4465	      continue;
4466	    }
4467
4468	  ent = obj_raw_syments (abfd) + symndx;
4469	  /* FIXME: We should not be casting between ints and
4470	     pointers like this.  */
4471	  if (! ent->is_sym)
4472	    {
4473	      _bfd_error_handler
4474		/* xgettext:c-format */
4475		(_("%pB: warning: illegal symbol index 0x%lx in line number entry %d"),
4476		 abfd, symndx, counter);
4477	      cache_ptr->line_number = -1;
4478	      ret = false;
4479	      continue;
4480	    }
4481	  sym = (coff_symbol_type *) (ent->u.syment._n._n_n._n_zeroes);
4482
4483	  /* PR 17512 file: 078-10659-0.004  */
4484	  if (sym < obj_symbols (abfd)
4485	      || sym >= obj_symbols (abfd) + bfd_get_symcount (abfd))
4486	    {
4487	      _bfd_error_handler
4488		/* xgettext:c-format */
4489		(_("%pB: warning: illegal symbol in line number entry %d"),
4490		 abfd, counter);
4491	      cache_ptr->line_number = -1;
4492	      ret = false;
4493	      continue;
4494	    }
4495
4496	  have_func = true;
4497	  nbr_func++;
4498	  cache_ptr->u.sym = (asymbol *) sym;
4499	  if (sym->lineno != NULL)
4500	    _bfd_error_handler
4501	      /* xgettext:c-format */
4502	      (_("%pB: warning: duplicate line number information for `%s'"),
4503	       abfd, bfd_asymbol_name (&sym->symbol));
4504
4505	  sym->lineno = cache_ptr;
4506	  if (sym->symbol.value < prev_offset)
4507	    ordered = false;
4508	  prev_offset = sym->symbol.value;
4509	}
4510      else if (!have_func)
4511	/* Drop line information that has no associated function.
4512	   PR 17521: file: 078-10659-0.004.  */
4513	continue;
4514      else
4515	cache_ptr->u.offset = dst.l_addr.l_paddr - bfd_section_vma (asect);
4516      cache_ptr++;
4517    }
4518
4519  asect->lineno_count = cache_ptr - lineno_cache;
4520  memset (cache_ptr, 0, sizeof (*cache_ptr));
4521  free (native_lineno);
4522
4523  /* On some systems (eg AIX5.3) the lineno table may not be sorted.  */
4524  if (!ordered)
4525    {
4526      /* Sort the table.  */
4527      alent **func_table;
4528      alent *n_lineno_cache;
4529
4530      /* Create a table of functions.  */
4531      if (_bfd_mul_overflow (nbr_func, sizeof (alent *), &amt))
4532	{
4533	  bfd_set_error (bfd_error_file_too_big);
4534	  ret = false;
4535	}
4536      else if ((func_table = (alent **) bfd_alloc (abfd, amt)) != NULL)
4537	{
4538	  alent **p = func_table;
4539	  unsigned int i;
4540
4541	  for (i = 0; i < asect->lineno_count; i++)
4542	    if (lineno_cache[i].line_number == 0)
4543	      *p++ = &lineno_cache[i];
4544
4545	  BFD_ASSERT ((unsigned int) (p - func_table) == nbr_func);
4546
4547	  /* Sort by functions.  */
4548	  qsort (func_table, nbr_func, sizeof (alent *), coff_sort_func_alent);
4549
4550	  /* Create the new sorted table.  */
4551	  if (_bfd_mul_overflow (asect->lineno_count, sizeof (alent), &amt))
4552	    {
4553	      bfd_set_error (bfd_error_file_too_big);
4554	      ret = false;
4555	    }
4556	  else if ((n_lineno_cache = (alent *) bfd_alloc (abfd, amt)) != NULL)
4557	    {
4558	      alent *n_cache_ptr = n_lineno_cache;
4559
4560	      for (i = 0; i < nbr_func; i++)
4561		{
4562		  coff_symbol_type *sym;
4563		  alent *old_ptr = func_table[i];
4564
4565		  /* Update the function entry.  */
4566		  sym = (coff_symbol_type *) old_ptr->u.sym;
4567		  /* PR binutils/17512: Point the lineno to where
4568		     this entry will be after the memcpy below.  */
4569		  sym->lineno = lineno_cache + (n_cache_ptr - n_lineno_cache);
4570		  /* Copy the function and line number entries.  */
4571		  do
4572		    *n_cache_ptr++ = *old_ptr++;
4573		  while (old_ptr->line_number != 0);
4574		}
4575
4576	      memcpy (lineno_cache, n_lineno_cache,
4577		      asect->lineno_count * sizeof (alent));
4578	    }
4579	  else
4580	    ret = false;
4581	  bfd_release (abfd, func_table);
4582	}
4583      else
4584	ret = false;
4585    }
4586
4587  return ret;
4588}
4589
4590/* Slurp in the symbol table, converting it to generic form.  Note
4591   that if coff_relocate_section is defined, the linker will read
4592   symbols via coff_link_add_symbols, rather than via this routine.  */
4593
4594static bool
4595coff_slurp_symbol_table (bfd * abfd)
4596{
4597  combined_entry_type *native_symbols;
4598  coff_symbol_type *cached_area;
4599  unsigned int *table_ptr;
4600  unsigned int number_of_symbols = 0;
4601  bool ret = true;
4602  size_t amt;
4603
4604  if (obj_symbols (abfd))
4605    return true;
4606
4607  /* Read in the symbol table.  */
4608  if ((native_symbols = coff_get_normalized_symtab (abfd)) == NULL)
4609    return false;
4610
4611  /* Allocate enough room for all the symbols in cached form.  */
4612  if (_bfd_mul_overflow (obj_raw_syment_count (abfd),
4613			 sizeof (*cached_area), &amt))
4614    {
4615      bfd_set_error (bfd_error_file_too_big);
4616      return false;
4617    }
4618  cached_area = (coff_symbol_type *) bfd_alloc (abfd, amt);
4619  if (cached_area == NULL)
4620    return false;
4621
4622  if (_bfd_mul_overflow (obj_raw_syment_count (abfd),
4623			 sizeof (*table_ptr), &amt))
4624    {
4625      bfd_set_error (bfd_error_file_too_big);
4626      return false;
4627    }
4628  table_ptr = (unsigned int *) bfd_zalloc (abfd, amt);
4629  if (table_ptr == NULL)
4630    return false;
4631  else
4632    {
4633      coff_symbol_type *dst = cached_area;
4634      unsigned int last_native_index = obj_raw_syment_count (abfd);
4635      unsigned int this_index = 0;
4636
4637      while (this_index < last_native_index)
4638	{
4639	  combined_entry_type *src = native_symbols + this_index;
4640	  table_ptr[this_index] = number_of_symbols;
4641
4642	  dst->symbol.the_bfd = abfd;
4643	  BFD_ASSERT (src->is_sym);
4644	  dst->symbol.name = (char *) (src->u.syment._n._n_n._n_offset);
4645	  /* We use the native name field to point to the cached field.  */
4646	  src->u.syment._n._n_n._n_zeroes = (uintptr_t) dst;
4647	  dst->symbol.section = coff_section_from_bfd_index (abfd,
4648						     src->u.syment.n_scnum);
4649	  dst->symbol.flags = 0;
4650	  /* PR 17512: file: 079-7098-0.001:0.1.  */
4651	  dst->symbol.value = 0;
4652	  dst->done_lineno = false;
4653
4654	  switch (src->u.syment.n_sclass)
4655	    {
4656	    case C_EXT:
4657	    case C_WEAKEXT:
4658#if defined ARM
4659	    case C_THUMBEXT:
4660	    case C_THUMBEXTFUNC:
4661#endif
4662#ifdef RS6000COFF_C
4663	    case C_HIDEXT:
4664#if ! defined _AIX52 && ! defined AIX_WEAK_SUPPORT
4665	    case C_AIX_WEAKEXT:
4666#endif
4667#endif
4668#ifdef C_SYSTEM
4669	    case C_SYSTEM:	/* System Wide variable.  */
4670#endif
4671#ifdef COFF_WITH_PE
4672	    /* In PE, 0x68 (104) denotes a section symbol.  */
4673	    case C_SECTION:
4674	    /* In PE, 0x69 (105) denotes a weak external symbol.  */
4675	    case C_NT_WEAK:
4676#endif
4677	      switch (coff_classify_symbol (abfd, &src->u.syment))
4678		{
4679		case COFF_SYMBOL_GLOBAL:
4680		  dst->symbol.flags = BSF_EXPORT | BSF_GLOBAL;
4681#if defined COFF_WITH_PE
4682		  /* PE sets the symbol to a value relative to the
4683		     start of the section.  */
4684		  dst->symbol.value = src->u.syment.n_value;
4685#else
4686		  dst->symbol.value = (src->u.syment.n_value
4687				       - dst->symbol.section->vma);
4688#endif
4689		  if (ISFCN ((src->u.syment.n_type)))
4690		    /* A function ext does not go at the end of a
4691		       file.  */
4692		    dst->symbol.flags |= BSF_NOT_AT_END | BSF_FUNCTION;
4693		  break;
4694
4695		case COFF_SYMBOL_COMMON:
4696		  dst->symbol.section = bfd_com_section_ptr;
4697		  dst->symbol.value = src->u.syment.n_value;
4698		  break;
4699
4700		case COFF_SYMBOL_UNDEFINED:
4701		  dst->symbol.section = bfd_und_section_ptr;
4702		  dst->symbol.value = 0;
4703		  break;
4704
4705		case COFF_SYMBOL_PE_SECTION:
4706		  dst->symbol.flags |= BSF_EXPORT | BSF_SECTION_SYM;
4707		  dst->symbol.value = 0;
4708		  break;
4709
4710		case COFF_SYMBOL_LOCAL:
4711		  dst->symbol.flags = BSF_LOCAL;
4712#if defined COFF_WITH_PE
4713		  /* PE sets the symbol to a value relative to the
4714		     start of the section.  */
4715		  dst->symbol.value = src->u.syment.n_value;
4716#else
4717		  dst->symbol.value = (src->u.syment.n_value
4718				       - dst->symbol.section->vma);
4719#endif
4720		  if (ISFCN ((src->u.syment.n_type)))
4721		    dst->symbol.flags |= BSF_NOT_AT_END | BSF_FUNCTION;
4722		  break;
4723		}
4724
4725#ifdef RS6000COFF_C
4726	      /* A symbol with a csect entry should not go at the end.  */
4727	      if (src->u.syment.n_numaux > 0)
4728		dst->symbol.flags |= BSF_NOT_AT_END;
4729#endif
4730
4731#ifdef COFF_WITH_PE
4732	      if (src->u.syment.n_sclass == C_NT_WEAK)
4733		dst->symbol.flags |= BSF_WEAK;
4734
4735	      if (src->u.syment.n_sclass == C_SECTION
4736		  && src->u.syment.n_scnum > 0)
4737		dst->symbol.flags = BSF_LOCAL;
4738#endif
4739	      if (src->u.syment.n_sclass == C_WEAKEXT
4740#ifdef RS6000COFF_C
4741		  || src->u.syment.n_sclass == C_AIX_WEAKEXT
4742#endif
4743		  )
4744		dst->symbol.flags |= BSF_WEAK;
4745
4746	      break;
4747
4748	    case C_STAT:	 /* Static.  */
4749#if defined ARM
4750	    case C_THUMBSTAT:    /* Thumb static.  */
4751	    case C_THUMBLABEL:   /* Thumb label.  */
4752	    case C_THUMBSTATFUNC:/* Thumb static function.  */
4753#endif
4754#ifdef RS6000COFF_C
4755	    case C_DWARF:	 /* A label in a dwarf section.  */
4756	    case C_INFO:	 /* A label in a comment section.  */
4757#endif
4758	    case C_LABEL:	 /* Label.  */
4759	      if (src->u.syment.n_scnum == N_DEBUG)
4760		dst->symbol.flags = BSF_DEBUGGING;
4761	      else
4762		dst->symbol.flags = BSF_LOCAL;
4763
4764	      /* Base the value as an index from the base of the
4765		 section, if there is one.  */
4766	      if (dst->symbol.section)
4767		{
4768#if defined COFF_WITH_PE
4769		  /* PE sets the symbol to a value relative to the
4770		     start of the section.  */
4771		  dst->symbol.value = src->u.syment.n_value;
4772#else
4773		  dst->symbol.value = (src->u.syment.n_value
4774				       - dst->symbol.section->vma);
4775#endif
4776		}
4777	      else
4778		dst->symbol.value = src->u.syment.n_value;
4779	      break;
4780
4781	    case C_FILE:	/* File name.  */
4782	      dst->symbol.flags = BSF_FILE;
4783	      /* Fall through.  */
4784	    case C_MOS:		/* Member of structure.  */
4785	    case C_EOS:		/* End of structure.  */
4786	    case C_REGPARM:	/* Register parameter.  */
4787	    case C_REG:		/* register variable.  */
4788	      /* C_AUTOARG conflicts with TI COFF C_UEXT.  */
4789	    case C_TPDEF:	/* Type definition.  */
4790	    case C_ARG:
4791	    case C_AUTO:	/* Automatic variable.  */
4792	    case C_FIELD:	/* Bit field.  */
4793	    case C_ENTAG:	/* Enumeration tag.  */
4794	    case C_MOE:		/* Member of enumeration.  */
4795	    case C_MOU:		/* Member of union.  */
4796	    case C_UNTAG:	/* Union tag.  */
4797	    case C_STRTAG:	/* Structure tag.  */
4798#ifdef RS6000COFF_C
4799	    case C_GSYM:
4800	    case C_LSYM:
4801	    case C_PSYM:
4802	    case C_RSYM:
4803	    case C_RPSYM:
4804	    case C_STSYM:
4805	    case C_TCSYM:
4806	    case C_BCOMM:
4807	    case C_ECOML:
4808	    case C_ECOMM:
4809	    case C_DECL:
4810	    case C_ENTRY:
4811	    case C_FUN:
4812	    case C_ESTAT:
4813#endif
4814	      dst->symbol.flags |= BSF_DEBUGGING;
4815	      dst->symbol.value = (src->u.syment.n_value);
4816	      break;
4817
4818#ifdef RS6000COFF_C
4819	    case C_BINCL:	/* Beginning of include file.  */
4820	    case C_EINCL:	/* Ending of include file.  */
4821	      /* The value is actually a pointer into the line numbers
4822		 of the file.  We locate the line number entry, and
4823		 set the section to the section which contains it, and
4824		 the value to the index in that section.  */
4825	      {
4826		asection *sec;
4827
4828		dst->symbol.flags = BSF_DEBUGGING;
4829		for (sec = abfd->sections; sec != NULL; sec = sec->next)
4830		  if (sec->line_filepos <= (file_ptr) src->u.syment.n_value
4831		      && ((file_ptr) (sec->line_filepos
4832				      + sec->lineno_count * bfd_coff_linesz (abfd))
4833			  > (file_ptr) src->u.syment.n_value))
4834		    break;
4835		if (sec == NULL)
4836		  dst->symbol.value = 0;
4837		else
4838		  {
4839		    dst->symbol.section = sec;
4840		    dst->symbol.value = ((src->u.syment.n_value
4841					  - sec->line_filepos)
4842					 / bfd_coff_linesz (abfd));
4843		    src->fix_line = 1;
4844		  }
4845	      }
4846	      break;
4847
4848	    case C_BSTAT:
4849	      dst->symbol.flags = BSF_DEBUGGING;
4850
4851	      /* The value is actually a symbol index.  Save a pointer
4852		 to the symbol instead of the index.  FIXME: This
4853		 should use a union.  */
4854	      src->u.syment.n_value
4855		= (uintptr_t) (native_symbols + src->u.syment.n_value);
4856	      dst->symbol.value = src->u.syment.n_value;
4857	      src->fix_value = 1;
4858	      break;
4859#endif
4860
4861	    case C_BLOCK:	/* ".bb" or ".eb".  */
4862	    case C_FCN:		/* ".bf" or ".ef" (or PE ".lf").  */
4863	    case C_EFCN:	/* Physical end of function.  */
4864#if defined COFF_WITH_PE
4865	      /* PE sets the symbol to a value relative to the start
4866		 of the section.  */
4867	      dst->symbol.value = src->u.syment.n_value;
4868	      if (strcmp (dst->symbol.name, ".bf") != 0)
4869		{
4870		  /* PE uses funny values for .ef and .lf; don't
4871		     relocate them.  */
4872		  dst->symbol.flags = BSF_DEBUGGING;
4873		}
4874	      else
4875		dst->symbol.flags = BSF_DEBUGGING | BSF_DEBUGGING_RELOC;
4876#else
4877	      /* Base the value as an index from the base of the
4878		 section.  */
4879	      dst->symbol.flags = BSF_LOCAL;
4880	      dst->symbol.value = (src->u.syment.n_value
4881				   - dst->symbol.section->vma);
4882#endif
4883	      break;
4884
4885	    case C_STATLAB:	/* Static load time label.  */
4886	      dst->symbol.value = src->u.syment.n_value;
4887	      dst->symbol.flags = BSF_GLOBAL;
4888	      break;
4889
4890	    case C_NULL:
4891	      /* PE DLLs sometimes have zeroed out symbols for some
4892		 reason.  Just ignore them without a warning.  */
4893	      if (src->u.syment.n_type == 0
4894		  && src->u.syment.n_value == 0
4895		  && src->u.syment.n_scnum == 0)
4896		break;
4897#ifdef RS6000COFF_C
4898	      /* XCOFF specific: deleted entry.  */
4899	      if (src->u.syment.n_value == C_NULL_VALUE)
4900		break;
4901#endif
4902	      /* Fall through.  */
4903	    case C_EXTDEF:	/* External definition.  */
4904	    case C_ULABEL:	/* Undefined label.  */
4905	    case C_USTATIC:	/* Undefined static.  */
4906#ifndef COFF_WITH_PE
4907	    /* C_LINE in regular coff is 0x68.  NT has taken over this storage
4908	       class to represent a section symbol.  */
4909	    case C_LINE:	/* line # reformatted as symbol table entry.  */
4910	      /* NT uses 0x67 for a weak symbol, not C_ALIAS.  */
4911	    case C_ALIAS:	/* Duplicate tag.  */
4912#endif
4913	      /* New storage classes for TI COFF.  */
4914#ifdef TICOFF
4915	    case C_UEXT:	/* Tentative external definition.  */
4916#endif
4917	    case C_EXTLAB:	/* External load time label.  */
4918	    default:
4919	      _bfd_error_handler
4920		/* xgettext:c-format */
4921		(_("%pB: unrecognized storage class %d for %s symbol `%s'"),
4922		 abfd, src->u.syment.n_sclass,
4923		 dst->symbol.section->name, dst->symbol.name);
4924	      ret = false;
4925	      /* Fall through.  */
4926	    case C_HIDDEN:	/* Ext symbol in dmert public lib.  */
4927	      /* PR 20722: These symbols can also be generated by
4928		 building DLLs with --gc-sections enabled.  */
4929	      dst->symbol.flags = BSF_DEBUGGING;
4930	      dst->symbol.value = (src->u.syment.n_value);
4931	      break;
4932	    }
4933
4934	  dst->native = src;
4935	  dst->symbol.udata.i = 0;
4936	  dst->lineno = NULL;
4937
4938	  this_index += (src->u.syment.n_numaux) + 1;
4939	  dst++;
4940	  number_of_symbols++;
4941	}
4942    }
4943
4944  obj_symbols (abfd) = cached_area;
4945  obj_raw_syments (abfd) = native_symbols;
4946
4947  abfd->symcount = number_of_symbols;
4948  obj_convert (abfd) = table_ptr;
4949  /* Slurp the line tables for each section too.  */
4950  {
4951    asection *p;
4952
4953    p = abfd->sections;
4954    while (p)
4955      {
4956	if (! coff_slurp_line_table (abfd, p))
4957	  return false;
4958	p = p->next;
4959      }
4960  }
4961
4962  return ret;
4963}
4964
4965/* Classify a COFF symbol.  A couple of targets have globally visible
4966   symbols which are not class C_EXT, and this handles those.  It also
4967   recognizes some special PE cases.  */
4968
4969static enum coff_symbol_classification
4970coff_classify_symbol (bfd *abfd,
4971		      struct internal_syment *syment)
4972{
4973  /* FIXME: This partially duplicates the switch in
4974     coff_slurp_symbol_table.  */
4975  switch (syment->n_sclass)
4976    {
4977    case C_EXT:
4978    case C_WEAKEXT:
4979#ifdef ARM
4980    case C_THUMBEXT:
4981    case C_THUMBEXTFUNC:
4982#endif
4983#ifdef RS6000COFF_C
4984    case C_HIDEXT:
4985#if ! defined _AIX52 && ! defined AIX_WEAK_SUPPORT
4986    case C_AIX_WEAKEXT:
4987#endif
4988#endif
4989#ifdef C_SYSTEM
4990    case C_SYSTEM:
4991#endif
4992#ifdef COFF_WITH_PE
4993    case C_NT_WEAK:
4994#endif
4995      if (syment->n_scnum == 0)
4996	{
4997	  if (syment->n_value == 0)
4998	    return COFF_SYMBOL_UNDEFINED;
4999	  else
5000	    return COFF_SYMBOL_COMMON;
5001	}
5002#ifdef RS6000COFF_C
5003      if (syment->n_sclass == C_HIDEXT)
5004	return COFF_SYMBOL_LOCAL;
5005#endif
5006      return COFF_SYMBOL_GLOBAL;
5007
5008    default:
5009      break;
5010    }
5011
5012#ifdef COFF_WITH_PE
5013  if (syment->n_sclass == C_STAT)
5014    {
5015      if (syment->n_scnum == 0)
5016	/* The Microsoft compiler sometimes generates these if a
5017	   small static function is inlined every time it is used.
5018	   The function is discarded, but the symbol table entry
5019	   remains.  */
5020	return COFF_SYMBOL_LOCAL;
5021
5022#ifdef STRICT_PE_FORMAT
5023      /* This is correct for Microsoft generated objects, but it
5024	 breaks gas generated objects.  */
5025      if (syment->n_value == 0)
5026	{
5027	  asection *sec;
5028	  char * name;
5029	  char buf[SYMNMLEN + 1];
5030
5031	  name = _bfd_coff_internal_syment_name (abfd, syment, buf)
5032	  sec = coff_section_from_bfd_index (abfd, syment->n_scnum);
5033	  if (sec != NULL && name != NULL
5034	      && (strcmp (bfd_section_name (sec), name) == 0))
5035	    return COFF_SYMBOL_PE_SECTION;
5036	}
5037#endif
5038
5039      return COFF_SYMBOL_LOCAL;
5040    }
5041
5042  if (syment->n_sclass == C_SECTION)
5043    {
5044      /* In some cases in a DLL generated by the Microsoft linker, the
5045	 n_value field will contain garbage.  FIXME: This should
5046	 probably be handled by the swapping function instead.  */
5047      syment->n_value = 0;
5048      if (syment->n_scnum == 0)
5049	return COFF_SYMBOL_UNDEFINED;
5050      return COFF_SYMBOL_PE_SECTION;
5051    }
5052#endif /* COFF_WITH_PE */
5053
5054  /* If it is not a global symbol, we presume it is a local symbol.  */
5055  if (syment->n_scnum == 0)
5056    {
5057      char buf[SYMNMLEN + 1];
5058
5059      _bfd_error_handler
5060	/* xgettext:c-format */
5061	(_("warning: %pB: local symbol `%s' has no section"),
5062	 abfd, _bfd_coff_internal_syment_name (abfd, syment, buf));
5063    }
5064
5065  return COFF_SYMBOL_LOCAL;
5066}
5067
5068/*
5069SUBSUBSECTION
5070	Reading relocations
5071
5072	Coff relocations are easily transformed into the internal BFD form
5073	(@code{arelent}).
5074
5075	Reading a coff relocation table is done in the following stages:
5076
5077	o Read the entire coff relocation table into memory.
5078
5079	o Process each relocation in turn; first swap it from the
5080	external to the internal form.
5081
5082	o Turn the symbol referenced in the relocation's symbol index
5083	into a pointer into the canonical symbol table.
5084	This table is the same as the one returned by a call to
5085	@code{bfd_canonicalize_symtab}. The back end will call that
5086	routine and save the result if a canonicalization hasn't been done.
5087
5088	o The reloc index is turned into a pointer to a howto
5089	structure, in a back end specific way. For instance, the 386
5090	uses the @code{r_type} to directly produce an index
5091	into a howto table vector.
5092*/
5093
5094#ifndef CALC_ADDEND
5095#define CALC_ADDEND(abfd, ptr, reloc, cache_ptr)		\
5096  {								\
5097    coff_symbol_type *coffsym = NULL;				\
5098								\
5099    if (ptr && bfd_asymbol_bfd (ptr) != abfd)			\
5100      coffsym = (obj_symbols (abfd)				\
5101		 + (cache_ptr->sym_ptr_ptr - symbols));		\
5102    else if (ptr)						\
5103      coffsym = coff_symbol_from (ptr);				\
5104    if (coffsym != NULL						\
5105	&& coffsym->native->is_sym				\
5106	&& coffsym->native->u.syment.n_scnum == 0)		\
5107      cache_ptr->addend = 0;					\
5108    else if (ptr && bfd_asymbol_bfd (ptr) == abfd		\
5109	     && ptr->section != NULL)				\
5110      cache_ptr->addend = - (ptr->section->vma + ptr->value);	\
5111    else							\
5112      cache_ptr->addend = 0;					\
5113  }
5114#endif
5115
5116static bool
5117coff_slurp_reloc_table (bfd * abfd, sec_ptr asect, asymbol ** symbols)
5118{
5119  bfd_byte *native_relocs;
5120  arelent *reloc_cache;
5121  arelent *cache_ptr;
5122  unsigned int idx;
5123  size_t amt;
5124
5125  if (asect->relocation)
5126    return true;
5127  if (asect->reloc_count == 0)
5128    return true;
5129  if (asect->flags & SEC_CONSTRUCTOR)
5130    return true;
5131  if (!coff_slurp_symbol_table (abfd))
5132    return false;
5133
5134  native_relocs = (bfd_byte *) buy_and_read (abfd, asect->rel_filepos,
5135					     asect->reloc_count,
5136					     bfd_coff_relsz (abfd));
5137  if (native_relocs == NULL)
5138    return false;
5139
5140  if (_bfd_mul_overflow (asect->reloc_count, sizeof (arelent), &amt))
5141    {
5142      bfd_set_error (bfd_error_file_too_big);
5143      return false;
5144    }
5145  reloc_cache = (arelent *) bfd_alloc (abfd, amt);
5146  if (reloc_cache == NULL)
5147    {
5148      free (native_relocs);
5149      return false;
5150    }
5151
5152  for (idx = 0; idx < asect->reloc_count; idx++)
5153    {
5154      struct internal_reloc dst;
5155      void *src;
5156#ifndef RELOC_PROCESSING
5157      asymbol *ptr;
5158#endif
5159
5160      cache_ptr = reloc_cache + idx;
5161      src = native_relocs + idx * (size_t) bfd_coff_relsz (abfd);
5162
5163      dst.r_offset = 0;
5164      bfd_coff_swap_reloc_in (abfd, src, &dst);
5165
5166#ifdef RELOC_PROCESSING
5167      RELOC_PROCESSING (cache_ptr, &dst, symbols, abfd, asect);
5168#else
5169      cache_ptr->address = dst.r_vaddr;
5170
5171      if (dst.r_symndx != -1 && symbols != NULL)
5172	{
5173	  if (dst.r_symndx < 0 || dst.r_symndx >= obj_conv_table_size (abfd))
5174	    {
5175	      _bfd_error_handler
5176		/* xgettext:c-format */
5177		(_("%pB: warning: illegal symbol index %ld in relocs"),
5178		 abfd, dst.r_symndx);
5179	      cache_ptr->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
5180	      ptr = NULL;
5181	    }
5182	  else
5183	    {
5184	      cache_ptr->sym_ptr_ptr = (symbols
5185					+ obj_convert (abfd)[dst.r_symndx]);
5186	      ptr = *(cache_ptr->sym_ptr_ptr);
5187	    }
5188	}
5189      else
5190	{
5191	  cache_ptr->sym_ptr_ptr = bfd_abs_section_ptr->symbol_ptr_ptr;
5192	  ptr = NULL;
5193	}
5194
5195      /* The symbols definitions that we have read in have been
5196	 relocated as if their sections started at 0. But the offsets
5197	 refering to the symbols in the raw data have not been
5198	 modified, so we have to have a negative addend to compensate.
5199
5200	 Note that symbols which used to be common must be left alone.  */
5201
5202      /* Calculate any reloc addend by looking at the symbol.  */
5203      CALC_ADDEND (abfd, ptr, dst, cache_ptr);
5204      (void) ptr;
5205
5206      cache_ptr->address -= asect->vma;
5207      /* !! cache_ptr->section = NULL;*/
5208
5209      /* Fill in the cache_ptr->howto field from dst.r_type.  */
5210      RTYPE2HOWTO (cache_ptr, &dst);
5211#endif	/* RELOC_PROCESSING */
5212
5213      if (cache_ptr->howto == NULL)
5214	{
5215	  _bfd_error_handler
5216	    /* xgettext:c-format */
5217	    (_("%pB: illegal relocation type %d at address %#" PRIx64),
5218	     abfd, dst.r_type, (uint64_t) dst.r_vaddr);
5219	  bfd_set_error (bfd_error_bad_value);
5220	  free (native_relocs);
5221	  return false;
5222	}
5223    }
5224
5225  free (native_relocs);
5226  asect->relocation = reloc_cache;
5227  return true;
5228}
5229
5230#ifndef coff_rtype_to_howto
5231#ifdef RTYPE2HOWTO
5232
5233/* Get the howto structure for a reloc.  This is only used if the file
5234   including this one defines coff_relocate_section to be
5235   _bfd_coff_generic_relocate_section, so it is OK if it does not
5236   always work.  It is the responsibility of the including file to
5237   make sure it is reasonable if it is needed.  */
5238
5239static reloc_howto_type *
5240coff_rtype_to_howto (bfd *abfd ATTRIBUTE_UNUSED,
5241		     asection *sec ATTRIBUTE_UNUSED,
5242		     struct internal_reloc *rel ATTRIBUTE_UNUSED,
5243		     struct coff_link_hash_entry *h ATTRIBUTE_UNUSED,
5244		     struct internal_syment *sym ATTRIBUTE_UNUSED,
5245		     bfd_vma *addendp ATTRIBUTE_UNUSED)
5246{
5247  arelent genrel;
5248
5249  genrel.howto = NULL;
5250  RTYPE2HOWTO (&genrel, rel);
5251  return genrel.howto;
5252}
5253
5254#else /* ! defined (RTYPE2HOWTO) */
5255
5256#define coff_rtype_to_howto NULL
5257
5258#endif /* ! defined (RTYPE2HOWTO) */
5259#endif /* ! defined (coff_rtype_to_howto) */
5260
5261/* This is stupid.  This function should be a boolean predicate.  */
5262
5263static long
5264coff_canonicalize_reloc (bfd * abfd,
5265			 sec_ptr section,
5266			 arelent ** relptr,
5267			 asymbol ** symbols)
5268{
5269  arelent *tblptr = section->relocation;
5270  unsigned int count = 0;
5271
5272  if (section->flags & SEC_CONSTRUCTOR)
5273    {
5274      /* This section has relocs made up by us, they are not in the
5275	 file, so take them out of their chain and place them into
5276	 the data area provided.  */
5277      arelent_chain *chain = section->constructor_chain;
5278
5279      for (count = 0; count < section->reloc_count; count++)
5280	{
5281	  *relptr++ = &chain->relent;
5282	  chain = chain->next;
5283	}
5284    }
5285  else
5286    {
5287      if (! coff_slurp_reloc_table (abfd, section, symbols))
5288	return -1;
5289
5290      tblptr = section->relocation;
5291
5292      for (; count++ < section->reloc_count;)
5293	*relptr++ = tblptr++;
5294    }
5295  *relptr = 0;
5296  return section->reloc_count;
5297}
5298
5299#ifndef coff_set_reloc
5300#define coff_set_reloc _bfd_generic_set_reloc
5301#endif
5302
5303#ifndef coff_reloc16_estimate
5304#define coff_reloc16_estimate dummy_reloc16_estimate
5305
5306static int
5307dummy_reloc16_estimate (bfd *abfd ATTRIBUTE_UNUSED,
5308			asection *input_section ATTRIBUTE_UNUSED,
5309			arelent *reloc ATTRIBUTE_UNUSED,
5310			unsigned int shrink ATTRIBUTE_UNUSED,
5311			struct bfd_link_info *link_info ATTRIBUTE_UNUSED)
5312{
5313  abort ();
5314  return 0;
5315}
5316
5317#endif
5318
5319#ifndef coff_reloc16_extra_cases
5320
5321#define coff_reloc16_extra_cases dummy_reloc16_extra_cases
5322
5323/* This works even if abort is not declared in any header file.  */
5324
5325static void
5326dummy_reloc16_extra_cases (bfd *abfd ATTRIBUTE_UNUSED,
5327			   struct bfd_link_info *link_info ATTRIBUTE_UNUSED,
5328			   struct bfd_link_order *link_order ATTRIBUTE_UNUSED,
5329			   arelent *reloc ATTRIBUTE_UNUSED,
5330			   bfd_byte *data ATTRIBUTE_UNUSED,
5331			   unsigned int *src_ptr ATTRIBUTE_UNUSED,
5332			   unsigned int *dst_ptr ATTRIBUTE_UNUSED)
5333{
5334  abort ();
5335}
5336#endif
5337
5338/* If coff_relocate_section is defined, we can use the optimized COFF
5339   backend linker.  Otherwise we must continue to use the old linker.  */
5340
5341#ifdef coff_relocate_section
5342
5343#ifndef coff_bfd_link_hash_table_create
5344#define coff_bfd_link_hash_table_create _bfd_coff_link_hash_table_create
5345#endif
5346#ifndef coff_bfd_link_add_symbols
5347#define coff_bfd_link_add_symbols _bfd_coff_link_add_symbols
5348#endif
5349#ifndef coff_bfd_final_link
5350#define coff_bfd_final_link _bfd_coff_final_link
5351#endif
5352
5353#else /* ! defined (coff_relocate_section) */
5354
5355#define coff_relocate_section NULL
5356#ifndef coff_bfd_link_hash_table_create
5357#define coff_bfd_link_hash_table_create _bfd_generic_link_hash_table_create
5358#endif
5359#ifndef coff_bfd_link_add_symbols
5360#define coff_bfd_link_add_symbols _bfd_generic_link_add_symbols
5361#endif
5362#define coff_bfd_final_link _bfd_generic_final_link
5363
5364#endif /* ! defined (coff_relocate_section) */
5365
5366#define coff_bfd_link_just_syms      _bfd_generic_link_just_syms
5367#define coff_bfd_copy_link_hash_symbol_type \
5368  _bfd_generic_copy_link_hash_symbol_type
5369#define coff_bfd_link_split_section  _bfd_generic_link_split_section
5370
5371#define coff_bfd_link_check_relocs   _bfd_generic_link_check_relocs
5372
5373#ifndef coff_start_final_link
5374#define coff_start_final_link NULL
5375#endif
5376
5377#ifndef coff_adjust_symndx
5378#define coff_adjust_symndx NULL
5379#endif
5380
5381#ifndef coff_link_add_one_symbol
5382#define coff_link_add_one_symbol _bfd_generic_link_add_one_symbol
5383#endif
5384
5385#ifndef coff_link_output_has_begun
5386
5387static bool
5388coff_link_output_has_begun (bfd * abfd,
5389			    struct coff_final_link_info * info ATTRIBUTE_UNUSED)
5390{
5391  return abfd->output_has_begun;
5392}
5393#endif
5394
5395#ifndef coff_final_link_postscript
5396
5397static bool
5398coff_final_link_postscript (bfd * abfd ATTRIBUTE_UNUSED,
5399			    struct coff_final_link_info * pfinfo ATTRIBUTE_UNUSED)
5400{
5401  return true;
5402}
5403#endif
5404
5405#ifndef coff_SWAP_aux_in
5406#define coff_SWAP_aux_in coff_swap_aux_in
5407#endif
5408#ifndef coff_SWAP_sym_in
5409#define coff_SWAP_sym_in coff_swap_sym_in
5410#endif
5411#ifndef coff_SWAP_lineno_in
5412#define coff_SWAP_lineno_in coff_swap_lineno_in
5413#endif
5414#ifndef coff_SWAP_aux_out
5415#define coff_SWAP_aux_out coff_swap_aux_out
5416#endif
5417#ifndef coff_SWAP_sym_out
5418#define coff_SWAP_sym_out coff_swap_sym_out
5419#endif
5420#ifndef coff_SWAP_lineno_out
5421#define coff_SWAP_lineno_out coff_swap_lineno_out
5422#endif
5423#ifndef coff_SWAP_reloc_out
5424#define coff_SWAP_reloc_out coff_swap_reloc_out
5425#endif
5426#ifndef coff_SWAP_filehdr_out
5427#define coff_SWAP_filehdr_out coff_swap_filehdr_out
5428#endif
5429#ifndef coff_SWAP_aouthdr_out
5430#define coff_SWAP_aouthdr_out coff_swap_aouthdr_out
5431#endif
5432#ifndef coff_SWAP_scnhdr_out
5433#define coff_SWAP_scnhdr_out coff_swap_scnhdr_out
5434#endif
5435#ifndef coff_SWAP_reloc_in
5436#define coff_SWAP_reloc_in coff_swap_reloc_in
5437#endif
5438#ifndef coff_SWAP_filehdr_in
5439#define coff_SWAP_filehdr_in coff_swap_filehdr_in
5440#endif
5441#ifndef coff_SWAP_aouthdr_in
5442#define coff_SWAP_aouthdr_in coff_swap_aouthdr_in
5443#endif
5444#ifndef coff_SWAP_scnhdr_in
5445#define coff_SWAP_scnhdr_in coff_swap_scnhdr_in
5446#endif
5447
5448static bfd_coff_backend_data bfd_coff_std_swap_table ATTRIBUTE_UNUSED =
5449{
5450  coff_SWAP_aux_in, coff_SWAP_sym_in, coff_SWAP_lineno_in,
5451  coff_SWAP_aux_out, coff_SWAP_sym_out,
5452  coff_SWAP_lineno_out, coff_SWAP_reloc_out,
5453  coff_SWAP_filehdr_out, coff_SWAP_aouthdr_out,
5454  coff_SWAP_scnhdr_out,
5455  FILHSZ, AOUTSZ, SCNHSZ, SYMESZ, AUXESZ, RELSZ, LINESZ, FILNMLEN,
5456#ifdef COFF_LONG_FILENAMES
5457  true,
5458#else
5459  false,
5460#endif
5461  COFF_DEFAULT_LONG_SECTION_NAMES,
5462  COFF_DEFAULT_SECTION_ALIGNMENT_POWER,
5463#ifdef COFF_FORCE_SYMBOLS_IN_STRINGS
5464  true,
5465#else
5466  false,
5467#endif
5468#ifdef COFF_DEBUG_STRING_WIDE_PREFIX
5469  4,
5470#else
5471  2,
5472#endif
5473  32768,
5474  coff_SWAP_filehdr_in, coff_SWAP_aouthdr_in, coff_SWAP_scnhdr_in,
5475  coff_SWAP_reloc_in, coff_bad_format_hook, coff_set_arch_mach_hook,
5476  coff_mkobject_hook, styp_to_sec_flags, coff_set_alignment_hook,
5477  coff_slurp_symbol_table, symname_in_debug_hook, coff_pointerize_aux_hook,
5478  coff_print_aux, coff_reloc16_extra_cases, coff_reloc16_estimate,
5479  coff_classify_symbol, coff_compute_section_file_positions,
5480  coff_start_final_link, coff_relocate_section, coff_rtype_to_howto,
5481  coff_adjust_symndx, coff_link_add_one_symbol,
5482  coff_link_output_has_begun, coff_final_link_postscript,
5483  bfd_pe_print_pdata
5484};
5485
5486#ifdef TICOFF
5487/* COFF0 differs in file/section header size and relocation entry size.  */
5488
5489static bfd_coff_backend_data ticoff0_swap_table =
5490{
5491  coff_SWAP_aux_in, coff_SWAP_sym_in, coff_SWAP_lineno_in,
5492  coff_SWAP_aux_out, coff_SWAP_sym_out,
5493  coff_SWAP_lineno_out, coff_swap_reloc_v0_out,
5494  coff_SWAP_filehdr_out, coff_SWAP_aouthdr_out,
5495  coff_SWAP_scnhdr_out,
5496  FILHSZ_V0, AOUTSZ, SCNHSZ_V01, SYMESZ, AUXESZ, RELSZ_V0, LINESZ, FILNMLEN,
5497#ifdef COFF_LONG_FILENAMES
5498  true,
5499#else
5500  false,
5501#endif
5502  COFF_DEFAULT_LONG_SECTION_NAMES,
5503  COFF_DEFAULT_SECTION_ALIGNMENT_POWER,
5504#ifdef COFF_FORCE_SYMBOLS_IN_STRINGS
5505  true,
5506#else
5507  false,
5508#endif
5509#ifdef COFF_DEBUG_STRING_WIDE_PREFIX
5510  4,
5511#else
5512  2,
5513#endif
5514  32768,
5515  coff_SWAP_filehdr_in, coff_SWAP_aouthdr_in, coff_SWAP_scnhdr_in,
5516  coff_swap_reloc_v0_in, ticoff0_bad_format_hook, coff_set_arch_mach_hook,
5517  coff_mkobject_hook, styp_to_sec_flags, coff_set_alignment_hook,
5518  coff_slurp_symbol_table, symname_in_debug_hook, coff_pointerize_aux_hook,
5519  coff_print_aux, coff_reloc16_extra_cases, coff_reloc16_estimate,
5520  coff_classify_symbol, coff_compute_section_file_positions,
5521  coff_start_final_link, coff_relocate_section, coff_rtype_to_howto,
5522  coff_adjust_symndx, coff_link_add_one_symbol,
5523  coff_link_output_has_begun, coff_final_link_postscript,
5524  bfd_pe_print_pdata
5525};
5526#endif
5527
5528#ifdef TICOFF
5529/* COFF1 differs in section header size.  */
5530
5531static bfd_coff_backend_data ticoff1_swap_table =
5532{
5533  coff_SWAP_aux_in, coff_SWAP_sym_in, coff_SWAP_lineno_in,
5534  coff_SWAP_aux_out, coff_SWAP_sym_out,
5535  coff_SWAP_lineno_out, coff_SWAP_reloc_out,
5536  coff_SWAP_filehdr_out, coff_SWAP_aouthdr_out,
5537  coff_SWAP_scnhdr_out,
5538  FILHSZ, AOUTSZ, SCNHSZ_V01, SYMESZ, AUXESZ, RELSZ, LINESZ, FILNMLEN,
5539#ifdef COFF_LONG_FILENAMES
5540  true,
5541#else
5542  false,
5543#endif
5544  COFF_DEFAULT_LONG_SECTION_NAMES,
5545  COFF_DEFAULT_SECTION_ALIGNMENT_POWER,
5546#ifdef COFF_FORCE_SYMBOLS_IN_STRINGS
5547  true,
5548#else
5549  false,
5550#endif
5551#ifdef COFF_DEBUG_STRING_WIDE_PREFIX
5552  4,
5553#else
5554  2,
5555#endif
5556  32768,
5557  coff_SWAP_filehdr_in, coff_SWAP_aouthdr_in, coff_SWAP_scnhdr_in,
5558  coff_SWAP_reloc_in, ticoff1_bad_format_hook, coff_set_arch_mach_hook,
5559  coff_mkobject_hook, styp_to_sec_flags, coff_set_alignment_hook,
5560  coff_slurp_symbol_table, symname_in_debug_hook, coff_pointerize_aux_hook,
5561  coff_print_aux, coff_reloc16_extra_cases, coff_reloc16_estimate,
5562  coff_classify_symbol, coff_compute_section_file_positions,
5563  coff_start_final_link, coff_relocate_section, coff_rtype_to_howto,
5564  coff_adjust_symndx, coff_link_add_one_symbol,
5565  coff_link_output_has_begun, coff_final_link_postscript,
5566  bfd_pe_print_pdata	/* huh */
5567};
5568#endif
5569
5570#ifdef COFF_WITH_PE_BIGOBJ
5571/* The UID for bigobj files.  */
5572
5573static const char header_bigobj_classid[16] =
5574{
5575  0xC7, 0xA1, 0xBA, 0xD1,
5576  0xEE, 0xBA,
5577  0xa9, 0x4b,
5578  0xAF, 0x20,
5579  0xFA, 0xF6, 0x6A, 0xA4, 0xDC, 0xB8
5580};
5581
5582/* Swap routines.  */
5583
5584static void
5585coff_bigobj_swap_filehdr_in (bfd * abfd, void * src, void * dst)
5586{
5587  struct external_ANON_OBJECT_HEADER_BIGOBJ *filehdr_src =
5588    (struct external_ANON_OBJECT_HEADER_BIGOBJ *) src;
5589  struct internal_filehdr *filehdr_dst = (struct internal_filehdr *) dst;
5590
5591  filehdr_dst->f_magic  = H_GET_16 (abfd, filehdr_src->Machine);
5592  filehdr_dst->f_nscns  = H_GET_32 (abfd, filehdr_src->NumberOfSections);
5593  filehdr_dst->f_timdat = H_GET_32 (abfd, filehdr_src->TimeDateStamp);
5594  filehdr_dst->f_symptr =
5595    GET_FILEHDR_SYMPTR (abfd, filehdr_src->PointerToSymbolTable);
5596  filehdr_dst->f_nsyms  = H_GET_32 (abfd, filehdr_src->NumberOfSymbols);
5597  filehdr_dst->f_opthdr = 0;
5598  filehdr_dst->f_flags  = 0;
5599
5600  /* Check other magic numbers.  */
5601  if (H_GET_16 (abfd, filehdr_src->Sig1) != IMAGE_FILE_MACHINE_UNKNOWN
5602      || H_GET_16 (abfd, filehdr_src->Sig2) != 0xffff
5603      || H_GET_16 (abfd, filehdr_src->Version) != 2
5604      || memcmp (filehdr_src->ClassID, header_bigobj_classid, 16) != 0)
5605    filehdr_dst->f_opthdr = 0xffff;
5606
5607  /* Note that CLR metadata are ignored.  */
5608}
5609
5610static unsigned int
5611coff_bigobj_swap_filehdr_out (bfd *abfd, void * in, void * out)
5612{
5613  struct internal_filehdr *filehdr_in = (struct internal_filehdr *) in;
5614  struct external_ANON_OBJECT_HEADER_BIGOBJ *filehdr_out =
5615    (struct external_ANON_OBJECT_HEADER_BIGOBJ *) out;
5616
5617  memset (filehdr_out, 0, sizeof (*filehdr_out));
5618
5619  H_PUT_16 (abfd, IMAGE_FILE_MACHINE_UNKNOWN, filehdr_out->Sig1);
5620  H_PUT_16 (abfd, 0xffff, filehdr_out->Sig2);
5621  H_PUT_16 (abfd, 2, filehdr_out->Version);
5622  memcpy (filehdr_out->ClassID, header_bigobj_classid, 16);
5623  H_PUT_16 (abfd, filehdr_in->f_magic, filehdr_out->Machine);
5624  H_PUT_32 (abfd, filehdr_in->f_nscns, filehdr_out->NumberOfSections);
5625  H_PUT_32 (abfd, filehdr_in->f_timdat, filehdr_out->TimeDateStamp);
5626  PUT_FILEHDR_SYMPTR (abfd, filehdr_in->f_symptr,
5627		      filehdr_out->PointerToSymbolTable);
5628  H_PUT_32 (abfd, filehdr_in->f_nsyms, filehdr_out->NumberOfSymbols);
5629
5630  return bfd_coff_filhsz (abfd);
5631}
5632
5633static void
5634coff_bigobj_swap_sym_in (bfd * abfd, void * ext1, void * in1)
5635{
5636  SYMENT_BIGOBJ *ext = (SYMENT_BIGOBJ *) ext1;
5637  struct internal_syment *in = (struct internal_syment *) in1;
5638
5639  if (ext->e.e_name[0] == 0)
5640    {
5641      in->_n._n_n._n_zeroes = 0;
5642      in->_n._n_n._n_offset = H_GET_32 (abfd, ext->e.e.e_offset);
5643    }
5644  else
5645    {
5646#if SYMNMLEN != E_SYMNMLEN
5647#error we need to cope with truncating or extending SYMNMLEN
5648#else
5649      memcpy (in->_n._n_name, ext->e.e_name, SYMNMLEN);
5650#endif
5651    }
5652
5653  in->n_value = H_GET_32 (abfd, ext->e_value);
5654  BFD_ASSERT (sizeof (in->n_scnum) >= 4);
5655  in->n_scnum = H_GET_32 (abfd, ext->e_scnum);
5656  in->n_type = H_GET_16 (abfd, ext->e_type);
5657  in->n_sclass = H_GET_8 (abfd, ext->e_sclass);
5658  in->n_numaux = H_GET_8 (abfd, ext->e_numaux);
5659}
5660
5661static unsigned int
5662coff_bigobj_swap_sym_out (bfd * abfd, void * inp, void * extp)
5663{
5664  struct internal_syment *in = (struct internal_syment *) inp;
5665  SYMENT_BIGOBJ *ext = (SYMENT_BIGOBJ *) extp;
5666
5667  if (in->_n._n_name[0] == 0)
5668    {
5669      H_PUT_32 (abfd, 0, ext->e.e.e_zeroes);
5670      H_PUT_32 (abfd, in->_n._n_n._n_offset, ext->e.e.e_offset);
5671    }
5672  else
5673    {
5674#if SYMNMLEN != E_SYMNMLEN
5675#error we need to cope with truncating or extending SYMNMLEN
5676#else
5677      memcpy (ext->e.e_name, in->_n._n_name, SYMNMLEN);
5678#endif
5679    }
5680
5681  H_PUT_32 (abfd, in->n_value, ext->e_value);
5682  H_PUT_32 (abfd, in->n_scnum, ext->e_scnum);
5683
5684  H_PUT_16 (abfd, in->n_type, ext->e_type);
5685  H_PUT_8 (abfd, in->n_sclass, ext->e_sclass);
5686  H_PUT_8 (abfd, in->n_numaux, ext->e_numaux);
5687
5688  return SYMESZ_BIGOBJ;
5689}
5690
5691static void
5692coff_bigobj_swap_aux_in (bfd *abfd,
5693			 void * ext1,
5694			 int type,
5695			 int in_class,
5696			 int indx,
5697			 int numaux,
5698			 void * in1)
5699{
5700  AUXENT_BIGOBJ *ext = (AUXENT_BIGOBJ *) ext1;
5701  union internal_auxent *in = (union internal_auxent *) in1;
5702
5703  /* Make sure that all fields in the aux structure are
5704     initialised.  */
5705  memset (in, 0, sizeof * in);
5706  switch (in_class)
5707    {
5708    case C_FILE:
5709      if (numaux > 1)
5710	{
5711	  if (indx == 0)
5712	    memcpy (in->x_file.x_n.x_fname, ext->File.Name,
5713		    numaux * sizeof (AUXENT_BIGOBJ));
5714	}
5715      else
5716	memcpy (in->x_file.x_n.x_fname, ext->File.Name, sizeof (ext->File.Name));
5717      break;
5718
5719    case C_STAT:
5720    case C_LEAFSTAT:
5721    case C_HIDDEN:
5722      if (type == T_NULL)
5723	{
5724	  in->x_scn.x_scnlen = H_GET_32 (abfd, ext->Section.Length);
5725	  in->x_scn.x_nreloc =
5726	    H_GET_16 (abfd, ext->Section.NumberOfRelocations);
5727	  in->x_scn.x_nlinno =
5728	    H_GET_16 (abfd, ext->Section.NumberOfLinenumbers);
5729	  in->x_scn.x_checksum = H_GET_32 (abfd, ext->Section.Checksum);
5730	  in->x_scn.x_associated = H_GET_16 (abfd, ext->Section.Number)
5731	    | (H_GET_16 (abfd, ext->Section.HighNumber) << 16);
5732	  in->x_scn.x_comdat = H_GET_8 (abfd, ext->Section.Selection);
5733	  return;
5734	}
5735      break;
5736
5737    default:
5738      in->x_sym.x_tagndx.l = H_GET_32 (abfd, ext->Sym.WeakDefaultSymIndex);
5739      /* Characteristics is ignored.  */
5740      break;
5741    }
5742}
5743
5744static unsigned int
5745coff_bigobj_swap_aux_out (bfd * abfd,
5746			  void * inp,
5747			  int type,
5748			  int in_class,
5749			  int indx ATTRIBUTE_UNUSED,
5750			  int numaux ATTRIBUTE_UNUSED,
5751			  void * extp)
5752{
5753  union internal_auxent * in = (union internal_auxent *) inp;
5754  AUXENT_BIGOBJ *ext = (AUXENT_BIGOBJ *) extp;
5755
5756  memset (ext, 0, AUXESZ);
5757
5758  switch (in_class)
5759    {
5760    case C_FILE:
5761      memcpy (ext->File.Name, in->x_file.x_n.x_fname, sizeof (ext->File.Name));
5762
5763      return AUXESZ;
5764
5765    case C_STAT:
5766    case C_LEAFSTAT:
5767    case C_HIDDEN:
5768      if (type == T_NULL)
5769	{
5770	  H_PUT_32 (abfd, in->x_scn.x_scnlen, ext->Section.Length);
5771	  H_PUT_16 (abfd, in->x_scn.x_nreloc,
5772		    ext->Section.NumberOfRelocations);
5773	  H_PUT_16 (abfd, in->x_scn.x_nlinno,
5774		    ext->Section.NumberOfLinenumbers);
5775	  H_PUT_32 (abfd, in->x_scn.x_checksum, ext->Section.Checksum);
5776	  H_PUT_16 (abfd, in->x_scn.x_associated & 0xffff,
5777		    ext->Section.Number);
5778	  H_PUT_16 (abfd, (in->x_scn.x_associated >> 16),
5779		    ext->Section.HighNumber);
5780	  H_PUT_8 (abfd, in->x_scn.x_comdat, ext->Section.Selection);
5781	  return AUXESZ;
5782	}
5783      break;
5784    }
5785
5786  H_PUT_32 (abfd, in->x_sym.x_tagndx.l, ext->Sym.WeakDefaultSymIndex);
5787  H_PUT_32 (abfd, 1, ext->Sym.WeakSearchType);
5788
5789  return AUXESZ;
5790}
5791
5792static bfd_coff_backend_data bigobj_swap_table =
5793{
5794  coff_bigobj_swap_aux_in, coff_bigobj_swap_sym_in, coff_SWAP_lineno_in,
5795  coff_bigobj_swap_aux_out, coff_bigobj_swap_sym_out,
5796  coff_SWAP_lineno_out, coff_SWAP_reloc_out,
5797  coff_bigobj_swap_filehdr_out, coff_SWAP_aouthdr_out,
5798  coff_SWAP_scnhdr_out,
5799  FILHSZ_BIGOBJ, AOUTSZ, SCNHSZ, SYMESZ_BIGOBJ, AUXESZ_BIGOBJ,
5800   RELSZ, LINESZ, FILNMLEN_BIGOBJ,
5801  true,
5802  COFF_DEFAULT_LONG_SECTION_NAMES,
5803  COFF_DEFAULT_SECTION_ALIGNMENT_POWER,
5804  false,
5805  2,
5806  1U << 31,
5807  coff_bigobj_swap_filehdr_in, coff_SWAP_aouthdr_in, coff_SWAP_scnhdr_in,
5808  coff_SWAP_reloc_in, coff_bad_format_hook, coff_set_arch_mach_hook,
5809  coff_mkobject_hook, styp_to_sec_flags, coff_set_alignment_hook,
5810  coff_slurp_symbol_table, symname_in_debug_hook, coff_pointerize_aux_hook,
5811  coff_print_aux, coff_reloc16_extra_cases, coff_reloc16_estimate,
5812  coff_classify_symbol, coff_compute_section_file_positions,
5813  coff_start_final_link, coff_relocate_section, coff_rtype_to_howto,
5814  coff_adjust_symndx, coff_link_add_one_symbol,
5815  coff_link_output_has_begun, coff_final_link_postscript,
5816  bfd_pe_print_pdata	/* huh */
5817};
5818
5819#endif /* COFF_WITH_PE_BIGOBJ */
5820
5821#ifndef coff_close_and_cleanup
5822#define coff_close_and_cleanup		    _bfd_coff_close_and_cleanup
5823#endif
5824
5825#ifndef coff_bfd_free_cached_info
5826#define coff_bfd_free_cached_info	    _bfd_generic_bfd_free_cached_info
5827#endif
5828
5829#ifndef coff_get_section_contents
5830#define coff_get_section_contents	    _bfd_generic_get_section_contents
5831#endif
5832
5833#ifndef coff_bfd_copy_private_symbol_data
5834#define coff_bfd_copy_private_symbol_data   _bfd_generic_bfd_copy_private_symbol_data
5835#endif
5836
5837#ifndef coff_bfd_copy_private_header_data
5838#define coff_bfd_copy_private_header_data   _bfd_generic_bfd_copy_private_header_data
5839#endif
5840
5841#ifndef coff_bfd_copy_private_section_data
5842#define coff_bfd_copy_private_section_data  _bfd_generic_bfd_copy_private_section_data
5843#endif
5844
5845#ifndef coff_bfd_copy_private_bfd_data
5846#define coff_bfd_copy_private_bfd_data      _bfd_generic_bfd_copy_private_bfd_data
5847#endif
5848
5849#ifndef coff_bfd_merge_private_bfd_data
5850#define coff_bfd_merge_private_bfd_data     _bfd_generic_bfd_merge_private_bfd_data
5851#endif
5852
5853#ifndef coff_bfd_set_private_flags
5854#define coff_bfd_set_private_flags	    _bfd_generic_bfd_set_private_flags
5855#endif
5856
5857#ifndef coff_bfd_print_private_bfd_data
5858#define coff_bfd_print_private_bfd_data     _bfd_generic_bfd_print_private_bfd_data
5859#endif
5860
5861#ifndef coff_bfd_is_local_label_name
5862#define coff_bfd_is_local_label_name	    _bfd_coff_is_local_label_name
5863#endif
5864
5865#ifndef coff_bfd_is_target_special_symbol
5866#define coff_bfd_is_target_special_symbol   _bfd_bool_bfd_asymbol_false
5867#endif
5868
5869#ifndef coff_read_minisymbols
5870#define coff_read_minisymbols		    _bfd_generic_read_minisymbols
5871#endif
5872
5873#ifndef coff_minisymbol_to_symbol
5874#define coff_minisymbol_to_symbol	    _bfd_generic_minisymbol_to_symbol
5875#endif
5876
5877/* The reloc lookup routine must be supplied by each individual COFF
5878   backend.  */
5879#ifndef coff_bfd_reloc_type_lookup
5880#define coff_bfd_reloc_type_lookup	    _bfd_norelocs_bfd_reloc_type_lookup
5881#endif
5882#ifndef coff_bfd_reloc_name_lookup
5883#define coff_bfd_reloc_name_lookup    _bfd_norelocs_bfd_reloc_name_lookup
5884#endif
5885
5886#ifndef coff_bfd_get_relocated_section_contents
5887#define coff_bfd_get_relocated_section_contents \
5888  bfd_generic_get_relocated_section_contents
5889#endif
5890
5891#ifndef coff_bfd_relax_section
5892#define coff_bfd_relax_section		    bfd_generic_relax_section
5893#endif
5894
5895#ifndef coff_bfd_gc_sections
5896#define coff_bfd_gc_sections		    bfd_coff_gc_sections
5897#endif
5898
5899#ifndef coff_bfd_lookup_section_flags
5900#define coff_bfd_lookup_section_flags	    bfd_generic_lookup_section_flags
5901#endif
5902
5903#ifndef coff_bfd_merge_sections
5904#define coff_bfd_merge_sections		    bfd_generic_merge_sections
5905#endif
5906
5907#ifndef coff_bfd_is_group_section
5908#define coff_bfd_is_group_section	    bfd_generic_is_group_section
5909#endif
5910
5911#ifndef coff_bfd_group_name
5912#define coff_bfd_group_name		    bfd_coff_group_name
5913#endif
5914
5915#ifndef coff_bfd_discard_group
5916#define coff_bfd_discard_group		    bfd_generic_discard_group
5917#endif
5918
5919#ifndef coff_section_already_linked
5920#define coff_section_already_linked \
5921  _bfd_coff_section_already_linked
5922#endif
5923
5924#ifndef coff_bfd_define_common_symbol
5925#define coff_bfd_define_common_symbol	    bfd_generic_define_common_symbol
5926#endif
5927
5928#ifndef coff_bfd_link_hide_symbol
5929#define coff_bfd_link_hide_symbol	    _bfd_generic_link_hide_symbol
5930#endif
5931
5932#ifndef coff_bfd_define_start_stop
5933#define coff_bfd_define_start_stop	    bfd_generic_define_start_stop
5934#endif
5935
5936#define CREATE_BIG_COFF_TARGET_VEC(VAR, NAME, EXTRA_O_FLAGS, EXTRA_S_FLAGS, UNDER, ALTERNATIVE, SWAP_TABLE)	\
5937const bfd_target VAR =							\
5938{									\
5939  NAME ,								\
5940  bfd_target_coff_flavour,						\
5941  BFD_ENDIAN_BIG,		/* Data byte order is big.  */		\
5942  BFD_ENDIAN_BIG,		/* Header byte order is big.  */	\
5943  /* object flags */							\
5944  (HAS_RELOC | EXEC_P | HAS_LINENO | HAS_DEBUG |			\
5945   HAS_SYMS | HAS_LOCALS | WP_TEXT | EXTRA_O_FLAGS),			\
5946  /* section flags */							\
5947  (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_RELOC | EXTRA_S_FLAGS),\
5948  UNDER,			/* Leading symbol underscore.  */	\
5949  '/',				/* AR_pad_char.  */			\
5950  15,				/* AR_max_namelen.  */			\
5951  0,				/* match priority.  */			\
5952  TARGET_KEEP_UNUSED_SECTION_SYMBOLS, /* keep unused section symbols.  */ \
5953									\
5954  /* Data conversion functions.  */					\
5955  bfd_getb64, bfd_getb_signed_64, bfd_putb64,				\
5956  bfd_getb32, bfd_getb_signed_32, bfd_putb32,				\
5957  bfd_getb16, bfd_getb_signed_16, bfd_putb16,				\
5958									\
5959  /* Header conversion functions.  */					\
5960  bfd_getb64, bfd_getb_signed_64, bfd_putb64,				\
5961  bfd_getb32, bfd_getb_signed_32, bfd_putb32,				\
5962  bfd_getb16, bfd_getb_signed_16, bfd_putb16,				\
5963									\
5964  {				/* bfd_check_format.  */		\
5965    _bfd_dummy_target,							\
5966    coff_object_p,							\
5967    bfd_generic_archive_p,						\
5968    _bfd_dummy_target							\
5969  },									\
5970  {				/* bfd_set_format.  */			\
5971    _bfd_bool_bfd_false_error,						\
5972    coff_mkobject,							\
5973    _bfd_generic_mkarchive,						\
5974    _bfd_bool_bfd_false_error						\
5975  },									\
5976  {				/* bfd_write_contents.  */		\
5977    _bfd_bool_bfd_false_error,						\
5978    coff_write_object_contents,						\
5979    _bfd_write_archive_contents,					\
5980    _bfd_bool_bfd_false_error						\
5981  },									\
5982									\
5983  BFD_JUMP_TABLE_GENERIC (coff),					\
5984  BFD_JUMP_TABLE_COPY (coff),						\
5985  BFD_JUMP_TABLE_CORE (_bfd_nocore),					\
5986  BFD_JUMP_TABLE_ARCHIVE (_bfd_archive_coff),				\
5987  BFD_JUMP_TABLE_SYMBOLS (coff),					\
5988  BFD_JUMP_TABLE_RELOCS (coff),						\
5989  BFD_JUMP_TABLE_WRITE (coff),						\
5990  BFD_JUMP_TABLE_LINK (coff),						\
5991  BFD_JUMP_TABLE_DYNAMIC (_bfd_nodynamic),				\
5992									\
5993  ALTERNATIVE,								\
5994									\
5995  SWAP_TABLE								\
5996};
5997
5998#define CREATE_BIGHDR_COFF_TARGET_VEC(VAR, NAME, EXTRA_O_FLAGS, EXTRA_S_FLAGS, UNDER, ALTERNATIVE, SWAP_TABLE)	\
5999const bfd_target VAR =							\
6000{									\
6001  NAME ,								\
6002  bfd_target_coff_flavour,						\
6003  BFD_ENDIAN_LITTLE,		/* Data byte order is little.  */	\
6004  BFD_ENDIAN_BIG,		/* Header byte order is big.  */	\
6005  /* object flags */							\
6006  (HAS_RELOC | EXEC_P | HAS_LINENO | HAS_DEBUG |			\
6007   HAS_SYMS | HAS_LOCALS | WP_TEXT | EXTRA_O_FLAGS),			\
6008  /* section flags */							\
6009  (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_RELOC | EXTRA_S_FLAGS),\
6010  UNDER,			/* Leading symbol underscore.  */	\
6011  '/',				/* AR_pad_char.  */			\
6012  15,				/* AR_max_namelen.  */			\
6013  0,				/* match priority.  */			\
6014  TARGET_KEEP_UNUSED_SECTION_SYMBOLS, /* keep unused section symbols.  */ \
6015									\
6016  /* Data conversion functions.  */					\
6017  bfd_getb64, bfd_getb_signed_64, bfd_putb64,				\
6018  bfd_getb32, bfd_getb_signed_32, bfd_putb32,				\
6019  bfd_getb16, bfd_getb_signed_16, bfd_putb16,				\
6020									\
6021  /* Header conversion functions.  */					\
6022  bfd_getb64, bfd_getb_signed_64, bfd_putb64,				\
6023  bfd_getb32, bfd_getb_signed_32, bfd_putb32,				\
6024  bfd_getb16, bfd_getb_signed_16, bfd_putb16,				\
6025									\
6026  {				/* bfd_check_format.  */		\
6027    _bfd_dummy_target,							\
6028    coff_object_p,							\
6029    bfd_generic_archive_p,						\
6030    _bfd_dummy_target							\
6031  },									\
6032  {				/* bfd_set_format.  */			\
6033    _bfd_bool_bfd_false_error,						\
6034    coff_mkobject,							\
6035    _bfd_generic_mkarchive,						\
6036    _bfd_bool_bfd_false_error						\
6037  },									\
6038  {				/* bfd_write_contents.  */		\
6039    _bfd_bool_bfd_false_error,						\
6040    coff_write_object_contents,						\
6041    _bfd_write_archive_contents,					\
6042    _bfd_bool_bfd_false_error						\
6043  },									\
6044									\
6045  BFD_JUMP_TABLE_GENERIC (coff),					\
6046  BFD_JUMP_TABLE_COPY (coff),						\
6047  BFD_JUMP_TABLE_CORE (_bfd_nocore),					\
6048  BFD_JUMP_TABLE_ARCHIVE (_bfd_archive_coff),				\
6049  BFD_JUMP_TABLE_SYMBOLS (coff),					\
6050  BFD_JUMP_TABLE_RELOCS (coff),						\
6051  BFD_JUMP_TABLE_WRITE (coff),						\
6052  BFD_JUMP_TABLE_LINK (coff),						\
6053  BFD_JUMP_TABLE_DYNAMIC (_bfd_nodynamic),				\
6054									\
6055  ALTERNATIVE,								\
6056									\
6057  SWAP_TABLE								\
6058};
6059
6060#define CREATE_LITTLE_COFF_TARGET_VEC(VAR, NAME, EXTRA_O_FLAGS, EXTRA_S_FLAGS, UNDER, ALTERNATIVE, SWAP_TABLE)	\
6061const bfd_target VAR =							\
6062{									\
6063  NAME ,								\
6064  bfd_target_coff_flavour,						\
6065  BFD_ENDIAN_LITTLE,		/* Data byte order is little.  */	\
6066  BFD_ENDIAN_LITTLE,		/* Header byte order is little.  */	\
6067	/* object flags */						\
6068  (HAS_RELOC | EXEC_P | HAS_LINENO | HAS_DEBUG |			\
6069   HAS_SYMS | HAS_LOCALS | WP_TEXT | EXTRA_O_FLAGS),			\
6070	/* section flags */						\
6071  (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_RELOC | EXTRA_S_FLAGS),\
6072  UNDER,			/* Leading symbol underscore.  */	\
6073  '/',				/* AR_pad_char.  */			\
6074  15,				/* AR_max_namelen.  */			\
6075  0,				/* match priority.  */			\
6076  TARGET_KEEP_UNUSED_SECTION_SYMBOLS, /* keep unused section symbols.  */ \
6077									\
6078  /* Data conversion functions.  */					\
6079  bfd_getl64, bfd_getl_signed_64, bfd_putl64,				\
6080  bfd_getl32, bfd_getl_signed_32, bfd_putl32,				\
6081  bfd_getl16, bfd_getl_signed_16, bfd_putl16,				\
6082  /* Header conversion functions.  */					\
6083  bfd_getl64, bfd_getl_signed_64, bfd_putl64,				\
6084  bfd_getl32, bfd_getl_signed_32, bfd_putl32,				\
6085  bfd_getl16, bfd_getl_signed_16, bfd_putl16,				\
6086									\
6087  {				/* bfd_check_format.  */		\
6088    _bfd_dummy_target,							\
6089    coff_object_p,							\
6090    bfd_generic_archive_p,						\
6091    _bfd_dummy_target							\
6092  },									\
6093  {				/* bfd_set_format.  */			\
6094    _bfd_bool_bfd_false_error,						\
6095    coff_mkobject,							\
6096    _bfd_generic_mkarchive,						\
6097    _bfd_bool_bfd_false_error						\
6098  },									\
6099  {				/* bfd_write_contents.  */		\
6100    _bfd_bool_bfd_false_error,						\
6101    coff_write_object_contents,						\
6102    _bfd_write_archive_contents,					\
6103    _bfd_bool_bfd_false_error						\
6104  },									\
6105									\
6106  BFD_JUMP_TABLE_GENERIC (coff),					\
6107  BFD_JUMP_TABLE_COPY (coff),						\
6108  BFD_JUMP_TABLE_CORE (_bfd_nocore),					\
6109  BFD_JUMP_TABLE_ARCHIVE (_bfd_archive_coff),				\
6110  BFD_JUMP_TABLE_SYMBOLS (coff),					\
6111  BFD_JUMP_TABLE_RELOCS (coff),						\
6112  BFD_JUMP_TABLE_WRITE (coff),						\
6113  BFD_JUMP_TABLE_LINK (coff),						\
6114  BFD_JUMP_TABLE_DYNAMIC (_bfd_nodynamic),				\
6115									\
6116  ALTERNATIVE,								\
6117									\
6118  SWAP_TABLE								\
6119};
6120