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