Home | History | Annotate | Line # | Download | only in emultempl
      1 # This shell script emits a C file. -*- C -*-
      2 # It does some substitutions.
      3 if [ -z "$MACHINE" ]; then
      4   OUTPUT_ARCH=${ARCH}
      5 else
      6   OUTPUT_ARCH=${ARCH}:${MACHINE}
      7 fi
      8 
      9 case ${target} in
     10   *-*-mingw*)
     11     mingw_behavior=1
     12     ;;
     13   *)
     14     mingw_behavior=0
     15     ;;
     16 esac
     17 
     18 rm -f e${EMULATION_NAME}.c
     19 (echo;echo;echo;echo;echo)>e${EMULATION_NAME}.c # there, now line numbers match ;-)
     20 fragment <<EOF
     21 /* Copyright (C) 1995-2025 Free Software Foundation, Inc.
     22 
     23    This file is part of the GNU Binutils.
     24 
     25    This program is free software; you can redistribute it and/or modify
     26    it under the terms of the GNU General Public License as published by
     27    the Free Software Foundation; either version 3 of the License, or
     28    (at your option) any later version.
     29 
     30    This program is distributed in the hope that it will be useful,
     31    but WITHOUT ANY WARRANTY; without even the implied warranty of
     32    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     33    GNU General Public License for more details.
     34 
     35    You should have received a copy of the GNU General Public License
     36    along with this program; if not, write to the Free Software
     37    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
     38    MA 02110-1301, USA.  */
     39 
     40 
     41 /* For WINDOWS_NT */
     42 /* The original file generated returned different default scripts depending
     43    on whether certain switches were set, but these switches pertain to the
     44    Linux system and that particular version of coff.  In the NT case, we
     45    only determine if the subsystem is console or windows in order to select
     46    the correct entry point by default. */
     47 
     48 #define TARGET_IS_${EMULATION_NAME}
     49 
     50 #include "sysdep.h"
     51 #include "bfd.h"
     52 #include "bfdlink.h"
     53 #include "ctf-api.h"
     54 #include "getopt.h"
     55 #include "libiberty.h"
     56 #include "filenames.h"
     57 #include "ld.h"
     58 #include "ldmain.h"
     59 #include "ldexp.h"
     60 #include "ldlang.h"
     61 #include "ldfile.h"
     62 #include "ldemul.h"
     63 #include <ldgram.h>
     64 #include "ldlex.h"
     65 #include "ldmisc.h"
     66 #include "ldctor.h"
     67 #include "ldbuildid.h"
     68 #include "coff/internal.h"
     69 EOF
     70 
     71 case ${target} in
     72   x86_64-*-mingw* | x86_64-*-pe | x86_64-*-pep | x86_64-*-cygwin | \
     73   i[3-7]86-*-mingw32* | i[3-7]86-*-cygwin* | i[3-7]86-*-winnt | i[3-7]86-*-pe)
     74 fragment <<EOF
     75 #include "pdb.h"
     76 EOF
     77     ;;
     78 esac
     79 
     80 fragment <<EOF
     81 
     82 /* FIXME: See bfd/peXXigen.c for why we include an architecture specific
     83    header in generic PE code.  */
     84 #include "coff/i386.h"
     85 #include "coff/pe.h"
     86 
     87 /* FIXME: These are BFD internal header files, and we should not be
     88    using it here.  */
     89 #include "../bfd/libcoff.h"
     90 #include "../bfd/libpei.h"
     91 
     92 #if defined(TARGET_IS_armpe) \
     93     || defined(TARGET_IS_arm_wince_pe)
     94 #define bfd_arm_allocate_interworking_sections \
     95 	bfd_${EMULATION_NAME}_allocate_interworking_sections
     96 #define bfd_arm_get_bfd_for_interworking \
     97 	bfd_${EMULATION_NAME}_get_bfd_for_interworking
     98 #define bfd_arm_process_before_allocation \
     99 	bfd_${EMULATION_NAME}_process_before_allocation
    100 #include "coff-arm.h"
    101 #endif
    102 
    103 #include "deffile.h"
    104 #include "pe-dll.h"
    105 #include "safe-ctype.h"
    106 
    107 /* Permit the emulation parameters to override the default section
    108    alignment by setting OVERRIDE_SECTION_ALIGNMENT.  FIXME: This makes
    109    it seem that include/coff/internal.h should not define
    110    PE_DEF_SECTION_ALIGNMENT.  */
    111 #if PE_DEF_SECTION_ALIGNMENT != ${OVERRIDE_SECTION_ALIGNMENT:-PE_DEF_SECTION_ALIGNMENT}
    112 #undef PE_DEF_SECTION_ALIGNMENT
    113 #define PE_DEF_SECTION_ALIGNMENT ${OVERRIDE_SECTION_ALIGNMENT}
    114 #endif
    115 
    116 #if defined(TARGET_IS_i386pe) \
    117     || defined(TARGET_IS_shpe) \
    118     || defined(TARGET_IS_armpe) \
    119     || defined(TARGET_IS_arm_wince_pe)
    120 #define DLL_SUPPORT
    121 #endif
    122 
    123 #if defined(TARGET_IS_i386pe)
    124 #define DEFAULT_PSEUDO_RELOC_VERSION 2
    125 #else
    126 #define DEFAULT_PSEUDO_RELOC_VERSION 1
    127 #endif
    128 
    129 #define DEFAULT_DLL_CHARACTERISTICS	(${mingw_behavior} \
    130 					 ? IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE \
    131 					   | IMAGE_DLL_CHARACTERISTICS_NX_COMPAT \
    132 					 : 0)
    133 
    134 #if defined(TARGET_IS_i386pe) || ! defined(DLL_SUPPORT)
    135 #define	PE_DEF_SUBSYSTEM		IMAGE_SUBSYSTEM_WINDOWS_CUI
    136 #else
    137 #undef NT_EXE_IMAGE_BASE
    138 #undef PE_DEF_SECTION_ALIGNMENT
    139 #undef PE_DEF_FILE_ALIGNMENT
    140 #define NT_EXE_IMAGE_BASE		0x00010000
    141 
    142 #if defined(TARGET_IS_armpe)
    143 #define PE_DEF_SECTION_ALIGNMENT	0x00001000
    144 #define	PE_DEF_SUBSYSTEM		IMAGE_SUBSYSTEM_WINDOWS_GUI
    145 #elif defined(TARGET_IS_arm_wince_pe)
    146 #define PE_DEF_SECTION_ALIGNMENT	0x00001000
    147 #define	PE_DEF_SUBSYSTEM		IMAGE_SUBSYSTEM_WINDOWS_CE_GUI
    148 #else
    149 #define PE_DEF_SECTION_ALIGNMENT	0x00000400
    150 #define	PE_DEF_SUBSYSTEM		IMAGE_SUBSYSTEM_WINDOWS_GUI
    151 #endif
    152 #define PE_DEF_FILE_ALIGNMENT		0x00000200
    153 #endif
    154 
    155 static struct internal_extra_pe_aouthdr pe;
    156 static int dll;
    157 static int pe_subsystem = ${SUBSYSTEM};
    158 static flagword real_flags = 0;
    159 static int support_old_code = 0;
    160 static char * thumb_entry_symbol = NULL;
    161 static lang_assignment_statement_type *image_base_statement = 0;
    162 static unsigned short pe_dll_characteristics = DEFAULT_DLL_CHARACTERISTICS;
    163 static bool insert_timestamp = true;
    164 static bool orphan_init_done;
    165 static const char *emit_build_id;
    166 #ifdef PDB_H
    167 static int pdb;
    168 static char *pdb_name;
    169 #endif
    170 
    171 #ifdef DLL_SUPPORT
    172 static int pe_enable_stdcall_fixup = -1; /* 0=disable 1=enable.  */
    173 static char *pe_out_def_filename = NULL;
    174 static int pe_enable_auto_image_base = 0;
    175 static unsigned long pe_auto_image_base = 0x61500000;
    176 static char *pe_dll_search_prefix = NULL;
    177 #endif
    178 
    179 extern const char *output_filename;
    180 
    181 static int
    182 is_underscoring (void)
    183 {
    184   int u = 0;
    185   if (pe_leading_underscore != -1)
    186     return pe_leading_underscore;
    187   if (!bfd_get_target_info ("${OUTPUT_FORMAT}", NULL, NULL, &u, NULL))
    188     bfd_get_target_info ("${RELOCATEABLE_OUTPUT_FORMAT}", NULL, NULL, &u, NULL);
    189 
    190   if (u == -1)
    191     abort ();
    192   pe_leading_underscore = (u != 0 ? 1 : 0);
    193   return pe_leading_underscore;
    194 }
    195 
    196 static void
    197 gld${EMULATION_NAME}_before_parse (void)
    198 {
    199   is_underscoring ();
    200   ldfile_set_output_arch ("${OUTPUT_ARCH}", bfd_arch_`echo ${ARCH} | sed -e 's/:.*//'`);
    201   output_filename = "${EXECUTABLE_NAME:-a.exe}";
    202 #ifdef DLL_SUPPORT
    203   input_flags.dynamic = true;
    204   config.has_shared = 1;
    205 EOF
    206 
    207 # Cygwin no longer wants these noisy warnings.  Other PE
    208 # targets might like to consider adding themselves here.
    209 # See also the mail thread starting here for the reason why
    210 # merge_rdata defaults to 0 for cygwin:
    211 #  http://cygwin.com/ml/cygwin-apps/2013-04/msg00187.html
    212 case ${target} in
    213   *-*-cygwin*)
    214     default_auto_import=1
    215     default_merge_rdata=0
    216     ;;
    217   i[3-7]86-*-mingw* | x86_64-*-mingw*)
    218     default_auto_import=1
    219     default_merge_rdata=0
    220     ;;
    221   *)
    222     default_auto_import=-1
    223     default_merge_rdata=1
    224     ;;
    225 esac
    226 
    227 fragment <<EOF
    228   link_info.pei386_auto_import = ${default_auto_import};
    229   /* Use by default version.  */
    230   link_info.pei386_runtime_pseudo_reloc = DEFAULT_PSEUDO_RELOC_VERSION;
    231 #endif
    232 }
    233 
    235 /* Indicates if RDATA shall be merged into DATA when pseudo-relocation
    236    version 2 is used and auto-import is enabled.  */
    237 #define MERGE_RDATA_V2 ${default_merge_rdata}
    238 
    239 /* PE format extra command line options.  */
    240 
    241 static void
    242 gld${EMULATION_NAME}_add_options
    243   (int ns ATTRIBUTE_UNUSED,
    244    char **shortopts ATTRIBUTE_UNUSED,
    245    int nl,
    246    struct option **longopts,
    247    int nrl ATTRIBUTE_UNUSED,
    248    struct option **really_longopts ATTRIBUTE_UNUSED)
    249 {
    250   static const struct option xtra_long[] =
    251   {
    252     /* PE options.  */
    253     {"base-file", required_argument, NULL, OPTION_BASE_FILE},
    254     {"dll", no_argument, NULL, OPTION_DLL},
    255     {"file-alignment", required_argument, NULL, OPTION_FILE_ALIGNMENT},
    256     {"heap", required_argument, NULL, OPTION_HEAP},
    257     {"major-image-version", required_argument, NULL, OPTION_MAJOR_IMAGE_VERSION},
    258     {"major-os-version", required_argument, NULL, OPTION_MAJOR_OS_VERSION},
    259     {"major-subsystem-version", required_argument, NULL, OPTION_MAJOR_SUBSYSTEM_VERSION},
    260     {"minor-image-version", required_argument, NULL, OPTION_MINOR_IMAGE_VERSION},
    261     {"minor-os-version", required_argument, NULL, OPTION_MINOR_OS_VERSION},
    262     {"minor-subsystem-version", required_argument, NULL, OPTION_MINOR_SUBSYSTEM_VERSION},
    263     {"section-alignment", required_argument, NULL, OPTION_SECTION_ALIGNMENT},
    264     {"stack", required_argument, NULL, OPTION_STACK},
    265     {"subsystem", required_argument, NULL, OPTION_SUBSYSTEM},
    266     {"support-old-code", no_argument, NULL, OPTION_SUPPORT_OLD_CODE},
    267     {"thumb-entry", required_argument, NULL, OPTION_THUMB_ENTRY},
    268     {"use-nul-prefixed-import-tables", no_argument, NULL,
    269      OPTION_USE_NUL_PREFIXED_IMPORT_TABLES},
    270     {"no-leading-underscore", no_argument, NULL, OPTION_NO_LEADING_UNDERSCORE},
    271     {"leading-underscore", no_argument, NULL, OPTION_LEADING_UNDERSCORE},
    272     {"insert-timestamp", no_argument, NULL, OPTION_INSERT_TIMESTAMP},
    273     {"no-insert-timestamp", no_argument, NULL, OPTION_NO_INSERT_TIMESTAMP},
    274 #ifdef DLL_SUPPORT
    275     /* getopt allows abbreviations, so we do this to stop it
    276        from treating -o as an abbreviation for this option.  */
    277     {"output-def", required_argument, NULL, OPTION_OUT_DEF},
    278     {"output-def", required_argument, NULL, OPTION_OUT_DEF},
    279     {"export-all-symbols", no_argument, NULL, OPTION_EXPORT_ALL},
    280     {"exclude-symbols", required_argument, NULL, OPTION_EXCLUDE_SYMBOLS},
    281     {"exclude-all-symbols", no_argument, NULL, OPTION_EXCLUDE_ALL_SYMBOLS},
    282     {"exclude-libs", required_argument, NULL, OPTION_EXCLUDE_LIBS},
    283     {"exclude-modules-for-implib", required_argument, NULL, OPTION_EXCLUDE_MODULES_FOR_IMPLIB},
    284     {"kill-at", no_argument, NULL, OPTION_KILL_ATS},
    285     {"add-stdcall-alias", no_argument, NULL, OPTION_STDCALL_ALIASES},
    286     {"enable-stdcall-fixup", no_argument, NULL, OPTION_ENABLE_STDCALL_FIXUP},
    287     {"disable-stdcall-fixup", no_argument, NULL, OPTION_DISABLE_STDCALL_FIXUP},
    288     {"warn-duplicate-exports", no_argument, NULL, OPTION_WARN_DUPLICATE_EXPORTS},
    289     /* getopt() allows abbreviations, so we do this to stop it from
    290        treating -c as an abbreviation for these --compat-implib.  */
    291     {"compat-implib", no_argument, NULL, OPTION_IMP_COMPAT},
    292     {"compat-implib", no_argument, NULL, OPTION_IMP_COMPAT},
    293     {"enable-auto-image-base", optional_argument, NULL, OPTION_ENABLE_AUTO_IMAGE_BASE},
    294     {"disable-auto-image-base", no_argument, NULL, OPTION_DISABLE_AUTO_IMAGE_BASE},
    295     {"dll-search-prefix", required_argument, NULL, OPTION_DLL_SEARCH_PREFIX},
    296     {"no-default-excludes", no_argument, NULL, OPTION_NO_DEFAULT_EXCLUDES},
    297     {"enable-auto-import", no_argument, NULL, OPTION_DLL_ENABLE_AUTO_IMPORT},
    298     {"disable-auto-import", no_argument, NULL, OPTION_DLL_DISABLE_AUTO_IMPORT},
    299     {"enable-extra-pe-debug", no_argument, NULL, OPTION_ENABLE_EXTRA_PE_DEBUG},
    300     {"enable-runtime-pseudo-reloc", no_argument, NULL, OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC},
    301     {"disable-runtime-pseudo-reloc", no_argument, NULL, OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC},
    302     {"enable-runtime-pseudo-reloc-v1", no_argument, NULL, OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V1},
    303     {"enable-runtime-pseudo-reloc-v2", no_argument, NULL, OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2},
    304 #endif
    305     {"large-address-aware", no_argument, NULL, OPTION_LARGE_ADDRESS_AWARE},
    306     {"disable-large-address-aware", no_argument, NULL, OPTION_DISABLE_LARGE_ADDRESS_AWARE},
    307     {"enable-long-section-names", no_argument, NULL, OPTION_ENABLE_LONG_SECTION_NAMES},
    308     {"disable-long-section-names", no_argument, NULL, OPTION_DISABLE_LONG_SECTION_NAMES},
    309     {"dynamicbase",no_argument, NULL, OPTION_DYNAMIC_BASE},
    310     {"disable-dynamicbase",no_argument, NULL, OPTION_DISABLE_DYNAMIC_BASE},
    311     {"forceinteg", no_argument, NULL, OPTION_FORCE_INTEGRITY},
    312     {"disable-forceinteg", no_argument, NULL, OPTION_DISABLE_FORCE_INTEGRITY},
    313     {"nxcompat", no_argument, NULL, OPTION_NX_COMPAT},
    314     {"disable-nxcompat", no_argument, NULL, OPTION_DISABLE_NX_COMPAT},
    315     {"no-isolation", no_argument, NULL, OPTION_NO_ISOLATION},
    316     {"disable-no-isolation", no_argument, NULL, OPTION_DISABLE_NO_ISOLATION},
    317     {"no-seh", no_argument, NULL, OPTION_NO_SEH},
    318     {"disable-no-seh", no_argument, NULL, OPTION_DISABLE_NO_SEH},
    319     {"no-bind", no_argument, NULL, OPTION_NO_BIND},
    320     {"disable-no-bind", no_argument, NULL, OPTION_DISABLE_NO_BIND},
    321     {"wdmdriver", no_argument, NULL, OPTION_WDM_DRIVER},
    322     {"disable-wdmdriver", no_argument, NULL, OPTION_DISABLE_WDM_DRIVER},
    323     {"tsaware", no_argument, NULL, OPTION_TERMINAL_SERVER_AWARE},
    324     {"disable-tsaware", no_argument, NULL, OPTION_DISABLE_TERMINAL_SERVER_AWARE},
    325     {"build-id", optional_argument, NULL, OPTION_BUILD_ID},
    326 #ifdef PDB_H
    327     {"pdb", required_argument, NULL, OPTION_PDB},
    328 #endif
    329     {"enable-reloc-section", no_argument, NULL, OPTION_ENABLE_RELOC_SECTION},
    330     {"disable-reloc-section", no_argument, NULL, OPTION_DISABLE_RELOC_SECTION},
    331     {NULL, no_argument, NULL, 0}
    332   };
    333 
    334   *longopts
    335     = xrealloc (*longopts, nl * sizeof (struct option) + sizeof (xtra_long));
    336   memcpy (*longopts + nl, &xtra_long, sizeof (xtra_long));
    337 }
    338 
    339 /* PE/WIN32; added routines to get the subsystem type, heap and/or stack
    340    parameters which may be input from the command line.  */
    341 
    342 typedef struct
    343 {
    344   void *ptr;
    345   int size;
    346   int value;
    347   char *symbol;
    348   int inited;
    349   /* FALSE for an assembly level symbol and TRUE for a C visible symbol.
    350      C visible symbols can be prefixed by underscore dependent to target's
    351      settings.  */
    352   bool is_c_symbol;
    353 } definfo;
    354 
    355 /* Get symbol name dependent to kind and C visible state of
    356    underscore.  */
    357 #define GET_INIT_SYMBOL_NAME(IDX) \
    358   (init[(IDX)].symbol \
    359    + ((!init[(IDX)].is_c_symbol || is_underscoring () != 0) ? 0 : 1))
    360 
    361 /* Decorates the C visible symbol by underscore, if target requires.  */
    362 #define U(CSTR) \
    363   ((is_underscoring () == 0) ? CSTR : "_" CSTR)
    364 
    365 #define D(field,symbol,def,usc)  {&pe.field, sizeof (pe.field), def, symbol, 0, usc}
    366 
    367 static definfo init[] =
    368 {
    369   /* imagebase must be first */
    370 #define IMAGEBASEOFF 0
    371   D(ImageBase,"__image_base__", NT_EXE_IMAGE_BASE, false),
    372 #define DLLOFF 1
    373   {&dll, sizeof(dll), 0, "__dll__", 0, false},
    374 #define MSIMAGEBASEOFF	2
    375   D(ImageBase, "___ImageBase", NT_EXE_IMAGE_BASE, true),
    376   D(SectionAlignment,"__section_alignment__", PE_DEF_SECTION_ALIGNMENT, false),
    377   D(FileAlignment,"__file_alignment__", PE_DEF_FILE_ALIGNMENT, false),
    378   D(MajorOperatingSystemVersion,"__major_os_version__", 4, false),
    379   D(MinorOperatingSystemVersion,"__minor_os_version__", 0, false),
    380   D(MajorImageVersion,"__major_image_version__", 1, false),
    381   D(MinorImageVersion,"__minor_image_version__", 0, false),
    382 #if defined(TARGET_IS_armpe)  || defined(TARGET_IS_arm_wince_pe)
    383   D(MajorSubsystemVersion,"__major_subsystem_version__", 3, false),
    384 #else
    385   D(MajorSubsystemVersion,"__major_subsystem_version__", 4, false),
    386 #endif
    387   D(MinorSubsystemVersion,"__minor_subsystem_version__", 0, false),
    388   D(Subsystem,"__subsystem__", ${SUBSYSTEM}, false),
    389   D(SizeOfStackReserve,"__size_of_stack_reserve__", 0x200000, false),
    390   D(SizeOfStackCommit,"__size_of_stack_commit__", 0x1000, false),
    391   D(SizeOfHeapReserve,"__size_of_heap_reserve__", 0x100000, false),
    392   D(SizeOfHeapCommit,"__size_of_heap_commit__", 0x1000, false),
    393   D(LoaderFlags,"__loader_flags__", 0x0, false),
    394   D(DllCharacteristics, "__dll_characteristics__", DEFAULT_DLL_CHARACTERISTICS, false),
    395   { NULL, 0, 0, NULL, 0 , false}
    396 };
    397 
    398 
    399 static void
    400 gld${EMULATION_NAME}_list_options (FILE *file)
    401 {
    402   fprintf (file, _("  --base_file <basefile>             Generate a base file for relocatable DLLs\n"));
    403   fprintf (file, _("  --dll                              Set image base to the default for DLLs\n"));
    404   fprintf (file, _("  --file-alignment <size>            Set file alignment\n"));
    405   fprintf (file, _("  --heap <size>                      Set initial size of the heap\n"));
    406   fprintf (file, _("  --image-base <address>             Set start address of the executable\n"));
    407   fprintf (file, _("  --major-image-version <number>     Set version number of the executable\n"));
    408   fprintf (file, _("  --major-os-version <number>        Set minimum required OS version\n"));
    409   fprintf (file, _("  --major-subsystem-version <number> Set minimum required OS subsystem version\n"));
    410   fprintf (file, _("  --minor-image-version <number>     Set revision number of the executable\n"));
    411   fprintf (file, _("  --minor-os-version <number>        Set minimum required OS revision\n"));
    412   fprintf (file, _("  --minor-subsystem-version <number> Set minimum required OS subsystem revision\n"));
    413   fprintf (file, _("  --section-alignment <size>         Set section alignment\n"));
    414   fprintf (file, _("  --stack <size>                     Set size of the initial stack\n"));
    415   fprintf (file, _("  --subsystem <name>[:<version>]     Set required OS subsystem [& version]\n"));
    416   fprintf (file, _("  --support-old-code                 Support interworking with old code\n"));
    417   fprintf (file, _("  --[no-]leading-underscore          Set explicit symbol underscore prefix mode\n"));
    418   fprintf (file, _("  --thumb-entry=<symbol>             Set the entry point to be Thumb <symbol>\n"));
    419   fprintf (file, _("  --[no-]insert-timestamp            Use a real timestamp rather than zero (default).\n"));
    420   fprintf (file, _("                                     This makes binaries non-deterministic\n"));
    421 #ifdef DLL_SUPPORT
    422   fprintf (file, _("  --add-stdcall-alias                Export symbols with and without @nn\n"));
    423   fprintf (file, _("  --disable-stdcall-fixup            Don't link _sym to _sym@nn\n"));
    424   fprintf (file, _("  --enable-stdcall-fixup             Link _sym to _sym@nn without warnings\n"));
    425   fprintf (file, _("  --exclude-symbols sym,sym,...      Exclude symbols from automatic export\n"));
    426   fprintf (file, _("  --exclude-all-symbols              Exclude all symbols from automatic export\n"));
    427   fprintf (file, _("  --exclude-libs lib,lib,...         Exclude libraries from automatic export\n"));
    428   fprintf (file, _("  --exclude-modules-for-implib mod,mod,...\n"));
    429   fprintf (file, _("                                     Exclude objects, archive members from auto\n"));
    430   fprintf (file, _("                                     export, place into import library instead.\n"));
    431   fprintf (file, _("  --export-all-symbols               Automatically export all globals to DLL\n"));
    432   fprintf (file, _("  --kill-at                          Remove @nn from exported symbols\n"));
    433   fprintf (file, _("  --output-def <file>                Generate a .DEF file for the built DLL\n"));
    434   fprintf (file, _("  --warn-duplicate-exports           Warn about duplicate exports\n"));
    435   fprintf (file, _("  --compat-implib                    Create backward compatible import libs;\n\
    436                                        create __imp_<SYMBOL> as well.\n"));
    437   fprintf (file, _("  --enable-auto-image-base[=<address>] Automatically choose image base for DLLs\n\
    438                                        (optionally starting with address) unless\n\
    439                                        specifically set with --image-base\n"));
    440   fprintf (file, _("  --disable-auto-image-base          Do not auto-choose image base. (default)\n"));
    441   fprintf (file, _("  --dll-search-prefix=<string>       When linking dynamically to a dll without\n\
    442                                        an importlib, use <string><basename>.dll\n\
    443                                        in preference to lib<basename>.dll \n"));
    444   fprintf (file, _("  --enable-auto-import               Do sophisticated linking of _sym to\n\
    445                                        __imp_sym for DATA references\n"));
    446   fprintf (file, _("  --disable-auto-import              Do not auto-import DATA items from DLLs\n"));
    447   fprintf (file, _("  --enable-runtime-pseudo-reloc      Work around auto-import limitations by\n\
    448                                        adding pseudo-relocations resolved at\n\
    449                                        runtime.\n"));
    450   fprintf (file, _("  --disable-runtime-pseudo-reloc     Do not add runtime pseudo-relocations for\n\
    451                                        auto-imported DATA.\n"));
    452   fprintf (file, _("  --enable-extra-pe-debug            Enable verbose debug output when building\n\
    453                                        or linking to DLLs (esp. auto-import)\n"));
    454 #endif
    455   fprintf (file, _("  --large-address-aware              Executable supports virtual addresses\n\
    456                                        greater than 2 gigabytes\n"));
    457   fprintf (file, _("  --disable-large-address-aware      Executable does not support virtual\n\
    458                                        addresses greater than 2 gigabytes\n"));
    459   fprintf (file, _("  --enable-long-section-names        Use long COFF section names even in\n\
    460                                        executable image files\n"));
    461   fprintf (file, _("  --disable-long-section-names       Never use long COFF section names, even\n\
    462                                        in object files\n"));
    463   fprintf (file, _("  --[disable-]dynamicbase            Image base address may be relocated using\n\
    464                                        address space layout randomization (ASLR)\n"));
    465   fprintf (file, _("  --enable-reloc-section             Create the base relocation table\n"));
    466   fprintf (file, _("  --disable-reloc-section            Do not create the base relocation table\n"));
    467   fprintf (file, _("  --[disable-]forceinteg             Code integrity checks are enforced\n"));
    468   fprintf (file, _("  --[disable-]nxcompat               Image is compatible with data execution\n\
    469                                        prevention\n"));
    470   fprintf (file, _("  --[disable-]no-isolation           Image understands isolation but do not\n\
    471                                        isolate the image\n"));
    472   fprintf (file, _("  --[disable-]no-seh                 Image does not use SEH. No SE handler may\n\
    473                                        be called in this image\n"));
    474   fprintf (file, _("  --[disable-]no-bind                Do not bind this image\n"));
    475   fprintf (file, _("  --[disable-]wdmdriver              Driver uses the WDM model\n"));
    476   fprintf (file, _("  --[disable-]tsaware                Image is Terminal Server aware\n"));
    477   fprintf (file, _("  --build-id[=STYLE]                 Generate build ID\n"));
    478 #ifdef PDB_H
    479   fprintf (file, _("  --pdb=[FILENAME]                   Generate PDB file\n"));
    480 #endif
    481 }
    482 
    483 /* A case insensitive comparison, regardless of the host platform, used for
    484    comparing file extensions.  */
    485 static int
    486 fileext_cmp (const char *s1, const char *s2)
    487 {
    488   for (;;)
    489     {
    490       int c1 = TOLOWER (*s1++);
    491       int c2 = *s2++; /* Assumed to be lower case from the caller.  */
    492 
    493       if (c1 != c2)
    494         return (c1 - c2);
    495 
    496       if (c1 == '\0')
    497         return 0;
    498     }
    499 }
    500 
    501 static void
    502 set_pe_name (char *name, long val)
    503 {
    504   int i;
    505   is_underscoring ();
    506 
    507   /* Find the name and set it.  */
    508   for (i = 0; init[i].ptr; i++)
    509     {
    510       if (strcmp (name, GET_INIT_SYMBOL_NAME (i)) == 0)
    511 	{
    512 	  init[i].value = val;
    513 	  init[i].inited = 1;
    514 	  if (strcmp (name,"__image_base__") == 0)
    515 	    set_pe_name (U ("__ImageBase"), val);
    516 	  return;
    517 	}
    518     }
    519   abort ();
    520 }
    521 
    522 static void
    523 set_entry_point (void)
    524 {
    525   const char *entry;
    526   const char *initial_symbol_char;
    527   int i;
    528 
    529   static const struct
    530   {
    531     const int value;
    532     const char *entry;
    533   }
    534   v[] =
    535     {
    536       { 1, "NtProcessStartup"  },
    537       { 2, "WinMainCRTStartup" },
    538       { 3, "mainCRTStartup"    },
    539       { 7, "__PosixProcessStartup"},
    540       { 9, "WinMainCRTStartup" },
    541       {14, "mainCRTStartup"    },
    542       { 0, NULL          }
    543     };
    544 
    545   /* Entry point name for arbitrary subsystem numbers.  */
    546   static const char default_entry[] = "mainCRTStartup";
    547 
    548   if (bfd_link_dll (&link_info) || dll)
    549     {
    550 #if defined (TARGET_IS_i386pe)
    551       entry = "DllMainCRTStartup@12";
    552 #else
    553       entry = "DllMainCRTStartup";
    554 #endif
    555     }
    556   else
    557     {
    558       for (i = 0; v[i].entry; i++)
    559 	if (v[i].value == pe_subsystem)
    560 	  break;
    561 
    562       /* If no match, use the default.  */
    563       if (v[i].entry != NULL)
    564 	entry = v[i].entry;
    565       else
    566 	entry = default_entry;
    567     }
    568 
    569   initial_symbol_char = (is_underscoring () != 0 ? "_" : "");
    570 
    571   if (*initial_symbol_char != '\0')
    572     {
    573       char *alc_entry;
    574 
    575       /* lang_default_entry expects its argument to be permanently
    576 	 allocated, so we don't free this string.  */
    577       alc_entry = xmalloc (strlen (initial_symbol_char)
    578 			   + strlen (entry)
    579 			   + 1);
    580       strcpy (alc_entry, initial_symbol_char);
    581       strcat (alc_entry, entry);
    582       entry = alc_entry;
    583     }
    584 
    585   lang_default_entry (entry);
    586 
    587   if (bfd_link_executable (&link_info) && ! entry_from_cmdline)
    588     ldlang_add_undef (entry, false);  
    589 }
    590 
    591 static void
    592 set_pe_subsystem (void)
    593 {
    594   const char *sver;
    595   char *end;
    596   int len;
    597   int i;
    598   unsigned long temp_subsystem;
    599   static const struct
    600     {
    601       const char *name;
    602       const int value;
    603     }
    604   v[] =
    605     {
    606       { "native",  1},
    607       { "windows", 2},
    608       { "console", 3},
    609       { "posix",   7},
    610       { "wince",   9},
    611       { "xbox",   14},
    612       { NULL, 0 }
    613     };
    614 
    615   /* Check for the presence of a version number.  */
    616   sver = strchr (optarg, ':');
    617   if (sver == NULL)
    618     len = strlen (optarg);
    619   else
    620     {
    621       len = sver - optarg;
    622       set_pe_name ("__major_subsystem_version__",
    623 		    strtoul (sver + 1, &end, 0));
    624       if (*end == '.')
    625 	set_pe_name ("__minor_subsystem_version__",
    626 		      strtoul (end + 1, &end, 0));
    627       if (*end != '\0')
    628 	einfo (_("%P: warning: bad version number in -subsystem option\n"));
    629     }
    630 
    631   /* Check for numeric subsystem.  */
    632   temp_subsystem = strtoul (optarg, & end, 0);
    633   if ((*end == ':' || *end == '\0') && (temp_subsystem < 65536))
    634     {
    635       /* Search list for a numeric match to use its entry point.  */
    636       for (i = 0; v[i].name; i++)
    637 	if (v[i].value == (int) temp_subsystem)
    638 	  break;
    639 
    640       /* Use this subsystem.  */
    641       pe_subsystem = (int) temp_subsystem;
    642     }
    643   else
    644     {
    645       /* Search for subsystem by name.  */
    646       for (i = 0; v[i].name; i++)
    647 	if (strncmp (optarg, v[i].name, len) == 0
    648 	    && v[i].name[len] == '\0')
    649 	  break;
    650 
    651       if (v[i].name == NULL)
    652 	{
    653 	  fatal (_("%P: invalid subsystem type %s\n"), optarg);
    654 	  return;
    655 	}
    656 
    657       pe_subsystem = v[i].value;
    658     }
    659 
    660   set_pe_name ("__subsystem__", pe_subsystem);
    661 
    662   return;
    663 }
    664 
    665 
    666 static void
    667 set_pe_value (char *name)
    668 {
    669   char *end;
    670 
    671   set_pe_name (name,  strtoul (optarg, &end, 0));
    672 
    673   if (end == optarg)
    674     fatal (_("%P: invalid hex number for PE parameter '%s'\n"), optarg);
    675 
    676   optarg = end;
    677 }
    678 
    679 
    680 static void
    681 set_pe_stack_heap (char *resname, char *comname)
    682 {
    683   set_pe_value (resname);
    684 
    685   if (*optarg == ',')
    686     {
    687       optarg++;
    688       set_pe_value (comname);
    689     }
    690   else if (*optarg)
    691     fatal (_("%P: strange hex info for PE parameter '%s'\n"), optarg);
    692 }
    693 
    694 #define DEFAULT_BUILD_ID_STYLE	"md5"
    695 
    696 static bool
    697 gld${EMULATION_NAME}_handle_option (int optc)
    698 {
    699   switch (optc)
    700     {
    701     default:
    702       return false;
    703 
    704     case OPTION_BASE_FILE:
    705       link_info.base_file = fopen (optarg, FOPEN_WB);
    706       if (link_info.base_file == NULL)
    707 	fatal (_("%P: cannot open base file %s\n"), optarg);
    708       break;
    709 
    710       /* PE options.  */
    711     case OPTION_HEAP:
    712       set_pe_stack_heap ("__size_of_heap_reserve__", "__size_of_heap_commit__");
    713       break;
    714     case OPTION_STACK:
    715       set_pe_stack_heap ("__size_of_stack_reserve__", "__size_of_stack_commit__");
    716       break;
    717     case OPTION_SUBSYSTEM:
    718       set_pe_subsystem ();
    719       break;
    720     case OPTION_MAJOR_OS_VERSION:
    721       set_pe_value ("__major_os_version__");
    722       break;
    723     case OPTION_MINOR_OS_VERSION:
    724       set_pe_value ("__minor_os_version__");
    725       break;
    726     case OPTION_MAJOR_SUBSYSTEM_VERSION:
    727       set_pe_value ("__major_subsystem_version__");
    728       break;
    729     case OPTION_MINOR_SUBSYSTEM_VERSION:
    730       set_pe_value ("__minor_subsystem_version__");
    731       break;
    732     case OPTION_MAJOR_IMAGE_VERSION:
    733       set_pe_value ("__major_image_version__");
    734       break;
    735     case OPTION_MINOR_IMAGE_VERSION:
    736       set_pe_value ("__minor_image_version__");
    737       break;
    738     case OPTION_FILE_ALIGNMENT:
    739       set_pe_value ("__file_alignment__");
    740       break;
    741     case OPTION_SECTION_ALIGNMENT:
    742       set_pe_value ("__section_alignment__");
    743       break;
    744     case OPTION_DLL:
    745       set_pe_name ("__dll__", 1);
    746       break;
    747     case OPTION_IMAGE_BASE:
    748       set_pe_value ("__image_base__");
    749       break;
    750     case OPTION_SUPPORT_OLD_CODE:
    751       support_old_code = 1;
    752       break;
    753     case OPTION_THUMB_ENTRY:
    754       thumb_entry_symbol = optarg;
    755       break;
    756     case OPTION_USE_NUL_PREFIXED_IMPORT_TABLES:
    757       pe_use_nul_prefixed_import_tables = true;
    758       break;
    759     case OPTION_NO_LEADING_UNDERSCORE:
    760       pe_leading_underscore = 0;
    761       break;
    762     case OPTION_LEADING_UNDERSCORE:
    763       pe_leading_underscore = 1;
    764       break;
    765     case OPTION_INSERT_TIMESTAMP:
    766       insert_timestamp = true;
    767       break;
    768     case OPTION_NO_INSERT_TIMESTAMP:
    769       insert_timestamp = false;
    770       break;
    771 #ifdef DLL_SUPPORT
    772     case OPTION_OUT_DEF:
    773       pe_out_def_filename = xstrdup (optarg);
    774       break;
    775     case OPTION_EXPORT_ALL:
    776       pe_dll_export_everything = 1;
    777       break;
    778     case OPTION_EXCLUDE_SYMBOLS:
    779       pe_dll_add_excludes (optarg, EXCLUDESYMS);
    780       break;
    781     case OPTION_EXCLUDE_ALL_SYMBOLS:
    782       pe_dll_exclude_all_symbols = 1;
    783       break;
    784     case OPTION_EXCLUDE_LIBS:
    785       pe_dll_add_excludes (optarg, EXCLUDELIBS);
    786       break;
    787     case OPTION_EXCLUDE_MODULES_FOR_IMPLIB:
    788       pe_dll_add_excludes (optarg, EXCLUDEFORIMPLIB);
    789       break;
    790     case OPTION_KILL_ATS:
    791       pe_dll_kill_ats = 1;
    792       break;
    793     case OPTION_STDCALL_ALIASES:
    794       pe_dll_stdcall_aliases = 1;
    795       break;
    796     case OPTION_ENABLE_STDCALL_FIXUP:
    797       pe_enable_stdcall_fixup = 1;
    798       break;
    799     case OPTION_DISABLE_STDCALL_FIXUP:
    800       pe_enable_stdcall_fixup = 0;
    801       break;
    802     case OPTION_WARN_DUPLICATE_EXPORTS:
    803       pe_dll_warn_dup_exports = 1;
    804       break;
    805     case OPTION_IMP_COMPAT:
    806       pe_dll_compat_implib = 1;
    807       break;
    808     case OPTION_ENABLE_AUTO_IMAGE_BASE:
    809       pe_enable_auto_image_base = 1;
    810       if (optarg && *optarg)
    811 	{
    812 	  char *end;
    813 	  pe_auto_image_base = strtoul (optarg, &end, 0);
    814 	  /* XXX should check that we actually parsed something */
    815 	}
    816       break;
    817     case OPTION_DISABLE_AUTO_IMAGE_BASE:
    818       pe_enable_auto_image_base = 0;
    819       break;
    820     case OPTION_DLL_SEARCH_PREFIX:
    821       pe_dll_search_prefix = xstrdup (optarg);
    822       break;
    823     case OPTION_NO_DEFAULT_EXCLUDES:
    824       pe_dll_do_default_excludes = 0;
    825       break;
    826     case OPTION_DLL_ENABLE_AUTO_IMPORT:
    827       link_info.pei386_auto_import = 1;
    828       break;
    829     case OPTION_DLL_DISABLE_AUTO_IMPORT:
    830       link_info.pei386_auto_import = 0;
    831       break;
    832     case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC:
    833       link_info.pei386_runtime_pseudo_reloc =
    834 	DEFAULT_PSEUDO_RELOC_VERSION;
    835       break;
    836     case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V1:
    837       link_info.pei386_runtime_pseudo_reloc = 1;
    838       break;
    839     case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2:
    840       link_info.pei386_runtime_pseudo_reloc = 2;
    841       break;
    842     case OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC:
    843       link_info.pei386_runtime_pseudo_reloc = 0;
    844       break;
    845     case OPTION_ENABLE_EXTRA_PE_DEBUG:
    846       pe_dll_extra_pe_debug = 1;
    847       break;
    848 #endif
    849     case OPTION_LARGE_ADDRESS_AWARE:
    850       real_flags |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
    851       break;
    852     case OPTION_DISABLE_LARGE_ADDRESS_AWARE:
    853       real_flags &= ~ IMAGE_FILE_LARGE_ADDRESS_AWARE;
    854       break;
    855     case OPTION_ENABLE_LONG_SECTION_NAMES:
    856       pe_use_coff_long_section_names = 1;
    857       break;
    858     case OPTION_DISABLE_LONG_SECTION_NAMES:
    859       pe_use_coff_long_section_names = 0;
    860       break;
    861 /*  Get DLLCharacteristics bits  */
    862     case OPTION_DYNAMIC_BASE:
    863       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
    864       /* fall through */
    865     case OPTION_ENABLE_RELOC_SECTION:
    866       pe_dll_enable_reloc_section = 1;
    867       break;
    868     case OPTION_DISABLE_RELOC_SECTION:
    869       pe_dll_enable_reloc_section = 0;
    870       /* fall through */
    871     case OPTION_DISABLE_DYNAMIC_BASE:
    872       pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
    873       break;
    874     case OPTION_FORCE_INTEGRITY:
    875       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
    876       break;
    877     case OPTION_DISABLE_FORCE_INTEGRITY:
    878       pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
    879       break;
    880     case OPTION_NX_COMPAT:
    881       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
    882       break;
    883     case OPTION_DISABLE_NX_COMPAT:
    884       pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
    885       break;
    886     case OPTION_NO_ISOLATION:
    887       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_ISOLATION;
    888       break;
    889     case OPTION_DISABLE_NO_ISOLATION:
    890       pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_ISOLATION;
    891       break;
    892     case OPTION_NO_SEH:
    893       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_SEH;
    894       break;
    895     case OPTION_DISABLE_NO_SEH:
    896       pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_SEH;
    897       break;
    898     case OPTION_NO_BIND:
    899       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_BIND;
    900       break;
    901     case OPTION_DISABLE_NO_BIND:
    902       pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_BIND;
    903       break;
    904     case OPTION_WDM_DRIVER:
    905       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_WDM_DRIVER;
    906       break;
    907     case OPTION_DISABLE_WDM_DRIVER:
    908       pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_WDM_DRIVER;
    909       break;
    910     case OPTION_TERMINAL_SERVER_AWARE:
    911       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
    912       break;
    913     case OPTION_DISABLE_TERMINAL_SERVER_AWARE:
    914       pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
    915       break;
    916     case OPTION_BUILD_ID:
    917       free ((char *) emit_build_id);
    918       emit_build_id = NULL;
    919       if (optarg == NULL)
    920 	optarg = DEFAULT_BUILD_ID_STYLE;
    921       if (strcmp (optarg, "none"))
    922 	emit_build_id = xstrdup (optarg);
    923       break;
    924 #ifdef PDB_H
    925     case OPTION_PDB:
    926       pdb = 1;
    927       if (optarg && optarg[0])
    928 	pdb_name = xstrdup (optarg);
    929       break;
    930 #endif
    931     }
    932 
    933   /*  Set DLLCharacteristics bits  */
    934   set_pe_name ("__dll_characteristics__", pe_dll_characteristics);
    935 
    936   return true;
    937 }
    938 
    940 
    941 #ifdef DLL_SUPPORT
    942 static unsigned long
    943 strhash (const char *str)
    944 {
    945   const unsigned char *s;
    946   unsigned long hash;
    947   unsigned int c;
    948   unsigned int len;
    949 
    950   hash = 0;
    951   len = 0;
    952   s = (const unsigned char *) str;
    953   while ((c = *s++) != '\0')
    954     {
    955       hash += c + (c << 17);
    956       hash ^= hash >> 2;
    957       ++len;
    958     }
    959   hash += len + (len << 17);
    960   hash ^= hash >> 2;
    961 
    962   return hash;
    963 }
    964 
    965 /* Use the output file to create a image base for relocatable DLLs.  */
    966 
    967 static unsigned long
    968 compute_dll_image_base (const char *ofile)
    969 {
    970   unsigned long hash = strhash (ofile);
    971   return pe_auto_image_base + ((hash << 16) & 0x0FFC0000);
    972 }
    973 #endif
    974 
    975 /* Assign values to the special symbols before the linker script is
    976    read.  */
    977 
    978 static void
    979 gld${EMULATION_NAME}_set_symbols (void)
    980 {
    981   /* Run through and invent symbols for all the
    982      names and insert the defaults.  */
    983   int j;
    984 
    985   is_underscoring ();
    986 
    987   if (!init[IMAGEBASEOFF].inited)
    988     {
    989       if (bfd_link_relocatable (&link_info))
    990 	init[IMAGEBASEOFF].value = 0;
    991       else if (init[DLLOFF].value || bfd_link_dll (&link_info))
    992 	{
    993 #ifdef DLL_SUPPORT
    994 	  init[IMAGEBASEOFF].value = (pe_enable_auto_image_base
    995 				      ? compute_dll_image_base (output_filename)
    996 				      : NT_DLL_IMAGE_BASE);
    997 #else
    998 	  init[IMAGEBASEOFF].value = NT_DLL_IMAGE_BASE;
    999 #endif
   1000 	}
   1001       else
   1002 	init[IMAGEBASEOFF].value = NT_EXE_IMAGE_BASE;
   1003       init[MSIMAGEBASEOFF].value = init[IMAGEBASEOFF].value;
   1004     }
   1005 
   1006   /* Don't do any symbol assignments if this is a relocatable link.  */
   1007   if (bfd_link_relocatable (&link_info))
   1008     return;
   1009 
   1010   /* Glue the assignments into the abs section.  */
   1011   push_stat_ptr (&abs_output_section->children);
   1012 
   1013   for (j = 0; init[j].ptr; j++)
   1014     {
   1015       long val = init[j].value;
   1016       lang_assignment_statement_type *rv;
   1017 
   1018       rv = lang_add_assignment (exp_assign (GET_INIT_SYMBOL_NAME (j),
   1019 					    exp_intop (val), false));
   1020       if (init[j].size == sizeof (short))
   1021 	*(short *) init[j].ptr = val;
   1022       else if (init[j].size == sizeof (int))
   1023 	*(int *) init[j].ptr = val;
   1024       else if (init[j].size == sizeof (long))
   1025 	*(long *) init[j].ptr = val;
   1026       /* This might be a long long or other special type.  */
   1027       else if (init[j].size == sizeof (bfd_vma))
   1028 	*(bfd_vma *) init[j].ptr = val;
   1029       else	abort ();
   1030       if (j == IMAGEBASEOFF)
   1031 	image_base_statement = rv;
   1032     }
   1033   /* Restore the pointer.  */
   1034   pop_stat_ptr ();
   1035 
   1036   if (pe.FileAlignment > pe.SectionAlignment)
   1037     {
   1038       einfo (_("%P: warning, file alignment > section alignment\n"));
   1039     }
   1040 }
   1041 
   1042 /* This is called after the linker script and the command line options
   1043    have been read.  */
   1044 
   1045 static void
   1046 gld${EMULATION_NAME}_after_parse (void)
   1047 {
   1048   /* PR ld/6744:  Warn the user if they have used an ELF-only
   1049      option hoping it will work on PE.  */
   1050   if (link_info.export_dynamic)
   1051     einfo (_("%P: warning: --export-dynamic is not supported for PE "
   1052       "targets, did you mean --export-all-symbols?\n"));
   1053 
   1054 #ifdef PDB_H
   1055   if (pdb && emit_build_id == NULL)
   1056     emit_build_id = xstrdup (DEFAULT_BUILD_ID_STYLE);
   1057 #endif
   1058 
   1059   set_entry_point ();
   1060 
   1061   after_parse_default ();
   1062 }
   1063 
   1064 #ifdef DLL_SUPPORT
   1065 static struct bfd_link_hash_entry *pe_undef_found_sym;
   1066 
   1067 static bool
   1068 pe_undef_cdecl_match (struct bfd_link_hash_entry *h, void *inf)
   1069 {
   1070   int sl;
   1071   char *string = inf;
   1072   const char *hs = h->root.string;
   1073 
   1074   sl = strlen (string);
   1075   if (h->type == bfd_link_hash_defined
   1076       && ((*hs == '@' && *string == '_'
   1077 		   && strncmp (hs + 1, string + 1, sl - 1) == 0)
   1078 		  || strncmp (hs, string, sl) == 0)
   1079       && h->root.string[sl] == '@')
   1080     {
   1081       pe_undef_found_sym = h;
   1082       return false;
   1083     }
   1084   return true;
   1085 }
   1086 
   1087 /* Change UNDEF to a defined symbol, taking data from SYM.  */
   1088 
   1089 static void
   1090 change_undef (struct bfd_link_hash_entry * undef,
   1091 	      struct bfd_link_hash_entry * sym)
   1092 {
   1093   static bool  gave_warning_message = false;
   1094 
   1095   undef->type = bfd_link_hash_defined;
   1096   undef->u.def.value = sym->u.def.value;
   1097   undef->u.def.section = sym->u.def.section;
   1098 
   1099   if (pe_enable_stdcall_fixup == -1)
   1100     {
   1101       einfo (_("%P: warning: resolving %s by linking to %s\n"),
   1102 	     undef->root.string, sym->root.string);
   1103 
   1104       if (! gave_warning_message)
   1105 	{
   1106 	  einfo (_("Use --enable-stdcall-fixup to disable these warnings\n"));
   1107 	  einfo (_("Use --disable-stdcall-fixup to disable these fixups\n"));
   1108 	  gave_warning_message = true;
   1109 	}
   1110     }
   1111 
   1112   /* PR 19803: Make sure that the linked symbol is not garbage collected.  */
   1113   lang_add_gc_name (sym->root.string);
   1114 }
   1115 
   1116 static void
   1117 set_decoration (const char *undecorated_name,
   1118 		struct bfd_link_hash_entry * decoration)
   1119 {
   1120   static bool  gave_warning_message = false;
   1121   struct decoration_hash_entry *entry;
   1122 
   1123   if (is_underscoring () && undecorated_name[0] == '_')
   1124     undecorated_name++;
   1125 
   1126   entry = (struct decoration_hash_entry *)
   1127 	  bfd_hash_lookup (&(coff_hash_table (&link_info)->decoration_hash),
   1128 			   undecorated_name, true /* create */, false /* copy */);
   1129 
   1130   if (entry->decorated_link != NULL && !gave_warning_message)
   1131     {
   1132       einfo (_("%P: warning: overwriting decorated name %s with %s\n"),
   1133 	     entry->decorated_link->root.string, undecorated_name);
   1134       gave_warning_message = true;
   1135     }
   1136 
   1137   entry->decorated_link = decoration;
   1138 }
   1139 
   1140 static void
   1141 pe_fixup_stdcalls (void)
   1142 {
   1143   struct bfd_link_hash_entry *undef, *sym;
   1144 
   1145   if (pe_dll_extra_pe_debug)
   1146     printf ("%s\n", __func__);
   1147 
   1148   for (undef = link_info.hash->undefs; undef; undef=undef->u.undef.next)
   1149     if (undef->type == bfd_link_hash_undefined)
   1150       {
   1151 	const char * name = undef->root.string;
   1152 	char * at;
   1153 	int lead_at = (*name == '@');
   1154 
   1155 	if (lead_at)
   1156 	  at = strchr (name + 1, '@');
   1157 	else
   1158 	  at = strchr (name, '@');
   1159 
   1160 	if (at || lead_at)
   1161 	  {
   1162 	    /* The symbol is a stdcall symbol, so let's look for a
   1163 	       cdecl symbol with the same name and resolve to that.  */
   1164 	    char *cname = xstrdup (name);
   1165 
   1166 	    if (lead_at)
   1167 	      *cname = '_';
   1168 	    if (at)
   1169 	      * strchr (cname, '@') = 0;
   1170 	    sym = bfd_link_hash_lookup (link_info.hash, cname, false, false, true);
   1171 
   1172 	    if (sym && sym->type == bfd_link_hash_defined)
   1173 	      change_undef (undef, sym);
   1174 	  }
   1175 	else
   1176 	  {
   1177 	    /* The symbol is a cdecl symbol, so we look for stdcall
   1178 	       symbols - which means scanning the whole symbol table.  */
   1179 	    pe_undef_found_sym = NULL;
   1180 	    bfd_link_hash_traverse (link_info.hash, pe_undef_cdecl_match,
   1181 				    (char *) name);
   1182 	    if (pe_undef_found_sym)
   1183 	      {
   1184 		change_undef (undef, pe_undef_found_sym);
   1185 		set_decoration (undef->root.string, pe_undef_found_sym);
   1186 	      }
   1187 	  }
   1188       }
   1189 }
   1190 
   1191 static bfd_vma
   1192 read_addend (arelent *rel, asection *s)
   1193 {
   1194   char buf[4];
   1195   bfd_vma addend = 0;
   1196 
   1197   if (!bfd_get_section_contents (s->owner, s, buf, rel->address, sizeof (buf)))
   1198     einfo (_("%P: %H: cannot get section contents - auto-import exception\n"),
   1199 	   s->owner, s, rel->address);
   1200   else
   1201     addend = bfd_get_32 (s->owner, buf);
   1202   return addend;
   1203 }
   1204 
   1205 static void
   1206 make_import_fixup (arelent *rel, asection *s, char *name, const char *symname)
   1207 {
   1208   struct bfd_symbol *sym = *rel->sym_ptr_ptr;
   1209   bfd_vma addend;
   1210 
   1211   if (pe_dll_extra_pe_debug)
   1212     printf ("arelent: %s@%#lx: add=%li\n", sym->name,
   1213 	    (unsigned long) rel->address, (long) rel->addend);
   1214 
   1215   addend = read_addend (rel, s);
   1216 
   1217   if (pe_dll_extra_pe_debug)
   1218     {
   1219       printf ("import of 0x%lx(0x%lx) sec_addr=0x%lx",
   1220 	      (long) addend, (long) rel->addend, (long) rel->address);
   1221       if (rel->howto->pc_relative)
   1222 	printf (" pcrel");
   1223       printf (" %d bit rel.\n", (int) rel->howto->bitsize);
   1224     }
   1225 
   1226   pe_create_import_fixup (rel, s, addend, name, symname);
   1227 }
   1228 
   1229 static void
   1230 make_runtime_ref (void)
   1231 {
   1232   const char *rr = U ("_pei386_runtime_relocator");
   1233   struct bfd_link_hash_entry *h
   1234     = bfd_wrapped_link_hash_lookup (link_info.output_bfd, &link_info,
   1235 				    rr, true, false, true);
   1236   if (!h)
   1237     fatal (_("%P: bfd_link_hash_lookup failed: %E\n"));
   1238   else
   1239     {
   1240       if (h->type == bfd_link_hash_new)
   1241 	{
   1242 	  h->type = bfd_link_hash_undefined;
   1243 	  h->u.undef.abfd = NULL;
   1244 	  if (h->u.undef.next == NULL && h != link_info.hash->undefs_tail)
   1245 	    bfd_link_add_undef (link_info.hash, h);
   1246 	}
   1247       h->non_ir_ref_regular = true;
   1248     }
   1249 }
   1250 
   1251 static bool
   1252 pr_sym (struct bfd_hash_entry *h, void *inf ATTRIBUTE_UNUSED)
   1253 {
   1254   printf ("+%s\n", h->string);
   1255 
   1256   return true;
   1257 }
   1258 #endif /* DLL_SUPPORT */
   1259 
   1260 static void
   1261 debug_section_p (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
   1262 {
   1263   int *found = (int *) obj;
   1264   if (strncmp (".debug_", sect->name, sizeof (".debug_") - 1) == 0)
   1265     *found = 1;
   1266 }
   1267 
   1268 static bool
   1269 pecoff_checksum_contents (bfd *abfd,
   1270 			  void (*process) (const void *, size_t, void *),
   1271 			  void *arg)
   1272 {
   1273   file_ptr filepos = (file_ptr) 0;
   1274 
   1275   while (1)
   1276     {
   1277       unsigned char b;
   1278       int status;
   1279 
   1280       if (bfd_seek (abfd, filepos, SEEK_SET) != 0)
   1281 	return 0;
   1282 
   1283       status = bfd_read (&b, 1, abfd);
   1284       if (status < 1)
   1285 	{
   1286 	  break;
   1287 	}
   1288 
   1289       (*process) (&b, 1, arg);
   1290       filepos += 1;
   1291     }
   1292 
   1293   return true;
   1294 }
   1295 
   1296 static bool
   1297 write_build_id (bfd *abfd)
   1298 {
   1299   struct pe_tdata *td = pe_data (abfd);
   1300   asection *asec;
   1301   struct bfd_link_order *link_order = NULL;
   1302   unsigned char *contents;
   1303   bfd_size_type build_id_size;
   1304   unsigned char *build_id;
   1305   const char *pdb_base_name = NULL;
   1306 
   1307   /* Find the section the .buildid output section has been merged info.  */
   1308   for (asec = abfd->sections; asec != NULL; asec = asec->next)
   1309     {
   1310       struct bfd_link_order *l = NULL;
   1311       for (l = asec->map_head.link_order; l != NULL; l = l->next)
   1312 	{
   1313 	  if (l->type == bfd_indirect_link_order)
   1314 	    {
   1315 	      if (l->u.indirect.section == td->build_id.sec)
   1316 		{
   1317 		  link_order = l;
   1318 		  break;
   1319 		}
   1320 	    }
   1321 	}
   1322 
   1323       if (link_order)
   1324 	break;
   1325     }
   1326 
   1327   if (!link_order)
   1328     {
   1329       einfo (_("%P: warning: .buildid section discarded,"
   1330 	       " --build-id ignored\n"));
   1331       return true;
   1332     }
   1333 
   1334   if (td->build_id.sec->contents == NULL)
   1335     td->build_id.sec->contents = xmalloc (td->build_id.sec->size);
   1336   contents = td->build_id.sec->contents;
   1337 
   1338   build_id_size = compute_build_id_size (td->build_id.style);
   1339   build_id = xmalloc (build_id_size);
   1340   generate_build_id (abfd, td->build_id.style, pecoff_checksum_contents,
   1341 		     build_id, build_id_size);
   1342 
   1343   bfd_vma ib = td->pe_opthdr.ImageBase;
   1344 
   1345 #ifdef PDB_H
   1346   if (pdb_name)
   1347     pdb_base_name = lbasename (pdb_name);
   1348 #endif
   1349 
   1350   /* Construct a debug directory entry which points to an immediately following CodeView record.  */
   1351   struct internal_IMAGE_DEBUG_DIRECTORY idd;
   1352   idd.Characteristics = 0;
   1353   idd.TimeDateStamp = 0;
   1354   idd.MajorVersion = 0;
   1355   idd.MinorVersion = 0;
   1356   idd.Type = PE_IMAGE_DEBUG_TYPE_CODEVIEW;
   1357   idd.SizeOfData = (sizeof (CV_INFO_PDB70)
   1358 #ifdef PDB_H
   1359 		    + (pdb_base_name ? strlen (pdb_base_name) : 0)
   1360 #endif
   1361 		    + 1);
   1362   idd.AddressOfRawData = asec->vma - ib + link_order->offset
   1363     + sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
   1364   idd.PointerToRawData = asec->filepos + link_order->offset
   1365     + sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
   1366 
   1367   struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *)contents;
   1368   _bfd_XXi_swap_debugdir_out (abfd, &idd, ext);
   1369 
   1370   /* Write the debug directory entry.  */
   1371   if (bfd_seek (abfd, asec->filepos + link_order->offset, SEEK_SET) != 0)
   1372     return 0;
   1373 
   1374   if (bfd_write (contents, sizeof (*ext), abfd) != sizeof (*ext))
   1375     return 0;
   1376 
   1377 #ifdef PDB_H
   1378   if (pdb)
   1379     {
   1380       if (!create_pdb_file (abfd, pdb_name, build_id))
   1381 	return 0;
   1382     }
   1383 #endif
   1384 
   1385   /* Construct the CodeView record.  */
   1386   CODEVIEW_INFO cvinfo;
   1387   cvinfo.CVSignature = CVINFO_PDB70_CVSIGNATURE;
   1388   cvinfo.Age = 1;
   1389 
   1390   /* Zero pad or truncate the generated build_id to fit in the
   1391      CodeView record.  */
   1392   memset (&(cvinfo.Signature), 0, CV_INFO_SIGNATURE_LENGTH);
   1393   memcpy (&(cvinfo.Signature), build_id,
   1394 	  (build_id_size > CV_INFO_SIGNATURE_LENGTH
   1395 	   ? CV_INFO_SIGNATURE_LENGTH : build_id_size));
   1396 
   1397   free (build_id);
   1398 
   1399   /* Write the codeview record.  */
   1400   if (_bfd_XXi_write_codeview_record (abfd, idd.PointerToRawData, &cvinfo,
   1401 				      pdb_base_name) == 0)
   1402     return 0;
   1403 
   1404   /* Record the location of the debug directory in the data directory.  */
   1405   td->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
   1406     = asec->vma - ib + link_order->offset;
   1407   td->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
   1408     = sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
   1409 
   1410   return true;
   1411 }
   1412 
   1413 /* Make .buildid section, and set up coff_tdata->build_id. */
   1414 static bool
   1415 setup_build_id (bfd *ibfd)
   1416 {
   1417   asection *s;
   1418   flagword flags;
   1419 
   1420   if (!validate_build_id_style (emit_build_id))
   1421     {
   1422       einfo (_("%P: warning: unrecognized --build-id style ignored\n"));
   1423       return false;
   1424     }
   1425 
   1426   flags = (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
   1427 	   | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
   1428   s = bfd_make_section_anyway_with_flags (ibfd, ".buildid", flags);
   1429   if (s != NULL)
   1430     {
   1431       struct pe_tdata *td = pe_data (link_info.output_bfd);
   1432       td->build_id.after_write_object_contents = &write_build_id;
   1433       td->build_id.style = emit_build_id;
   1434       td->build_id.sec = s;
   1435 
   1436       /* Section is a fixed size:
   1437 	 One IMAGE_DEBUG_DIRECTORY entry, of type IMAGE_DEBUG_TYPE_CODEVIEW,
   1438 	 pointing at a CV_INFO_PDB70 record containing the build-id, followed by
   1439 	 PdbFileName if relevant.  */
   1440       s->size = (sizeof (struct external_IMAGE_DEBUG_DIRECTORY)
   1441 		 + sizeof (CV_INFO_PDB70) + 1);
   1442 
   1443 #ifdef PDB_H
   1444       if (pdb_name)
   1445 	s->size += strlen (lbasename (pdb_name));
   1446 #endif
   1447       return true;
   1448     }
   1449 
   1450   einfo (_("%P: warning: cannot create .buildid section,"
   1451 	   " --build-id ignored\n"));
   1452   return false;
   1453 }
   1454 
   1455 static void
   1456 gld${EMULATION_NAME}_before_plugin_all_symbols_read (void)
   1457 {
   1458 #ifdef DLL_SUPPORT
   1459   if (link_info.lto_plugin_active
   1460       && link_info.pei386_auto_import)
   1461     make_runtime_ref ();
   1462 #endif
   1463 }
   1464 
   1465 static void
   1466 gld${EMULATION_NAME}_after_open (void)
   1467 {
   1468   after_open_default ();
   1469 
   1470 #ifdef DLL_SUPPORT
   1471   if (pe_dll_extra_pe_debug)
   1472     {
   1473       bfd *a;
   1474       struct bfd_link_hash_entry *sym;
   1475 
   1476       printf ("%s()\n", __func__);
   1477 
   1478       for (sym = link_info.hash->undefs; sym; sym=sym->u.undef.next)
   1479 	printf ("-%s\n", sym->root.string);
   1480       bfd_hash_traverse (&link_info.hash->table, pr_sym, NULL);
   1481 
   1482       for (a = link_info.input_bfds; a; a = a->link.next)
   1483 	printf ("*%s\n", bfd_get_filename (a));
   1484     }
   1485 #endif
   1486 
   1487 #ifdef PDB_H
   1488   if (pdb && !pdb_name)
   1489     {
   1490       const char *base = lbasename (bfd_get_filename (link_info.output_bfd));
   1491       size_t len = strlen (base);
   1492       static const char suffix[] = ".pdb";
   1493 
   1494       while (len > 0 && base[len] != '.')
   1495 	{
   1496 	  len--;
   1497 	}
   1498 
   1499       if (len == 0)
   1500 	len = strlen (base);
   1501 
   1502       pdb_name = xmalloc (len + sizeof (suffix));
   1503       memcpy (pdb_name, base, len);
   1504       memcpy (pdb_name + len, suffix, sizeof (suffix));
   1505     }
   1506 #endif
   1507 
   1508   if (emit_build_id != NULL)
   1509     {
   1510       bfd *abfd;
   1511 
   1512       /* Find a COFF input.  */
   1513       for (abfd = link_info.input_bfds;
   1514 	   abfd != (bfd *) NULL; abfd = abfd->link.next)
   1515 	if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
   1516 	  break;
   1517 
   1518       /* If there are no COFF input files do not try to
   1519 	 add a build-id section.  */
   1520       if (abfd == NULL
   1521 	  || !setup_build_id (abfd))
   1522 	{
   1523 	  free ((char *) emit_build_id);
   1524 	  emit_build_id = NULL;
   1525 	}
   1526     }
   1527 
   1528   /* Pass the wacky PE command line options into the output bfd.
   1529      FIXME: This should be done via a function, rather than by
   1530      including an internal BFD header.  */
   1531 
   1532   if (bfd_get_flavour (link_info.output_bfd) != bfd_target_coff_flavour
   1533       || coff_data (link_info.output_bfd) == NULL
   1534       || !obj_pe (link_info.output_bfd))
   1535     fatal (_("%P: cannot perform PE operations on non PE output file '%pB'\n"),
   1536 	   link_info.output_bfd);
   1537 
   1538   pe_data (link_info.output_bfd)->pe_opthdr = pe;
   1539   pe_data (link_info.output_bfd)->dll = init[DLLOFF].value;
   1540   pe_data (link_info.output_bfd)->real_flags |= real_flags;
   1541   if (insert_timestamp)
   1542     pe_data (link_info.output_bfd)->timestamp = -1;
   1543   else
   1544     pe_data (link_info.output_bfd)->timestamp = 0;
   1545 
   1546   /* At this point we must decide whether to use long section names
   1547      in the output or not.  If the user hasn't explicitly specified
   1548      on the command line, we leave it to the default for the format
   1549      (object files yes, image files no), except if there is debug
   1550      information present; GDB relies on the long section names to
   1551      find it, so enable it in that case.  */
   1552   if (pe_use_coff_long_section_names < 0 && link_info.strip == strip_none)
   1553     {
   1554       if (bfd_link_relocatable (&link_info))
   1555 	pe_use_coff_long_section_names = 1;
   1556       else
   1557 	{
   1558 	  /* Iterate over all sections of all input BFDs, checking
   1559 	     for any that begin 'debug_' and are long names.  */
   1560 	  LANG_FOR_EACH_INPUT_STATEMENT (is)
   1561 	  {
   1562 	    int found_debug = 0;
   1563 
   1564 	    bfd_map_over_sections (is->the_bfd, debug_section_p, &found_debug);
   1565 	    if (found_debug)
   1566 	      {
   1567 		pe_use_coff_long_section_names = 1;
   1568 		break;
   1569 	      }
   1570 	  }
   1571 	}
   1572     }
   1573 
   1574   pe_output_file_set_long_section_names (link_info.output_bfd);
   1575 
   1576 #ifdef DLL_SUPPORT
   1577   pe_process_import_defs (link_info.output_bfd, &link_info);
   1578 
   1579   if (link_info.pei386_auto_import) /* -1=warn or 1=enable */
   1580     pe_find_data_imports (U ("_head_"), make_import_fixup);
   1581 
   1582   /* The implementation of the feature is rather dumb and would cause the
   1583      compilation time to go through the roof if there are many undefined
   1584      symbols in the link, so it needs to be run after auto-import.  */
   1585   if (pe_enable_stdcall_fixup) /* -1=warn or 1=enable */
   1586     pe_fixup_stdcalls ();
   1587 
   1588 #if defined (TARGET_IS_i386pe) \
   1589     || defined (TARGET_IS_armpe) \
   1590     || defined (TARGET_IS_arm_wince_pe)
   1591   if (!bfd_link_relocatable (&link_info))
   1592     pe_dll_build_sections (link_info.output_bfd, &link_info);
   1593 #else
   1594   if (bfd_link_pic (&link_info))
   1595     pe_dll_build_sections (link_info.output_bfd, &link_info);
   1596   else
   1597     pe_exe_build_sections (link_info.output_bfd, &link_info);
   1598 #endif
   1599 #endif /* DLL_SUPPORT */
   1600 
   1601 #if defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_wince_pe)
   1602   if (strstr (bfd_get_target (link_info.output_bfd), "arm") == NULL)
   1603     {
   1604       /* The arm backend needs special fields in the output hash structure.
   1605 	 These will only be created if the output format is an arm format,
   1606 	 hence we do not support linking and changing output formats at the
   1607 	 same time.  Use a link followed by objcopy to change output formats.  */
   1608       fatal (_("%P: error: cannot change output format "
   1609 	       "whilst linking %s binaries\n"), "ARM");
   1610       return;
   1611     }
   1612   {
   1613     /* Find a BFD that can hold the interworking stubs.  */
   1614     LANG_FOR_EACH_INPUT_STATEMENT (is)
   1615       {
   1616 	if (bfd_arm_get_bfd_for_interworking (is->the_bfd, & link_info))
   1617 	  break;
   1618       }
   1619   }
   1620 #endif
   1621 
   1622   {
   1623     /* This next chunk of code tries to detect the case where you have
   1624        two import libraries for the same DLL (specifically,
   1625        symbolically linking libm.a and libc.a in cygwin to
   1626        libcygwin.a).  In those cases, it's possible for function
   1627        thunks from the second implib to be used but without the
   1628        head/tail objects, causing an improper import table.  We detect
   1629        those cases and rename the "other" import libraries to match
   1630        the one the head/tail come from, so that the linker will sort
   1631        things nicely and produce a valid import table.  */
   1632 
   1633     LANG_FOR_EACH_INPUT_STATEMENT (is)
   1634       {
   1635 	if (is->the_bfd->my_archive)
   1636 	  {
   1637 	    int idata2 = 0, reloc_count=0, is_imp = 0;
   1638 	    asection *sec;
   1639 
   1640 	    /* See if this is an import library thunk.  */
   1641 	    for (sec = is->the_bfd->sections; sec; sec = sec->next)
   1642 	      {
   1643 		if (strcmp (sec->name, ".idata\$2") == 0)
   1644 		  idata2 = 1;
   1645 		if (startswith (sec->name, ".idata\$"))
   1646 		  is_imp = 1;
   1647 		reloc_count += sec->reloc_count;
   1648 	      }
   1649 
   1650 	    if (is_imp && !idata2 && reloc_count)
   1651 	      {
   1652 		/* It is, look for the reference to head and see if it's
   1653 		   from our own library.  */
   1654 		for (sec = is->the_bfd->sections; sec; sec = sec->next)
   1655 		  {
   1656 		    int i;
   1657 		    long relsize;
   1658 		    asymbol **symbols;
   1659 		    arelent **relocs;
   1660 		    int nrelocs;
   1661 
   1662 		    relsize = bfd_get_reloc_upper_bound (is->the_bfd, sec);
   1663 		    if (relsize < 1)
   1664 		      break;
   1665 
   1666 		    if (!bfd_generic_link_read_symbols (is->the_bfd))
   1667 		      {
   1668 			fatal (_("%P: %pB: could not read symbols: %E\n"),
   1669 			       is->the_bfd);
   1670 			return;
   1671 		      }
   1672 		    symbols = bfd_get_outsymbols (is->the_bfd);
   1673 
   1674 		    relocs = xmalloc ((size_t) relsize);
   1675 		    nrelocs = bfd_canonicalize_reloc (is->the_bfd, sec,
   1676 						      relocs, symbols);
   1677 		    if (nrelocs < 0)
   1678 		      {
   1679 			free (relocs);
   1680 			einfo (_("%X%P: unable to process relocs: %E\n"));
   1681 			return;
   1682 		      }
   1683 
   1684 		    for (i = 0; i < nrelocs; i++)
   1685 		      {
   1686 			struct bfd_symbol *s;
   1687 			struct bfd_link_hash_entry * blhe;
   1688 			bfd *other_bfd;
   1689 			const char *other_bfd_filename;
   1690 
   1691 			s = (relocs[i]->sym_ptr_ptr)[0];
   1692 
   1693 			if (s->flags & BSF_LOCAL)
   1694 			  continue;
   1695 
   1696 			/* Thunk section with reloc to another bfd.  */
   1697 			blhe = bfd_link_hash_lookup (link_info.hash,
   1698 						     s->name,
   1699 						     false, false, true);
   1700 
   1701 			if (blhe == NULL
   1702 			    || blhe->type != bfd_link_hash_defined)
   1703 			  continue;
   1704 
   1705 			other_bfd = blhe->u.def.section->owner;
   1706 			if (other_bfd->my_archive == is->the_bfd->my_archive)
   1707 			  continue;
   1708 
   1709 			other_bfd_filename
   1710 			  = (other_bfd->my_archive
   1711 			     ? bfd_get_filename (other_bfd->my_archive)
   1712 			     : bfd_get_filename (other_bfd));
   1713 
   1714 			if (filename_cmp (bfd_get_filename
   1715 					    (is->the_bfd->my_archive),
   1716 					  other_bfd_filename) == 0)
   1717 			  continue;
   1718 
   1719 			/* Sort this implib to match the other one.  */
   1720 			lang_input_statement_type *arch_is
   1721 			  = bfd_usrdata (is->the_bfd->my_archive);
   1722 			arch_is->sort_key = other_bfd_filename;
   1723 			break;
   1724 		      }
   1725 
   1726 		    free (relocs);
   1727 		    /* Note - we do not free the symbols,
   1728 		       they are now cached in the BFD.  */
   1729 		  }
   1730 	      }
   1731 	  }
   1732       }
   1733   }
   1734 
   1735   {
   1736 
   1737     /* Careful - this is a shell script.  Watch those dollar signs! */
   1738     /* Microsoft import libraries have every member named the same,
   1739        and not in the right order for us to link them correctly.  We
   1740        must detect these and rename the members so that they'll link
   1741        correctly.  There are three types of objects: the head, the
   1742        thunks, and the sentinel(s).  The head is easy; it's the one
   1743        with idata2.  We assume that the sentinels won't have relocs,
   1744        and the thunks will.  It's easier than checking the symbol
   1745        table for external references.  */
   1746     LANG_FOR_EACH_INPUT_STATEMENT (is)
   1747       {
   1748 	if (is->the_bfd->my_archive)
   1749 	  {
   1750 	    char *pnt;
   1751 
   1752 	    /* Microsoft import libraries may contain archive members for
   1753 	       one or more DLLs, together with static object files.
   1754 	       The head and sentinels are regular COFF object files,
   1755 	       while the thunks are special ILF files that get synthesized
   1756 	       by bfd into COFF object files.
   1757 
   1758 	       As Microsoft import libraries can be for a module with
   1759 	       almost any file name (*.dll, *.exe, etc), we can't easily
   1760 	       know which archive members to inspect.
   1761 
   1762 	       Inspect all members, except ones named *.o or *.obj (which
   1763 	       is the case both for regular static libraries or for GNU
   1764 	       style import libraries). Archive members with file names other
   1765 	       than *.o or *.obj, that do contain .idata sections, are
   1766 	       considered to be Microsoft style import objects, and are
   1767 	       renamed accordingly.
   1768 
   1769 	       If this heuristic is wrong and we apply this on archive members
   1770 	       that already have unique names, it shouldn't make any difference
   1771 	       as we only append a suffix on the names.  */
   1772 	    pnt = strrchr (bfd_get_filename (is->the_bfd), '.');
   1773 
   1774 	    if (pnt != NULL && (fileext_cmp (pnt + 1, "o") != 0 &&
   1775 				fileext_cmp (pnt + 1, "obj") != 0))
   1776 	      {
   1777 		int idata2 = 0, reloc_count = 0, idata = 0;
   1778 		asection *sec;
   1779 		char *new_name, seq;
   1780 
   1781 		for (sec = is->the_bfd->sections; sec; sec = sec->next)
   1782 		  {
   1783 		    if (strcmp (sec->name, ".idata\$2") == 0)
   1784 		      idata2 = 1;
   1785 		    if (strncmp (sec->name, ".idata\$", 6) == 0)
   1786 		      idata = 1;
   1787 		    reloc_count += sec->reloc_count;
   1788 		  }
   1789 
   1790 		/* An archive member not named .o or .obj, but not having any
   1791 		   .idata sections - apparently not a Microsoft import object
   1792 		   after all: Skip renaming it.  */
   1793 		if (!idata)
   1794 		  continue;
   1795 
   1796 		if (idata2) /* .idata2 is the TOC */
   1797 		  seq = 'a';
   1798 		else if (reloc_count > 0) /* thunks */
   1799 		  seq = 'b';
   1800 		else /* sentinel */
   1801 		  seq = 'c';
   1802 
   1803 		new_name
   1804 		  = xmalloc (strlen (bfd_get_filename (is->the_bfd)) + 3);
   1805 		sprintf (new_name, "%s.%c",
   1806 			 bfd_get_filename (is->the_bfd), seq);
   1807 		is->sort_key = new_name;
   1808 	      }
   1809 	  }
   1810       }
   1811   }
   1812 
   1813   {
   1814     /* The following chunk of code tries to identify jump stubs in
   1815        import libraries which are dead code and eliminates them
   1816        from the final link. For each exported symbol <sym>, there
   1817        is a object file in the import library with a .text section
   1818        and several .idata\$* sections. The .text section contains the
   1819        symbol definition for <sym> which is a jump stub of the form
   1820        jmp *__imp_<sym>. The .idata\$5 contains the symbol definition
   1821        for __imp_<sym> which is the address of the slot for <sym> in
   1822        the import address table. When a symbol is imported explicitly
   1823        using __declspec(dllimport) declaration, the compiler generates
   1824        a reference to __imp_<sym> which directly resolves to the
   1825        symbol in .idata\$5, in which case the jump stub code is not
   1826        needed. The following code tries to identify jump stub sections
   1827        in import libraries which are not referred to by anyone and
   1828        marks them for exclusion from the final link.  */
   1829     LANG_FOR_EACH_INPUT_STATEMENT (is)
   1830       {
   1831 	if (is->the_bfd->my_archive)
   1832 	  {
   1833 	    int is_imp = 0;
   1834 	    asection *sec, *stub_sec = NULL;
   1835 
   1836 	    /* See if this is an import library thunk.  */
   1837 	    for (sec = is->the_bfd->sections; sec; sec = sec->next)
   1838 	      {
   1839 		if (strncmp (sec->name, ".idata\$", 7) == 0)
   1840 		  is_imp = 1;
   1841 		/* The section containing the jmp stub has code
   1842 		   and has a reloc.  */
   1843 		if ((sec->flags & SEC_CODE) && sec->reloc_count)
   1844 		  stub_sec = sec;
   1845 	      }
   1846 
   1847 	    if (is_imp && stub_sec)
   1848 	      {
   1849 		asymbol **symbols;
   1850 		long nsyms, src_count;
   1851 		struct bfd_link_hash_entry * blhe;
   1852 
   1853 		if (!bfd_generic_link_read_symbols (is->the_bfd))
   1854 		  {
   1855 		    fatal (_("%P: %pB: could not read symbols: %E\n"),
   1856 			   is->the_bfd);
   1857 		    return;
   1858 		  }
   1859 		symbols = bfd_get_outsymbols (is->the_bfd);
   1860 		nsyms = bfd_get_symcount (is->the_bfd);
   1861 
   1862 		for (src_count = 0; src_count < nsyms; src_count++)
   1863 		  {
   1864 		    if (symbols[src_count]->section->id == stub_sec->id)
   1865 		      {
   1866 			/* This symbol belongs to the section containing
   1867 			   the stub.  */
   1868 			blhe = bfd_link_hash_lookup (link_info.hash,
   1869 						     symbols[src_count]->name,
   1870 						     false, false, true);
   1871 			/* If the symbol in the stub section has no other
   1872 			   undefined references, exclude the stub section
   1873 			   from the final link.  */
   1874 			if (blhe != NULL
   1875 			    && blhe->type == bfd_link_hash_defined
   1876 			    && blhe->u.undef.next == NULL
   1877 			    && blhe != link_info.hash->undefs_tail)
   1878 			  stub_sec->flags |= SEC_EXCLUDE;
   1879 		      }
   1880 		  }
   1881 	      }
   1882 	  }
   1883       }
   1884   }
   1885 }
   1886 
   1888 static void
   1889 gld${EMULATION_NAME}_before_allocation (void)
   1890 {
   1891 #if defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_wince_pe)
   1892   /* FIXME: we should be able to set the size of the interworking stub
   1893      section.
   1894 
   1895      Here we rummage through the found bfds to collect glue
   1896      information.  FIXME: should this be based on a command line
   1897      option?  krk (a] cygnus.com.  */
   1898   {
   1899     LANG_FOR_EACH_INPUT_STATEMENT (is)
   1900       {
   1901 	if (! bfd_arm_process_before_allocation
   1902 	    (is->the_bfd, & link_info, support_old_code))
   1903 	  {
   1904 	    /* xgettext:c-format */
   1905 	    einfo (_("%P: errors encountered processing file %s for interworking\n"),
   1906 		   is->filename);
   1907 	  }
   1908       }
   1909   }
   1910 
   1911   /* We have seen it all. Allocate it, and carry on.  */
   1912   bfd_arm_allocate_interworking_sections (& link_info);
   1913 #endif /* TARGET_IS_armpe || TARGET_IS_arm_wince_pe */
   1914 
   1915   before_allocation_default ();
   1916 }
   1917 
   1919 #ifdef DLL_SUPPORT
   1920 /* This is called when an input file isn't recognized as a BFD.  We
   1921    check here for .DEF files and pull them in automatically.  */
   1922 
   1923 static int
   1924 saw_option (char *option)
   1925 {
   1926   int i;
   1927 
   1928   for (i = 0; init[i].ptr; i++)
   1929     if (strcmp (GET_INIT_SYMBOL_NAME (i), option) == 0)
   1930       return init[i].inited;
   1931   return 0;
   1932 }
   1933 #endif /* DLL_SUPPORT */
   1934 
   1935 static bool
   1936 gld${EMULATION_NAME}_unrecognized_file (lang_input_statement_type *entry ATTRIBUTE_UNUSED)
   1937 {
   1938 #ifdef DLL_SUPPORT
   1939   const char *ext = strrchr (entry->filename, '.');
   1940 
   1941   if (ext != NULL && fileext_cmp (ext + 1, "def") == 0)
   1942     {
   1943       pe_def_file = def_file_parse (entry->filename, pe_def_file);
   1944 
   1945       if (pe_def_file)
   1946 	{
   1947 	  int i, buflen=0, len;
   1948 	  char *buf;
   1949 
   1950 	  for (i = 0; i < pe_def_file->num_exports; i++)
   1951 	    {
   1952 	      len = strlen (pe_def_file->exports[i].internal_name);
   1953 	      if (buflen < len + 2)
   1954 		buflen = len + 2;
   1955 	    }
   1956 
   1957 	  buf = xmalloc (buflen);
   1958 
   1959 	  for (i = 0; i < pe_def_file->num_exports; i++)
   1960 	    {
   1961 	      struct bfd_link_hash_entry *h;
   1962 
   1963 	      sprintf (buf, "%s%s", U (""),
   1964 		       pe_def_file->exports[i].internal_name);
   1965 
   1966 	      h = bfd_link_hash_lookup (link_info.hash, buf, true, true, true);
   1967 	      if (h == (struct bfd_link_hash_entry *) NULL)
   1968 		fatal (_("%P: bfd_link_hash_lookup failed: %E\n"));
   1969 	      if (h->type == bfd_link_hash_new)
   1970 		{
   1971 		  h->type = bfd_link_hash_undefined;
   1972 		  h->u.undef.abfd = NULL;
   1973 		  bfd_link_add_undef (link_info.hash, h);
   1974 		}
   1975 	    }
   1976 	  free (buf);
   1977 
   1978 	  /* def_file_print (stdout, pe_def_file); */
   1979 	  if (pe_def_file->is_dll == 1)
   1980 	    link_info.type = type_dll;
   1981 
   1982 	  if (pe_def_file->base_address != (bfd_vma)(-1))
   1983 	    {
   1984 	      pe.ImageBase
   1985 		= pe_data (link_info.output_bfd)->pe_opthdr.ImageBase
   1986 		= init[IMAGEBASEOFF].value
   1987 		= pe_def_file->base_address;
   1988 	      init[IMAGEBASEOFF].inited = 1;
   1989 	      if (image_base_statement)
   1990 		image_base_statement->exp
   1991 		  = exp_assign ("__image_base__", exp_intop (pe.ImageBase),
   1992 				false);
   1993 	    }
   1994 
   1995 	  if (pe_def_file->stack_reserve != -1
   1996 	      && ! saw_option ("__size_of_stack_reserve__"))
   1997 	    {
   1998 	      pe.SizeOfStackReserve = pe_def_file->stack_reserve;
   1999 	      if (pe_def_file->stack_commit != -1)
   2000 		pe.SizeOfStackCommit = pe_def_file->stack_commit;
   2001 	    }
   2002 	  if (pe_def_file->heap_reserve != -1
   2003 	      && ! saw_option ("__size_of_heap_reserve__"))
   2004 	    {
   2005 	      pe.SizeOfHeapReserve = pe_def_file->heap_reserve;
   2006 	      if (pe_def_file->heap_commit != -1)
   2007 		pe.SizeOfHeapCommit = pe_def_file->heap_commit;
   2008 	    }
   2009 	  return true;
   2010 	}
   2011     }
   2012 #endif
   2013   return false;
   2014 }
   2015 
   2016 static bool
   2017 gld${EMULATION_NAME}_recognized_file (lang_input_statement_type *entry ATTRIBUTE_UNUSED)
   2018 {
   2019 #ifdef DLL_SUPPORT
   2020 #ifdef TARGET_IS_i386pe
   2021   pe_dll_id_target ("pei-i386");
   2022 #endif
   2023 #ifdef TARGET_IS_shpe
   2024   pe_dll_id_target ("pei-shl");
   2025 #endif
   2026 #ifdef TARGET_IS_armpe
   2027   pe_dll_id_target ("pei-arm-little");
   2028 #endif
   2029 #ifdef TARGET_IS_arm_wince_pe
   2030   pe_dll_id_target ("pei-arm-wince-little");
   2031 #endif
   2032   if (pe_bfd_is_dll (entry->the_bfd))
   2033     return pe_implied_import_dll (entry->filename);
   2034 #endif
   2035   return false;
   2036 }
   2037 
   2038 static void
   2039 gld${EMULATION_NAME}_finish (void)
   2040 {
   2041   /* Support the object-only output.  */
   2042   if (config.emit_gnu_object_only)
   2043     orphan_init_done = false;
   2044 
   2045 #if defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_wince_pe)
   2046   struct bfd_link_hash_entry * h;
   2047 
   2048   if (thumb_entry_symbol != NULL)
   2049     {
   2050       h = bfd_link_hash_lookup (link_info.hash, thumb_entry_symbol,
   2051 				false, false, true);
   2052 
   2053       if (h != (struct bfd_link_hash_entry *) NULL
   2054 	  && (h->type == bfd_link_hash_defined
   2055 	      || h->type == bfd_link_hash_defweak)
   2056 	  && h->u.def.section->output_section != NULL)
   2057 	{
   2058 	  static char buffer[32];
   2059 	  bfd_vma val;
   2060 
   2061 	  /* Special procesing is required for a Thumb entry symbol.  The
   2062 	     bottom bit of its address must be set.  */
   2063 	  val = (h->u.def.value
   2064 		 + bfd_section_vma (h->u.def.section->output_section)
   2065 		 + h->u.def.section->output_offset);
   2066 
   2067 	  val |= 1;
   2068 
   2069 	  /* Now convert this value into a string and store it in entry_symbol
   2070 	     where the lang_finish() function will pick it up.  */
   2071 	  sprintf (buffer, "0x%" PRIx64, (uint64_t) val);
   2072 
   2073 	  if (entry_symbol.name != NULL && entry_from_cmdline)
   2074 	    einfo (_("%P: warning: '--thumb-entry %s' is overriding '-e %s'\n"),
   2075 		   thumb_entry_symbol, entry_symbol.name);
   2076 	  entry_symbol.name = buffer;
   2077 	}
   2078       else
   2079 	einfo (_("%P: warning: cannot find thumb start symbol %s\n"), thumb_entry_symbol);
   2080     }
   2081 #endif /* defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_wince_pe) */
   2082 
   2083   finish_default ();
   2084 
   2085 #ifdef DLL_SUPPORT
   2086   if (bfd_link_pic (&link_info)
   2087 #if !defined(TARGET_IS_shpe)
   2088       || pe_dll_enable_reloc_section
   2089       || (!bfd_link_relocatable (&link_info)
   2090 	  && pe_def_file->num_exports != 0)
   2091 #endif
   2092     )
   2093     {
   2094       pe_dll_fill_sections (link_info.output_bfd, &link_info);
   2095       if (command_line.out_implib_filename
   2096           && (pe_def_file->num_exports != 0
   2097               || bfd_link_pic (&link_info)))
   2098 	pe_dll_generate_implib (pe_def_file, command_line.out_implib_filename,
   2099 				&link_info);
   2100     }
   2101 #if defined(TARGET_IS_shpe)
   2102   /* ARM doesn't need relocs.  */
   2103   else
   2104     {
   2105       pe_exe_fill_sections (link_info.output_bfd, &link_info);
   2106     }
   2107 #endif
   2108 
   2109   if (pe_out_def_filename)
   2110     pe_dll_generate_def_file (pe_out_def_filename);
   2111 #endif /* DLL_SUPPORT */
   2112 
   2113   /* I don't know where .idata gets set as code, but it shouldn't be.  */
   2114   {
   2115     asection *asec = bfd_get_section_by_name (link_info.output_bfd, ".idata");
   2116 
   2117     if (asec)
   2118       {
   2119 	asec->flags &= ~SEC_CODE;
   2120 	asec->flags |= SEC_DATA;
   2121       }
   2122   }
   2123 }
   2124 
   2125 
   2127 /* Place an orphan section.
   2128 
   2129    We use this to put sections in a reasonable place in the file, and
   2130    to ensure that they are aligned as required.
   2131 
   2132    We handle grouped sections here as well.  A section named .foo\$nn
   2133    goes into the output section .foo.  All grouped sections are sorted
   2134    by name.
   2135 
   2136    Grouped sections for the default sections are handled by the
   2137    default linker script using wildcards, and are sorted by
   2138    sort_sections.  */
   2139 
   2140 static lang_output_section_statement_type *
   2141 gld${EMULATION_NAME}_place_orphan (asection *s,
   2142 				   const char *secname,
   2143 				   int constraint)
   2144 {
   2145   const char *orig_secname = secname;
   2146   char *dollar = NULL;
   2147   lang_output_section_statement_type *os;
   2148   lang_statement_list_type add_child;
   2149   lang_output_section_statement_type *match_by_name = NULL;
   2150   lang_statement_union_type **pl;
   2151 
   2152   /* Look through the script to see where to place this section.  */
   2153   if (!bfd_link_relocatable (&link_info)
   2154       && (dollar = strchr (secname, '\$')) != NULL)
   2155     {
   2156       size_t len = dollar - secname;
   2157       char *newname = xmalloc (len + 1);
   2158       memcpy (newname, secname, len);
   2159       newname[len] = '\0';
   2160       secname = newname;
   2161     }
   2162 
   2163   lang_list_init (&add_child);
   2164 
   2165   os = NULL;
   2166   if (constraint == 0)
   2167     for (os = lang_output_section_find (secname);
   2168 	 os != NULL;
   2169 	 os = next_matching_output_section_statement (os, 0))
   2170       {
   2171 	/* If we don't match an existing output section, tell
   2172 	   lang_insert_orphan to create a new output section.  */
   2173 	constraint = SPECIAL;
   2174 
   2175 	if (os->bfd_section != NULL
   2176 	    && (os->bfd_section->flags == 0
   2177 		|| ((s->flags ^ os->bfd_section->flags)
   2178 		    & (SEC_LOAD | SEC_ALLOC)) == 0))
   2179 	  {
   2180 	    /* We already have an output section statement with this
   2181 	       name, and its bfd section has compatible flags.
   2182 	       If the section already exists but does not have any flags set,
   2183 	       then it has been created by the linker, probably as a result of
   2184 	       a --section-start command line switch.  */
   2185 	    lang_add_section (&add_child, s, NULL, NULL, os);
   2186 	    break;
   2187 	  }
   2188 
   2189 	/* Save unused output sections in case we can match them
   2190 	   against orphans later.  */
   2191 	if (os->bfd_section == NULL)
   2192 	  match_by_name = os;
   2193       }
   2194 
   2195   /* If we didn't match an active output section, see if we matched an
   2196      unused one and use that.  */
   2197   if (os == NULL && match_by_name)
   2198     {
   2199       lang_add_section (&match_by_name->children, s, NULL, NULL, match_by_name);
   2200       return match_by_name;
   2201     }
   2202 
   2203   if (os == NULL)
   2204     {
   2205       static struct orphan_save orig_hold[] =
   2206 	{
   2207 	  { ".text",
   2208 	    SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE,
   2209 	    0, 0, 0, 0 },
   2210 	  { ".idata",
   2211 	    SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
   2212 	    0, 0, 0, 0 },
   2213 	  { ".rdata",
   2214 	    SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
   2215 	    0, 0, 0, 0 },
   2216 	  { ".data",
   2217 	    SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA,
   2218 	    0, 0, 0, 0 },
   2219 	  { ".bss",
   2220 	    SEC_ALLOC,
   2221 	    0, 0, 0, 0 }
   2222 	};
   2223       static struct orphan_save hold[ARRAY_SIZE (orig_hold)];
   2224       enum orphan_save_index
   2225 	{
   2226 	  orphan_text = 0,
   2227 	  orphan_idata,
   2228 	  orphan_rodata,
   2229 	  orphan_data,
   2230 	  orphan_bss
   2231 	};
   2232       struct orphan_save *place;
   2233       lang_output_section_statement_type *after;
   2234       etree_type *address;
   2235       flagword flags;
   2236       asection *nexts;
   2237 
   2238       if (!orphan_init_done)
   2239 	{
   2240 	  struct orphan_save *ho, *horig;
   2241 	  for (ho = hold, horig = orig_hold;
   2242 	       ho < hold + ARRAY_SIZE (hold);
   2243 	       ++ho, ++horig)
   2244 	    {
   2245 	      *ho = *horig;
   2246 	      if (ho->name != NULL)
   2247 		{
   2248 		  ho->os = lang_output_section_find (ho->name);
   2249 		  if (ho->os != NULL && ho->os->flags == 0)
   2250 		    ho->os->flags = ho->flags;
   2251 	        }
   2252 	    }
   2253 	  orphan_init_done = true;
   2254 	}
   2255 
   2256       flags = s->flags;
   2257       if (!bfd_link_relocatable (&link_info))
   2258 	{
   2259 	  nexts = s;
   2260 	  while ((nexts = bfd_get_next_section_by_name (nexts->owner,
   2261 							nexts)))
   2262 	    if (nexts->output_section == NULL
   2263 		&& (nexts->flags & SEC_EXCLUDE) == 0
   2264 		&& ((nexts->flags ^ flags) & (SEC_LOAD | SEC_ALLOC)) == 0
   2265 		&& (nexts->owner->flags & DYNAMIC) == 0
   2266 		&& !bfd_input_just_syms (nexts->owner))
   2267 	      flags = (((flags ^ SEC_READONLY)
   2268 			| (nexts->flags ^ SEC_READONLY))
   2269 		       ^ SEC_READONLY);
   2270 	}
   2271 
   2272       /* Try to put the new output section in a reasonable place based
   2273 	 on the section name and section flags.  */
   2274 
   2275       place = NULL;
   2276       if ((flags & SEC_ALLOC) == 0)
   2277 	;
   2278       else if ((flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
   2279 	place = &hold[orphan_bss];
   2280       else if ((flags & SEC_READONLY) == 0)
   2281 	place = &hold[orphan_data];
   2282       else if ((flags & SEC_CODE) == 0)
   2283 	{
   2284 	  place = (!strncmp (secname, ".idata\$", 7) ? &hold[orphan_idata]
   2285 						     : &hold[orphan_rodata]);
   2286 	}
   2287       else
   2288 	place = &hold[orphan_text];
   2289 
   2290       after = NULL;
   2291       if (place != NULL)
   2292 	{
   2293 	  if (place->os == NULL)
   2294 	    place->os = lang_output_section_find (place->name);
   2295 	  after = place->os;
   2296 	  if (after == NULL)
   2297 	    after = lang_output_section_find_by_flags (s, flags, &place->os,
   2298 						       NULL);
   2299 	  if (after == NULL)
   2300 	    /* *ABS* is always the first output section statement.  */
   2301 	    after = (void *) lang_os_list.head;
   2302 	}
   2303 
   2304       /* All sections in an executable must be aligned to a page boundary.
   2305 	 In a relocatable link, just preserve the incoming alignment; the
   2306 	 address is discarded by lang_insert_orphan in that case, anyway.  */
   2307       address = exp_unop (ALIGN_K, exp_nameop (NAME, "__section_alignment__"));
   2308       os = lang_insert_orphan (s, secname, constraint, after, place, address,
   2309 			       &add_child);
   2310       if (bfd_link_relocatable (&link_info))
   2311 	{
   2312 	  os->section_alignment = exp_intop (1U << s->alignment_power);
   2313 	  os->bfd_section->alignment_power = s->alignment_power;
   2314 	}
   2315     }
   2316 
   2317   /* If the section name has a '\$', sort it with the other '\$'
   2318      sections.  */
   2319   for (pl = &os->children.head; *pl != NULL; pl = &(*pl)->header.next)
   2320     {
   2321       lang_input_section_type *ls;
   2322       const char *lname;
   2323 
   2324       if ((*pl)->header.type != lang_input_section_enum)
   2325 	continue;
   2326 
   2327       ls = &(*pl)->input_section;
   2328 
   2329       lname = bfd_section_name (ls->section);
   2330       if (strchr (lname, '\$') != NULL
   2331 	  && (dollar == NULL || strcmp (orig_secname, lname) < 0))
   2332 	break;
   2333     }
   2334 
   2335   if (add_child.head != NULL)
   2336     {
   2337       *add_child.tail = *pl;
   2338       *pl = add_child.head;
   2339     }
   2340 
   2341   return os;
   2342 }
   2343 
   2344 static bool
   2345 gld${EMULATION_NAME}_open_dynamic_archive
   2346   (const char *arch ATTRIBUTE_UNUSED,
   2347    search_dirs_type *search,
   2348    lang_input_statement_type *entry)
   2349 {
   2350   static const struct
   2351     {
   2352       const char * format;
   2353       bool use_prefix;
   2354     }
   2355   libname_fmt [] =
   2356     {
   2357       /* Preferred explicit import library for dll's.  */
   2358       { "lib%s.dll.a", false },
   2359       /* Alternate explicit import library for dll's.  */
   2360       { "%s.dll.a", false },
   2361       /* "libfoo.a" could be either an import lib or a static lib.
   2362 	 For backwards compatibility, libfoo.a needs to precede
   2363 	 libfoo.dll and foo.dll in the search.  */
   2364       { "lib%s.a", false },
   2365       /* The 'native' spelling of an import lib name is "foo.lib".  */
   2366       { "%s.lib", false },
   2367       /* PR 22948 - Check for an import library.  */
   2368       { "lib%s.lib", false },
   2369 #ifdef DLL_SUPPORT
   2370       /* Try "<prefix>foo.dll" (preferred dll name, if specified).  */
   2371       {	"%s%s.dll", true },
   2372 #endif
   2373       /* Try "libfoo.dll" (default preferred dll name).  */
   2374       {	"lib%s.dll", false },
   2375       /* Finally try 'native' dll name "foo.dll".  */
   2376       {  "%s.dll", false },
   2377       /* Note: If adding more formats to this table, make sure to check to
   2378 	 see if their length is longer than libname_fmt[0].format, and if
   2379 	 so, update the call to xmalloc() below.  */
   2380       { NULL, false }
   2381     };
   2382   static unsigned int format_max_len = 0;
   2383   const char * filename;
   2384   char * full_string;
   2385   char * base_string;
   2386   unsigned int i;
   2387 
   2388 
   2389   if (! entry->flags.maybe_archive || entry->flags.full_name_provided)
   2390     return false;
   2391 
   2392   filename = entry->filename;
   2393 
   2394   if (format_max_len == 0)
   2395     /* We need to allow space in the memory that we are going to allocate
   2396        for the characters in the format string.  Since the format array is
   2397        static we only need to calculate this information once.  In theory
   2398        this value could also be computed statically, but this introduces
   2399        the possibility for a discrepancy and hence a possible memory
   2400        corruption.  The lengths we compute here will be too long because
   2401        they will include any formating characters (%s) in the strings, but
   2402        this will not matter.  */
   2403     for (i = 0; libname_fmt[i].format; i++)
   2404       if (format_max_len < strlen (libname_fmt[i].format))
   2405 	format_max_len = strlen (libname_fmt[i].format);
   2406 
   2407   full_string = xmalloc (strlen (search->name)
   2408 			 + strlen (filename)
   2409 			 + format_max_len
   2410 #ifdef DLL_SUPPORT
   2411 			 + (pe_dll_search_prefix
   2412 			    ? strlen (pe_dll_search_prefix) : 0)
   2413 #endif
   2414 			 /* Allow for the terminating NUL and for the path
   2415 			    separator character that is inserted between
   2416 			    search->name and the start of the format string.  */
   2417 			 + 2);
   2418 
   2419   base_string = stpcpy (full_string, search->name);
   2420   *base_string++ = '/';
   2421 
   2422   for (i = 0; libname_fmt[i].format; i++)
   2423     {
   2424 #ifdef DLL_SUPPORT
   2425       if (libname_fmt[i].use_prefix)
   2426 	{
   2427 	  if (!pe_dll_search_prefix)
   2428 	    continue;
   2429 	  sprintf (base_string, libname_fmt[i].format, pe_dll_search_prefix, filename);
   2430 	}
   2431       else
   2432 #endif
   2433 	sprintf (base_string, libname_fmt[i].format, filename);
   2434 
   2435       if (ldfile_try_open_bfd (full_string, entry))
   2436 	break;
   2437     }
   2438 
   2439   if (!libname_fmt[i].format)
   2440     {
   2441       free (full_string);
   2442       return false;
   2443     }
   2444 
   2445   entry->filename = full_string;
   2446 
   2447   return true;
   2448 }
   2449 
   2450 static int
   2451 gld${EMULATION_NAME}_find_potential_libraries
   2452   (char *name, lang_input_statement_type *entry)
   2453 {
   2454   return ldfile_open_file_search (name, entry, "", ".lib");
   2455 }
   2456 
   2457 static struct bfd_link_hash_entry *
   2458 gld${EMULATION_NAME}_find_alt_start_symbol
   2459   (struct bfd_sym_chain *entry)
   2460 {
   2461 #if defined (TARGET_IS_i386pe)
   2462   bool entry_has_stdcall_suffix;
   2463 #endif
   2464   struct bfd_link_hash_entry *h;
   2465   size_t entry_name_len;
   2466   char *symbol_name;
   2467   const char *prefix;
   2468   const char *suffix;
   2469 
   2470   entry_name_len = strlen (entry->name);
   2471 
   2472   if (is_underscoring ())
   2473     prefix = "_";
   2474   else
   2475     prefix = "";
   2476 
   2477 #if defined (TARGET_IS_i386pe)
   2478   if ((entry_name_len > 2 && entry->name[entry_name_len-2] == '@' && ISDIGIT (entry->name[entry_name_len-1]))
   2479       || (entry_name_len > 3 && entry->name[entry_name_len-3] == '@' && ISDIGIT (entry->name[entry_name_len-2]) && ISDIGIT (entry->name[entry_name_len-1]))
   2480       || (entry_name_len > 4 && entry->name[entry_name_len-4] == '@' && ISDIGIT (entry->name[entry_name_len-3]) && ISDIGIT (entry->name[entry_name_len-2]) && ISDIGIT (entry->name[entry_name_len-1])))
   2481     entry_has_stdcall_suffix = true;
   2482   else
   2483     entry_has_stdcall_suffix = false;
   2484 
   2485   if (!entry_has_stdcall_suffix && (bfd_link_dll (&link_info) || dll))
   2486     suffix = "@12";
   2487   else if (!entry_has_stdcall_suffix && pe_subsystem == 1 /* NT kernel driver */)
   2488     suffix = "@8";
   2489   else
   2490 #endif
   2491     suffix = "";
   2492 
   2493   if (*prefix == '\0' && *suffix == '\0')
   2494     return NULL;
   2495 
   2496   symbol_name = xmalloc (entry_name_len + 5);
   2497   strcpy (symbol_name, prefix);
   2498   strcat (symbol_name, entry->name);
   2499   strcat (symbol_name, suffix);
   2500 
   2501   h = bfd_link_hash_lookup (link_info.hash, symbol_name, false, false, true);
   2502   free (symbol_name);
   2503   return h;
   2504 }
   2505 
   2507 static char *
   2508 gld${EMULATION_NAME}_get_script (int *isfile)
   2509 EOF
   2510 
   2511 if test x"$COMPILE_IN" = xyes
   2512 then
   2513 # Scripts compiled in.
   2514 
   2515 # sed commands to quote an ld script as a C string.
   2516 sc="-f ${srcdir}/emultempl/stringify.sed"
   2517 
   2518 fragment <<EOF
   2519 {
   2520   *isfile = 0;
   2521 
   2522   if (bfd_link_relocatable (&link_info) && config.build_constructors)
   2523     return
   2524 EOF
   2525 sed $sc ldscripts/${EMULATION_NAME}.xu			>> e${EMULATION_NAME}.c
   2526 echo '  ; else if (bfd_link_relocatable (&link_info)) return' >> e${EMULATION_NAME}.c
   2527 sed $sc ldscripts/${EMULATION_NAME}.xr			>> e${EMULATION_NAME}.c
   2528 echo '  ; else if (!config.text_read_only) return'	>> e${EMULATION_NAME}.c
   2529 sed $sc ldscripts/${EMULATION_NAME}.xbn			>> e${EMULATION_NAME}.c
   2530 echo '  ; else if (!config.magic_demand_paged) return'	>> e${EMULATION_NAME}.c
   2531 sed $sc ldscripts/${EMULATION_NAME}.xn			>> e${EMULATION_NAME}.c
   2532 if test -n "$GENERATE_AUTO_IMPORT_SCRIPT" ; then
   2533 echo '  ; else if (link_info.pei386_auto_import == 1 && (MERGE_RDATA_V2 || link_info.pei386_runtime_pseudo_reloc != 2)) return'	>> e${EMULATION_NAME}.c
   2534 sed $sc ldscripts/${EMULATION_NAME}.xa			>> e${EMULATION_NAME}.c
   2535 fi
   2536 echo '  ; else return'					>> e${EMULATION_NAME}.c
   2537 sed $sc ldscripts/${EMULATION_NAME}.x			>> e${EMULATION_NAME}.c
   2538 echo '; }'						>> e${EMULATION_NAME}.c
   2539 
   2540 else
   2541 # Scripts read from the filesystem.
   2542 
   2543 fragment <<EOF
   2544 {
   2545   *isfile = 1;
   2546 
   2547   if (bfd_link_relocatable (&link_info) && config.build_constructors)
   2548     return "ldscripts/${EMULATION_NAME}.xu";
   2549   else if (bfd_link_relocatable (&link_info))
   2550     return "ldscripts/${EMULATION_NAME}.xr";
   2551   else if (!config.text_read_only)
   2552     return "ldscripts/${EMULATION_NAME}.xbn";
   2553   else if (!config.magic_demand_paged)
   2554     return "ldscripts/${EMULATION_NAME}.xn";
   2555 EOF
   2556 if test -n "$GENERATE_AUTO_IMPORT_SCRIPT" ; then
   2557 fragment <<EOF
   2558   else if (link_info.pei386_auto_import == 1
   2559 	   && (MERGE_RDATA_V2 || link_info.pei386_runtime_pseudo_reloc != 2))
   2560     return "ldscripts/${EMULATION_NAME}.xa";
   2561 EOF
   2562 fi
   2563 fragment <<EOF
   2564   else
   2565     return "ldscripts/${EMULATION_NAME}.x";
   2566 }
   2567 EOF
   2568 fi
   2569 
   2570 LDEMUL_AFTER_PARSE=gld${EMULATION_NAME}_after_parse
   2571 LDEMUL_BEFORE_PLUGIN_ALL_SYMBOLS_READ=gld${EMULATION_NAME}_before_plugin_all_symbols_read
   2572 LDEMUL_AFTER_OPEN=gld${EMULATION_NAME}_after_open
   2573 LDEMUL_BEFORE_ALLOCATION=gld${EMULATION_NAME}_before_allocation
   2574 LDEMUL_FINISH=gld${EMULATION_NAME}_finish
   2575 LDEMUL_OPEN_DYNAMIC_ARCHIVE=gld${EMULATION_NAME}_open_dynamic_archive
   2576 LDEMUL_PLACE_ORPHAN=gld${EMULATION_NAME}_place_orphan
   2577 LDEMUL_SET_SYMBOLS=gld${EMULATION_NAME}_set_symbols
   2578 LDEMUL_ADD_OPTIONS=gld${EMULATION_NAME}_add_options
   2579 LDEMUL_HANDLE_OPTION=gld${EMULATION_NAME}_handle_option
   2580 LDEMUL_UNRECOGNIZED_FILE=gld${EMULATION_NAME}_unrecognized_file
   2581 LDEMUL_LIST_OPTIONS=gld${EMULATION_NAME}_list_options
   2582 LDEMUL_RECOGNIZED_FILE=gld${EMULATION_NAME}_recognized_file
   2583 LDEMUL_FIND_POTENTIAL_LIBRARIES=gld${EMULATION_NAME}_find_potential_libraries
   2584 LDEMUL_FIND_START_SYMBOL=gld${EMULATION_NAME}_find_alt_start_symbol
   2585 
   2586 source_em ${srcdir}/emultempl/emulation.em
   2587