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