Fix a bug recently introduced to the linker where it would complain about a section...
[external/binutils.git] / ld / emultempl / pep.em
1 # This shell script emits a C file. -*- C -*-
2 # It does some substitutions.
3 if [ -z "$MACHINE" ]; then
4   OUTPUT_ARCH=${ARCH}
5 else
6   OUTPUT_ARCH=${ARCH}:${MACHINE}
7 fi
8
9 case ${target} in
10   *-*-cygwin*)
11     move_default_addr_high=1
12     ;;
13   *)
14     move_default_addr_high=0;
15     ;;
16 esac
17
18 rm -f e${EMULATION_NAME}.c
19 (echo;echo;echo;echo;echo)>e${EMULATION_NAME}.c # there, now line numbers match ;-)
20 fragment <<EOF
21 /* Copyright (C) 2006-2019 Free Software Foundation, Inc.
22    Written by Kai Tietz, OneVision Software GmbH&CoKg.
23
24    This file is part of the GNU Binutils.
25
26    This program is free software; you can redistribute it and/or modify
27    it under the terms of the GNU General Public License as published by
28    the Free Software Foundation; either version 3 of the License, or
29    (at your option) any later version.
30
31    This program is distributed in the hope that it will be useful,
32    but WITHOUT ANY WARRANTY; without even the implied warranty of
33    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34    GNU General Public License for more details.
35
36    You should have received a copy of the GNU General Public License
37    along with this program; if not, write to the Free Software
38    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
39    MA 02110-1301, USA.  */
40
41
42 /* For WINDOWS_XP64 and higher */
43 /* Based on pe.em, but modified for 64 bit support.  */
44
45 #define TARGET_IS_${EMULATION_NAME}
46
47 #define COFF_IMAGE_WITH_PE
48 #define COFF_WITH_PE
49 #define COFF_WITH_pex64
50
51 #include "sysdep.h"
52 #include "bfd.h"
53 #include "bfdlink.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
70 /* FIXME: See bfd/peXXigen.c for why we include an architecture specific
71    header in generic PE code.  */
72 #include "coff/x86_64.h"
73 #include "coff/pe.h"
74
75 /* FIXME: These are BFD internal header files, and we should not be
76    using it here.  */
77 #include "../bfd/libcoff.h"
78 #include "../bfd/libpei.h"
79
80 #undef  AOUTSZ
81 #define AOUTSZ          PEPAOUTSZ
82 #define PEAOUTHDR       PEPAOUTHDR
83
84 #include "deffile.h"
85 #include "pep-dll.h"
86 #include "safe-ctype.h"
87
88 /* Permit the emulation parameters to override the default section
89    alignment by setting OVERRIDE_SECTION_ALIGNMENT.  FIXME: This makes
90    it seem that include/coff/internal.h should not define
91    PE_DEF_SECTION_ALIGNMENT.  */
92 #if PE_DEF_SECTION_ALIGNMENT != ${OVERRIDE_SECTION_ALIGNMENT:-PE_DEF_SECTION_ALIGNMENT}
93 #undef  PE_DEF_SECTION_ALIGNMENT
94 #define PE_DEF_SECTION_ALIGNMENT ${OVERRIDE_SECTION_ALIGNMENT}
95 #endif
96
97 #ifdef TARGET_IS_i386pep
98 #define DLL_SUPPORT
99 #endif
100
101 #if defined(TARGET_IS_i386pep) || ! defined(DLL_SUPPORT)
102 #define PE_DEF_SUBSYSTEM                3
103 #undef NT_EXE_IMAGE_BASE
104 #define NT_EXE_IMAGE_BASE \
105   ((bfd_vma) (${move_default_addr_high} ? 0x100400000LL \
106                                         : 0x400000LL))
107 #undef NT_DLL_IMAGE_BASE
108 #define NT_DLL_IMAGE_BASE \
109   ((bfd_vma) (${move_default_addr_high} ? 0x400000000LL \
110                                         : 0x10000000LL))
111 #undef NT_DLL_AUTO_IMAGE_BASE
112 #define NT_DLL_AUTO_IMAGE_BASE \
113   ((bfd_vma) (${move_default_addr_high} ? 0x400000000LL \
114                                         : 0x61300000LL))
115 #undef NT_DLL_AUTO_IMAGE_MASK
116 #define NT_DLL_AUTO_IMAGE_MASK \
117   ((bfd_vma) (${move_default_addr_high} ? 0x1ffff0000LL \
118                                         : 0x0ffc0000LL))
119 #else
120 #undef  NT_EXE_IMAGE_BASE
121 #define NT_EXE_IMAGE_BASE \
122   ((bfd_vma) (${move_default_addr_high} ? 0x100010000LL \
123                                         : 0x10000LL))
124 #undef NT_DLL_IMAGE_BASE
125 #define NT_DLL_IMAGE_BASE \
126   ((bfd_vma) (${move_default_addr_high} ? 0x110000000LL \
127                                         : 0x10000000LL))
128 #undef NT_DLL_AUTO_IMAGE_BASE
129 #define NT_DLL_AUTO_IMAGE_BASE \
130   ((bfd_vma) (${move_default_addr_high} ? 0x120000000LL \
131                                         : 0x61300000LL))
132 #undef NT_DLL_AUTO_IMAGE_MASK
133 #define NT_DLL_AUTO_IMAGE_MASK \
134   ((bfd_vma) (${move_default_addr_high} ? 0x0ffff0000LL \
135                                         : 0x0ffc0000LL))
136 #undef  PE_DEF_SECTION_ALIGNMENT
137 #define PE_DEF_SUBSYSTEM                2
138 #undef  PE_DEF_FILE_ALIGNMENT
139 #define PE_DEF_FILE_ALIGNMENT           0x00000200
140 #define PE_DEF_SECTION_ALIGNMENT        0x00000400
141 #endif
142
143 static struct internal_extra_pe_aouthdr pep;
144 static int dll;
145 static int pep_subsystem = ${SUBSYSTEM};
146 static flagword real_flags = IMAGE_FILE_LARGE_ADDRESS_AWARE;
147 static int support_old_code = 0;
148 static lang_assignment_statement_type *image_base_statement = 0;
149 static unsigned short pe_dll_characteristics = 0;
150 static bfd_boolean insert_timestamp = TRUE;
151 static const char *emit_build_id;
152
153 #ifdef DLL_SUPPORT
154 static int    pep_enable_stdcall_fixup = 1; /* 0=disable 1=enable (default).  */
155 static char * pep_out_def_filename = NULL;
156 static int    pep_enable_auto_image_base = 0;
157 static char * pep_dll_search_prefix = NULL;
158 #endif
159
160 extern const char *output_filename;
161
162 static int is_underscoring (void)
163 {
164   int u = 0;
165   if (pep_leading_underscore != -1)
166     return pep_leading_underscore;
167   if (!bfd_get_target_info ("${OUTPUT_FORMAT}", NULL, NULL, &u, NULL))
168     bfd_get_target_info ("${RELOCATEABLE_OUTPUT_FORMAT}", NULL, NULL, &u, NULL);
169
170   if (u == -1)
171     abort ();
172   pep_leading_underscore = (u != 0 ? 1 : 0);
173   return pep_leading_underscore;
174 }
175
176
177 static void
178 gld_${EMULATION_NAME}_before_parse (void)
179 {
180   is_underscoring ();
181   ldfile_set_output_arch ("${OUTPUT_ARCH}", bfd_arch_`echo ${ARCH} | sed -e 's/:.*//'`);
182   output_filename = "${EXECUTABLE_NAME:-a.exe}";
183 #ifdef DLL_SUPPORT
184   input_flags.dynamic = TRUE;
185   config.has_shared = 1;
186   link_info.pei386_auto_import = 1;
187   link_info.pei386_runtime_pseudo_reloc = 2; /* Use by default version 2.  */
188 #endif
189 }
190 \f
191 /* PE format extra command line options.  */
192
193 /* Used for setting flags in the PE header.  */
194 enum options
195 {
196   OPTION_BASE_FILE = 300 + 1,
197   OPTION_DLL,
198   OPTION_FILE_ALIGNMENT,
199   OPTION_IMAGE_BASE,
200   OPTION_MAJOR_IMAGE_VERSION,
201   OPTION_MAJOR_OS_VERSION,
202   OPTION_MAJOR_SUBSYSTEM_VERSION,
203   OPTION_MINOR_IMAGE_VERSION,
204   OPTION_MINOR_OS_VERSION,
205   OPTION_MINOR_SUBSYSTEM_VERSION,
206   OPTION_SECTION_ALIGNMENT,
207   OPTION_STACK,
208   OPTION_SUBSYSTEM,
209   OPTION_HEAP,
210   OPTION_SUPPORT_OLD_CODE,
211   OPTION_OUT_DEF,
212   OPTION_EXPORT_ALL,
213   OPTION_EXCLUDE_SYMBOLS,
214   OPTION_EXCLUDE_ALL_SYMBOLS,
215   OPTION_KILL_ATS,
216   OPTION_STDCALL_ALIASES,
217   OPTION_ENABLE_STDCALL_FIXUP,
218   OPTION_DISABLE_STDCALL_FIXUP,
219   OPTION_WARN_DUPLICATE_EXPORTS,
220   OPTION_IMP_COMPAT,
221   OPTION_ENABLE_AUTO_IMAGE_BASE,
222   OPTION_DISABLE_AUTO_IMAGE_BASE,
223   OPTION_DLL_SEARCH_PREFIX,
224   OPTION_NO_DEFAULT_EXCLUDES,
225   OPTION_DLL_ENABLE_AUTO_IMPORT,
226   OPTION_DLL_DISABLE_AUTO_IMPORT,
227   OPTION_ENABLE_EXTRA_PE_DEBUG,
228   OPTION_EXCLUDE_LIBS,
229   OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC,
230   OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC,
231   OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2,
232   OPTION_EXCLUDE_MODULES_FOR_IMPLIB,
233   OPTION_USE_NUL_PREFIXED_IMPORT_TABLES,
234   OPTION_NO_LEADING_UNDERSCORE,
235   OPTION_LEADING_UNDERSCORE,
236   OPTION_ENABLE_LONG_SECTION_NAMES,
237   OPTION_DISABLE_LONG_SECTION_NAMES,
238   OPTION_HIGH_ENTROPY_VA,
239   OPTION_DYNAMIC_BASE,
240   OPTION_FORCE_INTEGRITY,
241   OPTION_NX_COMPAT,
242   OPTION_NO_ISOLATION,
243   OPTION_NO_SEH,
244   OPTION_NO_BIND,
245   OPTION_WDM_DRIVER,
246   OPTION_INSERT_TIMESTAMP,
247   OPTION_NO_INSERT_TIMESTAMP,
248   OPTION_TERMINAL_SERVER_AWARE,
249   OPTION_BUILD_ID
250 };
251
252 static void
253 gld${EMULATION_NAME}_add_options
254   (int ns ATTRIBUTE_UNUSED,
255    char **shortopts ATTRIBUTE_UNUSED,
256    int nl,
257    struct option **longopts,
258    int nrl ATTRIBUTE_UNUSED,
259    struct option **really_longopts ATTRIBUTE_UNUSED)
260 {
261   static const struct option xtra_long[] =
262   {
263     /* PE options */
264     {"base-file", required_argument, NULL, OPTION_BASE_FILE},
265     {"dll", no_argument, NULL, OPTION_DLL},
266     {"file-alignment", required_argument, NULL, OPTION_FILE_ALIGNMENT},
267     {"heap", required_argument, NULL, OPTION_HEAP},
268     {"image-base", required_argument, NULL, OPTION_IMAGE_BASE},
269     {"major-image-version", required_argument, NULL, OPTION_MAJOR_IMAGE_VERSION},
270     {"major-os-version", required_argument, NULL, OPTION_MAJOR_OS_VERSION},
271     {"major-subsystem-version", required_argument, NULL, OPTION_MAJOR_SUBSYSTEM_VERSION},
272     {"minor-image-version", required_argument, NULL, OPTION_MINOR_IMAGE_VERSION},
273     {"minor-os-version", required_argument, NULL, OPTION_MINOR_OS_VERSION},
274     {"minor-subsystem-version", required_argument, NULL, OPTION_MINOR_SUBSYSTEM_VERSION},
275     {"section-alignment", required_argument, NULL, OPTION_SECTION_ALIGNMENT},
276     {"stack", required_argument, NULL, OPTION_STACK},
277     {"subsystem", required_argument, NULL, OPTION_SUBSYSTEM},
278     {"support-old-code", no_argument, NULL, OPTION_SUPPORT_OLD_CODE},
279     {"use-nul-prefixed-import-tables", no_argument, NULL,
280      OPTION_USE_NUL_PREFIXED_IMPORT_TABLES},
281     {"no-leading-underscore", no_argument, NULL, OPTION_NO_LEADING_UNDERSCORE},
282     {"leading-underscore", no_argument, NULL, OPTION_LEADING_UNDERSCORE},
283 #ifdef DLL_SUPPORT
284     /* getopt allows abbreviations, so we do this to stop it
285        from treating -o as an abbreviation for this option.  */
286     {"output-def", required_argument, NULL, OPTION_OUT_DEF},
287     {"output-def", required_argument, NULL, OPTION_OUT_DEF},
288     {"export-all-symbols", no_argument, NULL, OPTION_EXPORT_ALL},
289     {"exclude-symbols", required_argument, NULL, OPTION_EXCLUDE_SYMBOLS},
290     {"exclude-all-symbols", no_argument, NULL, OPTION_EXCLUDE_ALL_SYMBOLS},
291     {"exclude-libs", required_argument, NULL, OPTION_EXCLUDE_LIBS},
292     {"exclude-modules-for-implib", required_argument, NULL, OPTION_EXCLUDE_MODULES_FOR_IMPLIB},
293     {"kill-at", no_argument, NULL, OPTION_KILL_ATS},
294     {"add-stdcall-alias", no_argument, NULL, OPTION_STDCALL_ALIASES},
295     {"enable-stdcall-fixup", no_argument, NULL, OPTION_ENABLE_STDCALL_FIXUP},
296     {"disable-stdcall-fixup", no_argument, NULL, OPTION_DISABLE_STDCALL_FIXUP},
297     {"warn-duplicate-exports", no_argument, NULL, OPTION_WARN_DUPLICATE_EXPORTS},
298     /* getopt() allows abbreviations, so we do this to stop it from
299        treating -c as an abbreviation for these --compat-implib.  */
300     {"compat-implib", no_argument, NULL, OPTION_IMP_COMPAT},
301     {"compat-implib", no_argument, NULL, OPTION_IMP_COMPAT},
302     {"enable-auto-image-base", no_argument, NULL, OPTION_ENABLE_AUTO_IMAGE_BASE},
303     {"disable-auto-image-base", no_argument, NULL, OPTION_DISABLE_AUTO_IMAGE_BASE},
304     {"dll-search-prefix", required_argument, NULL, OPTION_DLL_SEARCH_PREFIX},
305     {"no-default-excludes", no_argument, NULL, OPTION_NO_DEFAULT_EXCLUDES},
306     {"enable-auto-import", no_argument, NULL, OPTION_DLL_ENABLE_AUTO_IMPORT},
307     {"disable-auto-import", no_argument, NULL, OPTION_DLL_DISABLE_AUTO_IMPORT},
308     {"enable-extra-pep-debug", no_argument, NULL, OPTION_ENABLE_EXTRA_PE_DEBUG},
309     {"enable-runtime-pseudo-reloc", no_argument, NULL, OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC},
310     {"disable-runtime-pseudo-reloc", no_argument, NULL, OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC},
311     {"enable-runtime-pseudo-reloc-v2", no_argument, NULL, OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2},
312 #endif
313     {"enable-long-section-names", no_argument, NULL, OPTION_ENABLE_LONG_SECTION_NAMES},
314     {"disable-long-section-names", no_argument, NULL, OPTION_DISABLE_LONG_SECTION_NAMES},
315     {"high-entropy-va", no_argument, NULL, OPTION_HIGH_ENTROPY_VA},
316     {"dynamicbase",no_argument, NULL, OPTION_DYNAMIC_BASE},
317     {"forceinteg", no_argument, NULL, OPTION_FORCE_INTEGRITY},
318     {"nxcompat", no_argument, NULL, OPTION_NX_COMPAT},
319     {"no-isolation", no_argument, NULL, OPTION_NO_ISOLATION},
320     {"no-seh", no_argument, NULL, OPTION_NO_SEH},
321     {"no-bind", no_argument, NULL, OPTION_NO_BIND},
322     {"wdmdriver", no_argument, NULL, OPTION_WDM_DRIVER},
323     {"tsaware", no_argument, NULL, OPTION_TERMINAL_SERVER_AWARE},
324     {"insert-timestamp", no_argument, NULL, OPTION_INSERT_TIMESTAMP},
325     {"no-insert-timestamp", no_argument, NULL, OPTION_NO_INSERT_TIMESTAMP},
326     {"build-id", optional_argument, NULL, OPTION_BUILD_ID},
327     {NULL, no_argument, NULL, 0}
328   };
329
330   *longopts
331     = xrealloc (*longopts, nl * sizeof (struct option) + sizeof (xtra_long));
332   memcpy (*longopts + nl, &xtra_long, sizeof (xtra_long));
333 }
334
335 /* PE/WIN32; added routines to get the subsystem type, heap and/or stack
336    parameters which may be input from the command line.  */
337
338 typedef struct
339 {
340   void *ptr;
341   int size;
342   bfd_vma value;
343   char *symbol;
344   int inited;
345   /* FALSE for an assembly level symbol and TRUE for a C visible symbol.
346      C visible symbols can be prefixed by underscore dependent on target's
347      settings.  */
348   bfd_boolean is_c_symbol;
349 } definfo;
350
351 #define GET_INIT_SYMBOL_NAME(IDX) \
352   (init[(IDX)].symbol \
353    + ((!init[(IDX)].is_c_symbol || is_underscoring () == 1) ? 0 : 1))
354
355 /* Decorates the C visible symbol by underscore, if target requires.  */
356 #define U(CSTR) \
357   ((is_underscoring () == 0) ? CSTR : "_" CSTR)
358
359 #define D(field,symbol,def,usc)  {&pep.field, sizeof (pep.field), def, symbol, 0, usc}
360
361 static definfo init[] =
362 {
363   /* imagebase must be first */
364 #define IMAGEBASEOFF 0
365   D(ImageBase,"__image_base__", NT_EXE_IMAGE_BASE, FALSE),
366 #define DLLOFF 1
367   {&dll, sizeof(dll), 0, "__dll__", 0, FALSE},
368 #define MSIMAGEBASEOFF  2
369   D(ImageBase, "___ImageBase", NT_EXE_IMAGE_BASE, TRUE),
370   D(SectionAlignment,"__section_alignment__", PE_DEF_SECTION_ALIGNMENT, FALSE),
371   D(FileAlignment,"__file_alignment__", PE_DEF_FILE_ALIGNMENT, FALSE),
372   D(MajorOperatingSystemVersion,"__major_os_version__", 4, FALSE),
373   D(MinorOperatingSystemVersion,"__minor_os_version__", 0, FALSE),
374   D(MajorImageVersion,"__major_image_version__", 0, FALSE),
375   D(MinorImageVersion,"__minor_image_version__", 0, FALSE),
376   D(MajorSubsystemVersion,"__major_subsystem_version__", 5, FALSE),
377   D(MinorSubsystemVersion,"__minor_subsystem_version__", 2, FALSE),
378   D(Subsystem,"__subsystem__", ${SUBSYSTEM}, FALSE),
379   D(SizeOfStackReserve,"__size_of_stack_reserve__", 0x200000, FALSE),
380   D(SizeOfStackCommit,"__size_of_stack_commit__", 0x1000, FALSE),
381   D(SizeOfHeapReserve,"__size_of_heap_reserve__", 0x100000, FALSE),
382   D(SizeOfHeapCommit,"__size_of_heap_commit__", 0x1000, FALSE),
383   D(LoaderFlags,"__loader_flags__", 0x0, FALSE),
384   D(DllCharacteristics, "__dll_characteristics__", 0x0, FALSE),
385   { NULL, 0, 0, NULL, 0, FALSE}
386 };
387
388
389 static void
390 gld_${EMULATION_NAME}_list_options (FILE *file)
391 {
392   fprintf (file, _("  --base_file <basefile>             Generate a base file for relocatable DLLs\n"));
393   fprintf (file, _("  --dll                              Set image base to the default for DLLs\n"));
394   fprintf (file, _("  --file-alignment <size>            Set file alignment\n"));
395   fprintf (file, _("  --heap <size>                      Set initial size of the heap\n"));
396   fprintf (file, _("  --image-base <address>             Set start address of the executable\n"));
397   fprintf (file, _("  --major-image-version <number>     Set version number of the executable\n"));
398   fprintf (file, _("  --major-os-version <number>        Set minimum required OS version\n"));
399   fprintf (file, _("  --major-subsystem-version <number> Set minimum required OS subsystem version\n"));
400   fprintf (file, _("  --minor-image-version <number>     Set revision number of the executable\n"));
401   fprintf (file, _("  --minor-os-version <number>        Set minimum required OS revision\n"));
402   fprintf (file, _("  --minor-subsystem-version <number> Set minimum required OS subsystem revision\n"));
403   fprintf (file, _("  --section-alignment <size>         Set section alignment\n"));
404   fprintf (file, _("  --stack <size>                     Set size of the initial stack\n"));
405   fprintf (file, _("  --subsystem <name>[:<version>]     Set required OS subsystem [& version]\n"));
406   fprintf (file, _("  --support-old-code                 Support interworking with old code\n"));
407   fprintf (file, _("  --[no-]leading-underscore          Set explicit symbol underscore prefix mode\n"));
408   fprintf (file, _("  --[no-]insert-timestamp            Use a real timestamp rather than zero (default)\n"));
409   fprintf (file, _("                                     This makes binaries non-deterministic\n"));
410 #ifdef DLL_SUPPORT
411   fprintf (file, _("  --add-stdcall-alias                Export symbols with and without @nn\n"));
412   fprintf (file, _("  --disable-stdcall-fixup            Don't link _sym to _sym@nn\n"));
413   fprintf (file, _("  --enable-stdcall-fixup             Link _sym to _sym@nn without warnings\n"));
414   fprintf (file, _("  --exclude-symbols sym,sym,...      Exclude symbols from automatic export\n"));
415   fprintf (file, _("  --exclude-all-symbols              Exclude all symbols from automatic export\n"));
416   fprintf (file, _("  --exclude-libs lib,lib,...         Exclude libraries from automatic export\n"));
417   fprintf (file, _("  --exclude-modules-for-implib mod,mod,...\n"));
418   fprintf (file, _("                                     Exclude objects, archive members from auto\n"));
419   fprintf (file, _("                                     export, place into import library instead\n"));
420   fprintf (file, _("  --export-all-symbols               Automatically export all globals to DLL\n"));
421   fprintf (file, _("  --kill-at                          Remove @nn from exported symbols\n"));
422   fprintf (file, _("  --output-def <file>                Generate a .DEF file for the built DLL\n"));
423   fprintf (file, _("  --warn-duplicate-exports           Warn about duplicate exports\n"));
424   fprintf (file, _("  --compat-implib                    Create backward compatible import libs;\n\
425                                        create __imp_<SYMBOL> as well\n"));
426   fprintf (file, _("  --enable-auto-image-base           Automatically choose image base for DLLs\n\
427                                        unless user specifies one\n"));
428   fprintf (file, _("  --disable-auto-image-base          Do not auto-choose image base (default)\n"));
429   fprintf (file, _("  --dll-search-prefix=<string>       When linking dynamically to a dll without\n\
430                                        an importlib, use <string><basename>.dll\n\
431                                        in preference to lib<basename>.dll \n"));
432   fprintf (file, _("  --enable-auto-import               Do sophisticated linking of _sym to\n\
433                                        __imp_sym for DATA references\n"));
434   fprintf (file, _("  --disable-auto-import              Do not auto-import DATA items from DLLs\n"));
435   fprintf (file, _("  --enable-runtime-pseudo-reloc      Work around auto-import limitations by\n\
436                                        adding pseudo-relocations resolved at\n\
437                                        runtime\n"));
438   fprintf (file, _("  --disable-runtime-pseudo-reloc     Do not add runtime pseudo-relocations for\n\
439                                        auto-imported DATA\n"));
440   fprintf (file, _("  --enable-extra-pep-debug            Enable verbose debug output when building\n\
441                                        or linking to DLLs (esp. auto-import)\n"));
442   fprintf (file, _("  --enable-long-section-names        Use long COFF section names even in\n\
443                                        executable image files\n"));
444   fprintf (file, _("  --disable-long-section-names       Never use long COFF section names, even\n\
445                                        in object files\n"));
446   fprintf (file, _("  --high-entropy-va                  Image is compatible with 64-bit address space\n\
447                                        layout randomization (ASLR)\n"));
448   fprintf (file, _("  --dynamicbase                      Image base address may be relocated using\n\
449                                        address space layout randomization (ASLR)\n"));
450   fprintf (file, _("  --forceinteg               Code integrity checks are enforced\n"));
451   fprintf (file, _("  --nxcompat                 Image is compatible with data execution prevention\n"));
452   fprintf (file, _("  --no-isolation             Image understands isolation but do not isolate the image\n"));
453   fprintf (file, _("  --no-seh                   Image does not use SEH; no SE handler may\n\
454                                        be called in this image\n"));
455   fprintf (file, _("  --no-bind                  Do not bind this image\n"));
456   fprintf (file, _("  --wdmdriver                Driver uses the WDM model\n"));
457   fprintf (file, _("  --tsaware                  Image is Terminal Server aware\n"));
458   fprintf (file, _("  --build-id[=STYLE]         Generate build ID\n"));
459 #endif
460 }
461
462
463 static void
464 set_pep_name (char *name, bfd_vma val)
465 {
466   int i;
467   is_underscoring ();
468   /* Find the name and set it.  */
469   for (i = 0; init[i].ptr; i++)
470     {
471       if (strcmp (name, GET_INIT_SYMBOL_NAME (i)) == 0)
472         {
473           init[i].value = val;
474           init[i].inited = 1;
475           if (strcmp (name,"__image_base__") == 0)
476             set_pep_name (U ("__ImageBase"), val);
477           return;
478         }
479     }
480   abort ();
481 }
482
483 static void
484 set_entry_point (void)
485 {
486   const char *entry;
487   const char *initial_symbol_char;
488   int i;
489
490   static const struct
491   {
492     const int value;
493     const char *entry;
494   }
495   v[] =
496     {
497       { 1, "NtProcessStartup"  },
498       { 2, "WinMainCRTStartup" },
499       { 3, "mainCRTStartup"    },
500       { 7, "__PosixProcessStartup" },
501       { 9, "WinMainCRTStartup" },
502       {14, "mainCRTStartup"    },
503       { 0, NULL          }
504     };
505
506   /* Entry point name for arbitrary subsystem numbers.  */
507   static const char default_entry[] = "mainCRTStartup";
508
509   if (bfd_link_pic (&link_info) || dll)
510     {
511       entry = "DllMainCRTStartup";
512     }
513   else
514     {
515       for (i = 0; v[i].entry; i++)
516         if (v[i].value == pep_subsystem)
517           break;
518
519       /* If no match, use the default.  */
520       if (v[i].entry != NULL)
521         entry = v[i].entry;
522       else
523         entry = default_entry;
524     }
525
526   /* Now we check target's default for getting proper symbol_char.  */
527   initial_symbol_char = (is_underscoring () != 0 ? "_" : "");
528
529   if (*initial_symbol_char != '\0')
530     {
531       char *alc_entry;
532
533       /* lang_default_entry expects its argument to be permanently
534          allocated, so we don't free this string.  */
535       alc_entry = xmalloc (strlen (initial_symbol_char)
536                            + strlen (entry)
537                            + 1);
538       strcpy (alc_entry, initial_symbol_char);
539       strcat (alc_entry, entry);
540       entry = alc_entry;
541     }
542
543   lang_default_entry (entry);
544 }
545
546 static void
547 set_pep_subsystem (void)
548 {
549   const char *sver;
550   char *end;
551   int len;
552   int i;
553   unsigned long temp_subsystem;
554   static const struct
555     {
556       const char *name;
557       const int value;
558     }
559   v[] =
560     {
561       { "native",  1 },
562       { "windows", 2 },
563       { "console", 3 },
564       { "posix",   7 },
565       { "wince",   9 },
566       { "xbox",   14 },
567       { NULL, 0 }
568     };
569
570   /* Check for the presence of a version number.  */
571   sver = strchr (optarg, ':');
572   if (sver == NULL)
573     len = strlen (optarg);
574   else
575     {
576       len = sver - optarg;
577       set_pep_name ("__major_subsystem_version__",
578                     strtoul (sver + 1, &end, 0));
579       if (*end == '.')
580         set_pep_name ("__minor_subsystem_version__",
581                       strtoul (end + 1, &end, 0));
582       if (*end != '\0')
583         einfo (_("%P: warning: bad version number in -subsystem option\n"));
584     }
585
586   /* Check for numeric subsystem.  */
587   temp_subsystem = strtoul (optarg, & end, 0);
588   if ((*end == ':' || *end == '\0') && (temp_subsystem < 65536))
589     {
590       /* Search list for a numeric match to use its entry point.  */
591       for (i = 0; v[i].name; i++)
592         if (v[i].value == (int) temp_subsystem)
593           break;
594
595       /* Use this subsystem.  */
596       pep_subsystem = (int) temp_subsystem;
597     }
598   else
599     {
600       /* Search for subsystem by name.  */
601       for (i = 0; v[i].name; i++)
602         if (strncmp (optarg, v[i].name, len) == 0
603             && v[i].name[len] == '\0')
604           break;
605
606       if (v[i].name == NULL)
607         {
608           einfo (_("%F%P: invalid subsystem type %s\n"), optarg);
609           return;
610         }
611
612       pep_subsystem = v[i].value;
613     }
614
615   set_pep_name ("__subsystem__", pep_subsystem);
616
617   return;
618 }
619
620
621 static void
622 set_pep_value (char *name)
623 {
624   char *end;
625
626   set_pep_name (name,  (bfd_vma) strtoull (optarg, &end, 0));
627
628   if (end == optarg)
629     einfo (_("%F%P: invalid hex number for PE parameter '%s'\n"), optarg);
630
631   optarg = end;
632 }
633
634
635 static void
636 set_pep_stack_heap (char *resname, char *comname)
637 {
638   set_pep_value (resname);
639
640   if (*optarg == ',')
641     {
642       optarg++;
643       set_pep_value (comname);
644     }
645   else if (*optarg)
646     einfo (_("%F%P: strange hex info for PE parameter '%s'\n"), optarg);
647 }
648
649 #define DEFAULT_BUILD_ID_STYLE  "md5"
650
651 static bfd_boolean
652 gld${EMULATION_NAME}_handle_option (int optc)
653 {
654   is_underscoring ();
655   switch (optc)
656     {
657     default:
658       return FALSE;
659
660     case OPTION_BASE_FILE:
661       link_info.base_file = fopen (optarg, FOPEN_WB);
662       if (link_info.base_file == NULL)
663         einfo (_("%F%P: cannot open base file %s\n"), optarg);
664       break;
665
666       /* PE options.  */
667     case OPTION_HEAP:
668       set_pep_stack_heap ("__size_of_heap_reserve__", "__size_of_heap_commit__");
669       break;
670     case OPTION_STACK:
671       set_pep_stack_heap ("__size_of_stack_reserve__", "__size_of_stack_commit__");
672       break;
673     case OPTION_SUBSYSTEM:
674       set_pep_subsystem ();
675       break;
676     case OPTION_MAJOR_OS_VERSION:
677       set_pep_value ("__major_os_version__");
678       break;
679     case OPTION_MINOR_OS_VERSION:
680       set_pep_value ("__minor_os_version__");
681       break;
682     case OPTION_MAJOR_SUBSYSTEM_VERSION:
683       set_pep_value ("__major_subsystem_version__");
684       break;
685     case OPTION_MINOR_SUBSYSTEM_VERSION:
686       set_pep_value ("__minor_subsystem_version__");
687       break;
688     case OPTION_MAJOR_IMAGE_VERSION:
689       set_pep_value ("__major_image_version__");
690       break;
691     case OPTION_MINOR_IMAGE_VERSION:
692       set_pep_value ("__minor_image_version__");
693       break;
694     case OPTION_FILE_ALIGNMENT:
695       set_pep_value ("__file_alignment__");
696       break;
697     case OPTION_SECTION_ALIGNMENT:
698       set_pep_value ("__section_alignment__");
699       break;
700     case OPTION_DLL:
701       set_pep_name ("__dll__", 1);
702       break;
703     case OPTION_IMAGE_BASE:
704       set_pep_value ("__image_base__");
705       break;
706     case OPTION_SUPPORT_OLD_CODE:
707       support_old_code = 1;
708       break;
709     case OPTION_USE_NUL_PREFIXED_IMPORT_TABLES:
710       pep_use_nul_prefixed_import_tables = TRUE;
711       break;
712     case OPTION_NO_LEADING_UNDERSCORE:
713       pep_leading_underscore = 0;
714       break;
715     case OPTION_LEADING_UNDERSCORE:
716       pep_leading_underscore = 1;
717       break;
718     case OPTION_INSERT_TIMESTAMP:
719       insert_timestamp = TRUE;
720       break;
721     case OPTION_NO_INSERT_TIMESTAMP:
722       insert_timestamp = FALSE;
723       break;
724 #ifdef DLL_SUPPORT
725     case OPTION_OUT_DEF:
726       pep_out_def_filename = xstrdup (optarg);
727       break;
728     case OPTION_EXPORT_ALL:
729       pep_dll_export_everything = 1;
730       break;
731     case OPTION_EXCLUDE_SYMBOLS:
732       pep_dll_add_excludes (optarg, EXCLUDESYMS);
733       break;
734     case OPTION_EXCLUDE_ALL_SYMBOLS:
735       pep_dll_exclude_all_symbols = 1;
736       break;
737     case OPTION_EXCLUDE_LIBS:
738       pep_dll_add_excludes (optarg, EXCLUDELIBS);
739       break;
740     case OPTION_EXCLUDE_MODULES_FOR_IMPLIB:
741       pep_dll_add_excludes (optarg, EXCLUDEFORIMPLIB);
742       break;
743     case OPTION_KILL_ATS:
744       pep_dll_kill_ats = 1;
745       break;
746     case OPTION_STDCALL_ALIASES:
747       pep_dll_stdcall_aliases = 1;
748       break;
749     case OPTION_ENABLE_STDCALL_FIXUP:
750       pep_enable_stdcall_fixup = 1;
751       break;
752     case OPTION_DISABLE_STDCALL_FIXUP:
753       pep_enable_stdcall_fixup = 0;
754       break;
755     case OPTION_WARN_DUPLICATE_EXPORTS:
756       pep_dll_warn_dup_exports = 1;
757       break;
758     case OPTION_IMP_COMPAT:
759       pep_dll_compat_implib = 1;
760       break;
761     case OPTION_ENABLE_AUTO_IMAGE_BASE:
762       pep_enable_auto_image_base = 1;
763       break;
764     case OPTION_DISABLE_AUTO_IMAGE_BASE:
765       pep_enable_auto_image_base = 0;
766       break;
767     case OPTION_DLL_SEARCH_PREFIX:
768       pep_dll_search_prefix = xstrdup (optarg);
769       break;
770     case OPTION_NO_DEFAULT_EXCLUDES:
771       pep_dll_do_default_excludes = 0;
772       break;
773     case OPTION_DLL_ENABLE_AUTO_IMPORT:
774       link_info.pei386_auto_import = 1;
775       break;
776     case OPTION_DLL_DISABLE_AUTO_IMPORT:
777       link_info.pei386_auto_import = 0;
778       break;
779     case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC:
780       link_info.pei386_runtime_pseudo_reloc = 2;
781       break;
782     case OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC:
783       link_info.pei386_runtime_pseudo_reloc = 0;
784       break;
785     case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2:
786       link_info.pei386_runtime_pseudo_reloc = 2;
787       break;
788     case OPTION_ENABLE_EXTRA_PE_DEBUG:
789       pep_dll_extra_pe_debug = 1;
790       break;
791 #endif
792     case OPTION_ENABLE_LONG_SECTION_NAMES:
793       pep_use_coff_long_section_names = 1;
794       break;
795     case OPTION_DISABLE_LONG_SECTION_NAMES:
796       pep_use_coff_long_section_names = 0;
797       break;
798     /*  Get DLLCharacteristics bits  */
799     case OPTION_HIGH_ENTROPY_VA:
800       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
801       break;
802     case OPTION_DYNAMIC_BASE:
803       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
804       break;
805     case OPTION_FORCE_INTEGRITY:
806       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
807       break;
808     case OPTION_NX_COMPAT:
809       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
810       break;
811     case OPTION_NO_ISOLATION:
812       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_ISOLATION;
813       break;
814     case OPTION_NO_SEH:
815       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_SEH;
816       break;
817     case OPTION_NO_BIND:
818       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_BIND;
819       break;
820     case OPTION_WDM_DRIVER:
821       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_WDM_DRIVER;
822       break;
823     case OPTION_TERMINAL_SERVER_AWARE:
824       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
825       break;
826     case OPTION_BUILD_ID:
827       if (emit_build_id != NULL)
828         {
829           free ((char *) emit_build_id);
830           emit_build_id = NULL;
831         }
832       if (optarg == NULL)
833         optarg = DEFAULT_BUILD_ID_STYLE;
834       if (strcmp (optarg, "none"))
835         emit_build_id = xstrdup (optarg);
836       break;
837     }
838
839   /*  Set DLLCharacteristics bits  */
840   set_pep_name ("__dll_characteristics__", pe_dll_characteristics);
841
842   return TRUE;
843 }
844 \f
845
846 #ifdef DLL_SUPPORT
847 static unsigned long
848 strhash (const char *str)
849 {
850   const unsigned char *s;
851   unsigned long hash;
852   unsigned int c;
853   unsigned int len;
854
855   hash = 0;
856   len = 0;
857   s = (const unsigned char *) str;
858   while ((c = *s++) != '\0')
859     {
860       hash += c + (c << 17);
861       hash ^= hash >> 2;
862       ++len;
863     }
864   hash += len + (len << 17);
865   hash ^= hash >> 2;
866
867   return hash;
868 }
869
870 /* Use the output file to create a image base for relocatable DLLs.  */
871
872 static bfd_vma
873 compute_dll_image_base (const char *ofile)
874 {
875   bfd_vma hash = (bfd_vma) strhash (ofile);
876   return NT_DLL_AUTO_IMAGE_BASE + ((hash << 16) & NT_DLL_AUTO_IMAGE_MASK);
877 }
878 #endif
879
880 /* Assign values to the special symbols before the linker script is
881    read.  */
882
883 static void
884 gld_${EMULATION_NAME}_set_symbols (void)
885 {
886   /* Run through and invent symbols for all the
887      names and insert the defaults.  */
888   int j;
889
890   is_underscoring ();
891
892   if (!init[IMAGEBASEOFF].inited)
893     {
894       if (bfd_link_relocatable (&link_info))
895         init[IMAGEBASEOFF].value = 0;
896       else if (init[DLLOFF].value || bfd_link_dll (&link_info))
897         {
898 #ifdef DLL_SUPPORT
899           init[IMAGEBASEOFF].value = (pep_enable_auto_image_base
900                                       ? compute_dll_image_base (output_filename)
901                                       : NT_DLL_IMAGE_BASE);
902 #else
903           init[IMAGEBASEOFF].value = NT_DLL_IMAGE_BASE;
904 #endif
905         }
906       else
907         init[IMAGEBASEOFF].value = NT_EXE_IMAGE_BASE;
908       init[MSIMAGEBASEOFF].value = init[IMAGEBASEOFF].value;
909     }
910
911   /* Don't do any symbol assignments if this is a relocatable link.  */
912   if (bfd_link_relocatable (&link_info))
913     return;
914
915   /* Glue the assignments into the abs section.  */
916   push_stat_ptr (&abs_output_section->children);
917
918   for (j = 0; init[j].ptr; j++)
919     {
920       bfd_vma val = init[j].value;
921       lang_assignment_statement_type *rv;
922
923       rv = lang_add_assignment (exp_assign (GET_INIT_SYMBOL_NAME (j),
924                                             exp_intop (val), FALSE));
925       if (init[j].size == sizeof (short))
926         *(short *) init[j].ptr = (short) val;
927       else if (init[j].size == sizeof (int))
928         *(int *) init[j].ptr = (int) val;
929       else if (init[j].size == sizeof (long))
930         *(long *) init[j].ptr = (long) val;
931       /* This might be a long long or other special type.  */
932       else if (init[j].size == sizeof (bfd_vma))
933         *(bfd_vma *) init[j].ptr = val;
934       else      abort ();
935       if (j == IMAGEBASEOFF)
936         image_base_statement = rv;
937     }
938   /* Restore the pointer.  */
939   pop_stat_ptr ();
940
941   if (pep.FileAlignment > pep.SectionAlignment)
942     {
943       einfo (_("%P: warning, file alignment > section alignment\n"));
944     }
945 }
946
947 /* This is called after the linker script and the command line options
948    have been read.  */
949
950 static void
951 gld_${EMULATION_NAME}_after_parse (void)
952 {
953   /* PR ld/6744:  Warn the user if they have used an ELF-only
954      option hoping it will work on PE+.  */
955   if (link_info.export_dynamic)
956     einfo (_("%P: warning: --export-dynamic is not supported for PE+ "
957       "targets, did you mean --export-all-symbols?\n"));
958
959   set_entry_point ();
960
961   after_parse_default ();
962 }
963
964 #ifdef DLL_SUPPORT
965 static struct bfd_link_hash_entry *pep_undef_found_sym;
966
967 static bfd_boolean
968 pep_undef_cdecl_match (struct bfd_link_hash_entry *h, void *inf)
969 {
970   int sl;
971   char *string = inf;
972   const char *hs = h->root.string;
973
974   sl = strlen (string);
975   if (h->type == bfd_link_hash_defined
976       && ((*hs == '@' && *string == '_'
977                    && strncmp (hs + 1, string + 1, sl - 1) == 0)
978                   || strncmp (hs, string, sl) == 0)
979       && h->root.string[sl] == '@')
980     {
981       pep_undef_found_sym = h;
982       return FALSE;
983     }
984   return TRUE;
985 }
986
987 static void
988 pep_fixup_stdcalls (void)
989 {
990   static int gave_warning_message = 0;
991   struct bfd_link_hash_entry *undef, *sym;
992
993   if (pep_dll_extra_pe_debug)
994     printf ("%s\n", __FUNCTION__);
995
996   for (undef = link_info.hash->undefs; undef; undef=undef->u.undef.next)
997     if (undef->type == bfd_link_hash_undefined)
998       {
999         char* at = strchr (undef->root.string, '@');
1000         int lead_at = (*undef->root.string == '@');
1001         if (lead_at)
1002           at = strchr (undef->root.string + 1, '@');
1003         if (at || lead_at)
1004           {
1005             /* The symbol is a stdcall symbol, so let's look for a
1006                cdecl symbol with the same name and resolve to that.  */
1007             char *cname = xstrdup (undef->root.string);
1008
1009             if (lead_at)
1010               *cname = '_';
1011             at = strchr (cname, '@');
1012             if (at)
1013               *at = 0;
1014             sym = bfd_link_hash_lookup (link_info.hash, cname, 0, 0, 1);
1015
1016             if (sym && sym->type == bfd_link_hash_defined)
1017               {
1018                 undef->type = bfd_link_hash_defined;
1019                 undef->u.def.value = sym->u.def.value;
1020                 undef->u.def.section = sym->u.def.section;
1021
1022                 if (pep_enable_stdcall_fixup == -1)
1023                   {
1024                     einfo (_("warning: resolving %s by linking to %s\n"),
1025                            undef->root.string, cname);
1026                     if (! gave_warning_message)
1027                       {
1028                         gave_warning_message = 1;
1029                         einfo (_("Use --enable-stdcall-fixup to disable these warnings\n"));
1030                         einfo (_("Use --disable-stdcall-fixup to disable these fixups\n"));
1031                       }
1032                   }
1033               }
1034           }
1035         else
1036           {
1037             /* The symbol is a cdecl symbol, so we look for stdcall
1038                symbols - which means scanning the whole symbol table.  */
1039             pep_undef_found_sym = 0;
1040             bfd_link_hash_traverse (link_info.hash, pep_undef_cdecl_match,
1041                                     (char *) undef->root.string);
1042             sym = pep_undef_found_sym;
1043             if (sym)
1044               {
1045                 undef->type = bfd_link_hash_defined;
1046                 undef->u.def.value = sym->u.def.value;
1047                 undef->u.def.section = sym->u.def.section;
1048
1049                 if (pep_enable_stdcall_fixup == -1)
1050                   {
1051                     einfo (_("warning: resolving %s by linking to %s\n"),
1052                            undef->root.string, sym->root.string);
1053                     if (! gave_warning_message)
1054                       {
1055                         gave_warning_message = 1;
1056                         einfo (_("Use --enable-stdcall-fixup to disable these warnings\n"));
1057                         einfo (_("Use --disable-stdcall-fixup to disable these fixups\n"));
1058                       }
1059                   }
1060               }
1061           }
1062       }
1063 }
1064
1065 static void
1066 make_import_fixup (arelent *rel, asection *s, char *name, const char *symname)
1067 {
1068   struct bfd_symbol *sym = *rel->sym_ptr_ptr;
1069   char addend[8];
1070   bfd_vma _addend = 0;
1071   int suc = 0;
1072
1073   if (pep_dll_extra_pe_debug)
1074     printf ("arelent: %s@%#lx: add=%li\n", sym->name,
1075             (unsigned long) rel->address, (long) rel->addend);
1076
1077   memset (addend, 0, sizeof (addend));
1078   switch ((rel->howto->bitsize))
1079     {
1080     case 8:
1081       suc = bfd_get_section_contents (s->owner, s, addend, rel->address, 1);
1082       if (suc && rel->howto->pc_relative)
1083         _addend = bfd_get_signed_8 (s->owner, addend);
1084       else if (suc)
1085         _addend = bfd_get_8 (s->owner, addend);
1086       break;
1087     case 16:
1088       suc = bfd_get_section_contents (s->owner, s, addend, rel->address, 2);
1089       if (suc && rel->howto->pc_relative)
1090         _addend = bfd_get_signed_16 (s->owner, addend);
1091       else if (suc)
1092         _addend = bfd_get_16 (s->owner, addend);
1093       break;
1094     case 32:
1095       suc = bfd_get_section_contents (s->owner, s, addend, rel->address, 4);
1096       if (suc && rel->howto->pc_relative)
1097         _addend = bfd_get_signed_32 (s->owner, addend);
1098       else if (suc)
1099         _addend = bfd_get_32 (s->owner, addend);
1100       break;
1101     case 64:
1102       suc = bfd_get_section_contents (s->owner, s, addend, rel->address, 8);
1103       if (suc)
1104         _addend = bfd_get_64 (s->owner, addend);
1105       break;
1106     }
1107   if (! suc)
1108     einfo (_("%P: %C: cannot get section contents - auto-import exception\n"),
1109            s->owner, s, rel->address);
1110
1111   if (pep_dll_extra_pe_debug)
1112     {
1113       printf ("import of 0x%lx(0x%lx) sec_addr=0x%lx",
1114               (long) _addend, (long) rel->addend, (long) rel->address);
1115       if (rel->howto->pc_relative)
1116         printf (" pcrel");
1117       printf (" %d bit rel.\n", (int) rel->howto->bitsize);
1118     }
1119
1120   pep_create_import_fixup (rel, s, _addend, name, symname);
1121 }
1122
1123 static bfd_boolean
1124 pr_sym (struct bfd_hash_entry *h, void *inf ATTRIBUTE_UNUSED)
1125 {
1126   printf ("+%s\n", h->string);
1127
1128   return TRUE;
1129 }
1130 #endif /* DLL_SUPPORT */
1131
1132 static void
1133 debug_section_p (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
1134 {
1135   int *found = (int *) obj;
1136
1137   if (strncmp (".debug_", sect->name, sizeof (".debug_") - 1) == 0)
1138     *found = 1;
1139 }
1140
1141 static bfd_boolean
1142 pecoff_checksum_contents (bfd *abfd,
1143                           void (*process) (const void *, size_t, void *),
1144                           void *arg)
1145 {
1146   file_ptr filepos = (file_ptr) 0;
1147
1148   while (1)
1149     {
1150       unsigned char b;
1151       int status;
1152
1153       if (bfd_seek (abfd, filepos, SEEK_SET) != 0)
1154         return 0;
1155
1156       status = bfd_bread (&b, (bfd_size_type) 1, abfd);
1157       if (status < 1)
1158         {
1159           break;
1160         }
1161
1162       (*process) (&b, 1, arg);
1163       filepos += 1;
1164     }
1165
1166   return TRUE;
1167 }
1168
1169 static bfd_boolean
1170 write_build_id (bfd *abfd)
1171 {
1172   struct pe_tdata *t = pe_data (abfd);
1173   asection *asec;
1174   struct bfd_link_order *link_order = NULL;
1175   unsigned char *contents;
1176   bfd_size_type size;
1177   bfd_size_type build_id_size;
1178   unsigned char *build_id;
1179
1180   /* Find the section the .buildid output section has been merged info.  */
1181   for (asec = abfd->sections; asec != NULL; asec = asec->next)
1182     {
1183       struct bfd_link_order *l = NULL;
1184       for (l = asec->map_head.link_order; l != NULL; l = l->next)
1185         {
1186           if (l->type == bfd_indirect_link_order)
1187             {
1188               if (l->u.indirect.section == t->build_id.sec)
1189                 {
1190                   link_order = l;
1191                   break;
1192                 }
1193             }
1194         }
1195
1196       if (link_order)
1197         break;
1198     }
1199
1200   if (!link_order)
1201     {
1202       einfo (_("%P: warning: .buildid section discarded,"
1203                " --build-id ignored\n"));
1204       return TRUE;
1205     }
1206
1207   if (t->build_id.sec->contents == NULL)
1208     t->build_id.sec->contents = (unsigned char *) xmalloc (t->build_id.sec->size);
1209   contents = t->build_id.sec->contents;
1210   size = t->build_id.sec->size;
1211
1212   build_id_size = compute_build_id_size (t->build_id.style);
1213   build_id = xmalloc (build_id_size);
1214   generate_build_id (abfd, t->build_id.style, pecoff_checksum_contents, build_id, build_id_size);
1215
1216   bfd_vma ib = pe_data (link_info.output_bfd)->pe_opthdr.ImageBase;
1217
1218   /* Construct a debug directory entry which points to an immediately following CodeView record.  */
1219   struct internal_IMAGE_DEBUG_DIRECTORY idd;
1220   idd.Characteristics = 0;
1221   idd.TimeDateStamp = 0;
1222   idd.MajorVersion = 0;
1223   idd.MinorVersion = 0;
1224   idd.Type = PE_IMAGE_DEBUG_TYPE_CODEVIEW;
1225   idd.SizeOfData = sizeof (CV_INFO_PDB70) + 1;
1226   idd.AddressOfRawData = asec->vma - ib + link_order->offset
1227     + sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1228   idd.PointerToRawData = asec->filepos + link_order->offset
1229     + sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1230
1231   struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *)contents;
1232   _bfd_XXi_swap_debugdir_out (abfd, &idd, ext);
1233
1234   /* Write the debug directory enttry */
1235   if (bfd_seek (abfd, asec->filepos + link_order->offset, SEEK_SET) != 0)
1236     return 0;
1237
1238   if (bfd_bwrite (contents, size, abfd) != size)
1239     return 0;
1240
1241   /* Construct the CodeView record.  */
1242   CODEVIEW_INFO cvinfo;
1243   cvinfo.CVSignature = CVINFO_PDB70_CVSIGNATURE;
1244   cvinfo.Age = 1;
1245
1246   /* Zero pad or truncate the generated build_id to fit in the CodeView record.  */
1247   memset (&(cvinfo.Signature), 0, CV_INFO_SIGNATURE_LENGTH);
1248   memcpy (&(cvinfo.Signature), build_id, (build_id_size > CV_INFO_SIGNATURE_LENGTH)
1249           ? CV_INFO_SIGNATURE_LENGTH :  build_id_size);
1250
1251   free (build_id);
1252
1253   /* Write the codeview record.  */
1254   if (_bfd_XXi_write_codeview_record (abfd, idd.PointerToRawData, &cvinfo) == 0)
1255     return 0;
1256
1257   /* Record the location of the debug directory in the data directory.  */
1258   pe_data (link_info.output_bfd)->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
1259     = asec->vma  - ib + link_order->offset;
1260   pe_data (link_info.output_bfd)->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
1261     = sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1262
1263   return TRUE;
1264 }
1265
1266 /* Make .buildid section, and set up coff_tdata->build_id. */
1267 static bfd_boolean
1268 setup_build_id (bfd *ibfd)
1269 {
1270   asection *s;
1271   flagword flags;
1272
1273   if (!validate_build_id_style (emit_build_id))
1274     {
1275       einfo (_("%P: warning: unrecognized --build-id style ignored\n"));
1276       return FALSE;
1277     }
1278
1279   flags = (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1280            | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1281   s = bfd_make_section_anyway_with_flags (ibfd, ".buildid", flags);
1282   if (s != NULL)
1283     {
1284       struct pe_tdata *t = pe_data (link_info.output_bfd);
1285       t->build_id.after_write_object_contents = &write_build_id;
1286       t->build_id.style = emit_build_id;
1287       t->build_id.sec = s;
1288
1289       /* Section is a fixed size:
1290          One IMAGE_DEBUG_DIRECTORY entry, of type IMAGE_DEBUG_TYPE_CODEVIEW,
1291          pointing at a CV_INFO_PDB70 record containing the build-id, with a
1292          null byte for PdbFileName.  */
1293       s->size = sizeof (struct external_IMAGE_DEBUG_DIRECTORY)
1294         + sizeof (CV_INFO_PDB70) + 1;
1295
1296       return TRUE;
1297     }
1298
1299   einfo (_("%P: warning: cannot create .buildid section,"
1300            " --build-id ignored\n"));
1301   return FALSE;
1302 }
1303
1304 static void
1305 gld_${EMULATION_NAME}_after_open (void)
1306 {
1307   after_open_default ();
1308
1309   is_underscoring ();
1310 #ifdef DLL_SUPPORT
1311   if (pep_dll_extra_pe_debug)
1312     {
1313       bfd *a;
1314       struct bfd_link_hash_entry *sym;
1315
1316       printf ("%s()\n", __FUNCTION__);
1317
1318       for (sym = link_info.hash->undefs; sym; sym=sym->u.undef.next)
1319         printf ("-%s\n", sym->root.string);
1320       bfd_hash_traverse (&link_info.hash->table, pr_sym, NULL);
1321
1322       for (a = link_info.input_bfds; a; a = a->link.next)
1323         printf ("*%s\n",a->filename);
1324     }
1325 #endif
1326
1327   if (emit_build_id != NULL)
1328     {
1329       bfd *abfd;
1330
1331       /* Find a COFF input.  */
1332       for (abfd = link_info.input_bfds;
1333            abfd != (bfd *) NULL; abfd = abfd->link.next)
1334         if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
1335           break;
1336
1337       /* If there are no COFF input files do not try to
1338          add a build-id section.  */
1339       if (abfd == NULL
1340           || !setup_build_id (abfd))
1341         {
1342           free ((char *) emit_build_id);
1343           emit_build_id = NULL;
1344         }
1345     }
1346
1347   /* Pass the wacky PE command line options into the output bfd.
1348      FIXME: This should be done via a function, rather than by
1349      including an internal BFD header.  */
1350
1351   if (bfd_get_flavour (link_info.output_bfd) != bfd_target_coff_flavour
1352       || coff_data (link_info.output_bfd) == NULL
1353       || coff_data (link_info.output_bfd)->pe == 0)
1354     einfo (_("%F%P: cannot perform PE operations on non PE output file '%pB'\n"),
1355            link_info.output_bfd);
1356
1357   pe_data (link_info.output_bfd)->pe_opthdr = pep;
1358   pe_data (link_info.output_bfd)->dll = init[DLLOFF].value;
1359   pe_data (link_info.output_bfd)->real_flags |= real_flags;
1360   pe_data (link_info.output_bfd)->insert_timestamp = insert_timestamp;
1361
1362   /* At this point we must decide whether to use long section names
1363      in the output or not.  If the user hasn't explicitly specified
1364      on the command line, we leave it to the default for the format
1365      (object files yes, image files no), except if there is debug
1366      information present; GDB relies on the long section names to
1367      find it, so enable it in that case.  */
1368   if (pep_use_coff_long_section_names < 0 && link_info.strip == strip_none)
1369     {
1370       if (bfd_link_relocatable (&link_info))
1371         pep_use_coff_long_section_names = 1;
1372       else
1373         {
1374           /* Iterate over all sections of all input BFDs, checking
1375              for any that begin 'debug_' and are long names.  */
1376           LANG_FOR_EACH_INPUT_STATEMENT (is)
1377           {
1378             int found_debug = 0;
1379
1380             bfd_map_over_sections (is->the_bfd, debug_section_p, &found_debug);
1381             if (found_debug)
1382               {
1383                 pep_use_coff_long_section_names = 1;
1384                 break;
1385               }
1386           }
1387         }
1388     }
1389
1390   pep_output_file_set_long_section_names (link_info.output_bfd);
1391
1392 #ifdef DLL_SUPPORT
1393   pep_process_import_defs (link_info.output_bfd, &link_info);
1394
1395   if (link_info.pei386_auto_import) /* -1=warn or 1=enable */
1396     pep_find_data_imports (U ("_head_"), make_import_fixup);
1397
1398   /* The implementation of the feature is rather dumb and would cause the
1399      compilation time to go through the roof if there are many undefined
1400      symbols in the link, so it needs to be run after auto-import.  */
1401   if (pep_enable_stdcall_fixup) /* -1=warn or 1=enable */
1402     pep_fixup_stdcalls ();
1403
1404 #ifndef TARGET_IS_i386pep
1405   if (bfd_link_pic (&link_info))
1406 #else
1407   if (!bfd_link_relocatable (&link_info))
1408 #endif
1409     pep_dll_build_sections (link_info.output_bfd, &link_info);
1410
1411 #ifndef TARGET_IS_i386pep
1412   else
1413     pep_exe_build_sections (link_info.output_bfd, &link_info);
1414 #endif
1415 #endif /* DLL_SUPPORT */
1416
1417   {
1418     /* This next chunk of code tries to detect the case where you have
1419        two import libraries for the same DLL (specifically,
1420        symbolically linking libm.a and libc.a in cygwin to
1421        libcygwin.a).  In those cases, it's possible for function
1422        thunks from the second implib to be used but without the
1423        head/tail objects, causing an improper import table.  We detect
1424        those cases and rename the "other" import libraries to match
1425        the one the head/tail come from, so that the linker will sort
1426        things nicely and produce a valid import table.  */
1427
1428     LANG_FOR_EACH_INPUT_STATEMENT (is)
1429       {
1430         if (is->the_bfd->my_archive)
1431           {
1432             int idata2 = 0, reloc_count=0, is_imp = 0;
1433             asection *sec;
1434
1435             /* See if this is an import library thunk.  */
1436             for (sec = is->the_bfd->sections; sec; sec = sec->next)
1437               {
1438                 if (strcmp (sec->name, ".idata\$2") == 0)
1439                   idata2 = 1;
1440                 if (CONST_STRNEQ (sec->name, ".idata\$"))
1441                   is_imp = 1;
1442                 reloc_count += sec->reloc_count;
1443               }
1444
1445             if (is_imp && !idata2 && reloc_count)
1446               {
1447                 /* It is, look for the reference to head and see if it's
1448                    from our own library.  */
1449                 for (sec = is->the_bfd->sections; sec; sec = sec->next)
1450                   {
1451                     int i;
1452                     long relsize;
1453                     asymbol **symbols;
1454                     arelent **relocs;
1455                     int nrelocs;
1456
1457                     relsize = bfd_get_reloc_upper_bound (is->the_bfd, sec);
1458                     if (relsize < 1)
1459                       break;
1460
1461                     if (!bfd_generic_link_read_symbols (is->the_bfd))
1462                       {
1463                         einfo (_("%F%P: %pB: could not read symbols: %E\n"),
1464                                is->the_bfd);
1465                         return;
1466                       }
1467                     symbols = bfd_get_outsymbols (is->the_bfd);
1468
1469                     relocs = xmalloc ((size_t) relsize);
1470                     nrelocs = bfd_canonicalize_reloc (is->the_bfd, sec,
1471                                                       relocs, symbols);
1472                     if (nrelocs < 0)
1473                       {
1474                         free (relocs);
1475                         einfo (_("%X%P: unable to process relocs: %E\n"));
1476                         return;
1477                       }
1478
1479                     for (i = 0; i < nrelocs; i++)
1480                       {
1481                         struct bfd_symbol *s;
1482                         struct bfd_link_hash_entry * blhe;
1483                         char *other_bfd_filename;
1484                         char *n;
1485
1486                         s = (relocs[i]->sym_ptr_ptr)[0];
1487
1488                         if (s->flags & BSF_LOCAL)
1489                           continue;
1490
1491                         /* Thunk section with reloc to another bfd.  */
1492                         blhe = bfd_link_hash_lookup (link_info.hash,
1493                                                      s->name,
1494                                                      FALSE, FALSE, TRUE);
1495
1496                         if (blhe == NULL
1497                             || blhe->type != bfd_link_hash_defined)
1498                           continue;
1499
1500                         other_bfd_filename
1501                           = blhe->u.def.section->owner->my_archive
1502                             ? bfd_get_filename (blhe->u.def.section->owner->my_archive)
1503                             : bfd_get_filename (blhe->u.def.section->owner);
1504
1505                         if (filename_cmp (bfd_get_filename
1506                                             (is->the_bfd->my_archive),
1507                                           other_bfd_filename) == 0)
1508                           continue;
1509
1510                         /* Rename this implib to match the other one.  */
1511                         n = xmalloc (strlen (other_bfd_filename) + 1);
1512                         strcpy (n, other_bfd_filename);
1513                         is->the_bfd->my_archive->filename = n;
1514                       }
1515
1516                     free (relocs);
1517                     /* Note - we do not free the symbols,
1518                        they are now cached in the BFD.  */
1519                   }
1520               }
1521           }
1522       }
1523   }
1524
1525   {
1526     int is_ms_arch = 0;
1527     bfd *cur_arch = 0;
1528     lang_input_statement_type *is2;
1529     lang_input_statement_type *is3;
1530
1531     /* Careful - this is a shell script.  Watch those dollar signs! */
1532     /* Microsoft import libraries have every member named the same,
1533        and not in the right order for us to link them correctly.  We
1534        must detect these and rename the members so that they'll link
1535        correctly.  There are three types of objects: the head, the
1536        thunks, and the sentinel(s).  The head is easy; it's the one
1537        with idata2.  We assume that the sentinels won't have relocs,
1538        and the thunks will.  It's easier than checking the symbol
1539        table for external references.  */
1540     LANG_FOR_EACH_INPUT_STATEMENT (is)
1541       {
1542         if (is->the_bfd->my_archive)
1543           {
1544             char *pnt;
1545             bfd *arch = is->the_bfd->my_archive;
1546
1547             if (cur_arch != arch)
1548               {
1549                 cur_arch = arch;
1550                 is_ms_arch = 1;
1551
1552                 for (is3 = is;
1553                      is3 && is3->the_bfd->my_archive == arch;
1554                      is3 = (lang_input_statement_type *) is3->next)
1555                   {
1556                     /* A MS dynamic import library can also contain static
1557                        members, so look for the first element with a .dll
1558                        extension, and use that for the remainder of the
1559                        comparisons.  */
1560                     pnt = strrchr (is3->the_bfd->filename, '.');
1561                     if (pnt != NULL && filename_cmp (pnt, ".dll") == 0)
1562                       break;
1563                   }
1564
1565                 if (is3 == NULL)
1566                   is_ms_arch = 0;
1567                 else
1568                   {
1569                     /* OK, found one.  Now look to see if the remaining
1570                        (dynamic import) members use the same name.  */
1571                     for (is2 = is;
1572                          is2 && is2->the_bfd->my_archive == arch;
1573                          is2 = (lang_input_statement_type *) is2->next)
1574                       {
1575                         /* Skip static members, ie anything with a .obj
1576                            extension.  */
1577                         pnt = strrchr (is2->the_bfd->filename, '.');
1578                         if (pnt != NULL && filename_cmp (pnt, ".obj") == 0)
1579                           continue;
1580
1581                         if (filename_cmp (is3->the_bfd->filename,
1582                                           is2->the_bfd->filename))
1583                           {
1584                             is_ms_arch = 0;
1585                             break;
1586                           }
1587                       }
1588                   }
1589               }
1590
1591             /* This fragment might have come from an .obj file in a Microsoft
1592                import, and not an actual import record. If this is the case,
1593                then leave the filename alone.  */
1594             pnt = strrchr (is->the_bfd->filename, '.');
1595
1596             if (is_ms_arch && (filename_cmp (pnt, ".dll") == 0))
1597               {
1598                 int idata2 = 0, reloc_count=0;
1599                 asection *sec;
1600                 char *new_name, seq;
1601
1602                 for (sec = is->the_bfd->sections; sec; sec = sec->next)
1603                   {
1604                     if (strcmp (sec->name, ".idata\$2") == 0)
1605                       idata2 = 1;
1606                     reloc_count += sec->reloc_count;
1607                   }
1608
1609                 if (idata2) /* .idata2 is the TOC */
1610                   seq = 'a';
1611                 else if (reloc_count > 0) /* thunks */
1612                   seq = 'b';
1613                 else /* sentinel */
1614                   seq = 'c';
1615
1616                 new_name = xmalloc (strlen (is->the_bfd->filename) + 3);
1617                 sprintf (new_name, "%s.%c", is->the_bfd->filename, seq);
1618                 is->the_bfd->filename = new_name;
1619
1620                 new_name = xmalloc (strlen (is->filename) + 3);
1621                 sprintf (new_name, "%s.%c", is->filename, seq);
1622                 is->filename = new_name;
1623               }
1624           }
1625       }
1626   }
1627 }
1628 \f
1629 static void
1630 gld_${EMULATION_NAME}_before_allocation (void)
1631 {
1632   is_underscoring ();
1633   before_allocation_default ();
1634 }
1635 \f
1636 #ifdef DLL_SUPPORT
1637 /* This is called when an input file isn't recognized as a BFD.  We
1638    check here for .DEF files and pull them in automatically.  */
1639
1640 static int
1641 saw_option (char *option)
1642 {
1643   int i;
1644
1645   is_underscoring ();
1646
1647   for (i = 0; init[i].ptr; i++)
1648     if (strcmp (GET_INIT_SYMBOL_NAME (i), option) == 0)
1649       return init[i].inited;
1650   return 0;
1651 }
1652 #endif /* DLL_SUPPORT */
1653
1654 static bfd_boolean
1655 gld_${EMULATION_NAME}_unrecognized_file (lang_input_statement_type *entry ATTRIBUTE_UNUSED)
1656 {
1657 #ifdef DLL_SUPPORT
1658   const char *ext = entry->filename + strlen (entry->filename) - 4;
1659
1660   if (filename_cmp (ext, ".def") == 0 || filename_cmp (ext, ".DEF") == 0)
1661     {
1662       pep_def_file = def_file_parse (entry->filename, pep_def_file);
1663
1664       if (pep_def_file)
1665         {
1666           int i, buflen=0, len;
1667           char *buf;
1668
1669           for (i = 0; i < pep_def_file->num_exports; i++)
1670             {
1671               len = strlen (pep_def_file->exports[i].internal_name);
1672               if (buflen < len + 2)
1673                 buflen = len + 2;
1674             }
1675
1676           buf = xmalloc (buflen);
1677
1678           for (i = 0; i < pep_def_file->num_exports; i++)
1679             {
1680               struct bfd_link_hash_entry *h;
1681
1682               sprintf (buf, "%s%s", U (""),
1683                        pep_def_file->exports[i].internal_name);
1684
1685               h = bfd_link_hash_lookup (link_info.hash, buf, TRUE, TRUE, TRUE);
1686               if (h == (struct bfd_link_hash_entry *) NULL)
1687                 einfo (_("%F%P: bfd_link_hash_lookup failed: %E\n"));
1688               if (h->type == bfd_link_hash_new)
1689                 {
1690                   h->type = bfd_link_hash_undefined;
1691                   h->u.undef.abfd = NULL;
1692                   bfd_link_add_undef (link_info.hash, h);
1693                 }
1694             }
1695           free (buf);
1696
1697           /* def_file_print (stdout, pep_def_file); */
1698           if (pep_def_file->is_dll == 1)
1699             link_info.type = type_dll;
1700
1701           if (pep_def_file->base_address != (bfd_vma)(-1))
1702             {
1703               pep.ImageBase
1704                 = pe_data (link_info.output_bfd)->pe_opthdr.ImageBase
1705                 = init[IMAGEBASEOFF].value
1706                 = pep_def_file->base_address;
1707               init[IMAGEBASEOFF].inited = 1;
1708               if (image_base_statement)
1709                 image_base_statement->exp
1710                   = exp_assign ("__image_base__", exp_intop (pep.ImageBase),
1711                                 FALSE);
1712             }
1713
1714           if (pep_def_file->stack_reserve != -1
1715               && ! saw_option ("__size_of_stack_reserve__"))
1716             {
1717               pep.SizeOfStackReserve = pep_def_file->stack_reserve;
1718               if (pep_def_file->stack_commit != -1)
1719                 pep.SizeOfStackCommit = pep_def_file->stack_commit;
1720             }
1721           if (pep_def_file->heap_reserve != -1
1722               && ! saw_option ("__size_of_heap_reserve__"))
1723             {
1724               pep.SizeOfHeapReserve = pep_def_file->heap_reserve;
1725               if (pep_def_file->heap_commit != -1)
1726                 pep.SizeOfHeapCommit = pep_def_file->heap_commit;
1727             }
1728           return TRUE;
1729         }
1730     }
1731 #endif
1732   return FALSE;
1733 }
1734
1735 static bfd_boolean
1736 gld_${EMULATION_NAME}_recognized_file (lang_input_statement_type *entry ATTRIBUTE_UNUSED)
1737 {
1738   is_underscoring ();
1739 #ifdef DLL_SUPPORT
1740 #ifdef TARGET_IS_i386pep
1741   pep_dll_id_target ("pei-x86-64");
1742 #endif
1743   if (pep_bfd_is_dll (entry->the_bfd))
1744     return pep_implied_import_dll (entry->filename);
1745 #endif
1746   return FALSE;
1747 }
1748
1749 static void
1750 gld_${EMULATION_NAME}_finish (void)
1751 {
1752   is_underscoring ();
1753   finish_default ();
1754
1755 #ifdef DLL_SUPPORT
1756   if (bfd_link_pic (&link_info)
1757       || (!bfd_link_relocatable (&link_info)
1758           && pep_def_file->num_exports != 0))
1759     {
1760       pep_dll_fill_sections (link_info.output_bfd, &link_info);
1761       if (command_line.out_implib_filename)
1762         pep_dll_generate_implib (pep_def_file,
1763                                  command_line.out_implib_filename, &link_info);
1764     }
1765
1766   if (pep_out_def_filename)
1767     pep_dll_generate_def_file (pep_out_def_filename);
1768 #endif /* DLL_SUPPORT */
1769
1770   /* I don't know where .idata gets set as code, but it shouldn't be.  */
1771   {
1772     asection *asec = bfd_get_section_by_name (link_info.output_bfd, ".idata");
1773
1774     if (asec)
1775       {
1776         asec->flags &= ~SEC_CODE;
1777         asec->flags |= SEC_DATA;
1778       }
1779   }
1780 }
1781
1782 \f
1783 /* Place an orphan section.
1784
1785    We use this to put sections in a reasonable place in the file, and
1786    to ensure that they are aligned as required.
1787
1788    We handle grouped sections here as well.  A section named .foo\$nn
1789    goes into the output section .foo.  All grouped sections are sorted
1790    by name.
1791
1792    Grouped sections for the default sections are handled by the
1793    default linker script using wildcards, and are sorted by
1794    sort_sections.  */
1795
1796 static lang_output_section_statement_type *
1797 gld_${EMULATION_NAME}_place_orphan (asection *s,
1798                                     const char *secname,
1799                                     int constraint)
1800 {
1801   const char *orig_secname = secname;
1802   char *dollar = NULL;
1803   lang_output_section_statement_type *os;
1804   lang_statement_list_type add_child;
1805   lang_output_section_statement_type *match_by_name = NULL;
1806   lang_statement_union_type **pl;
1807
1808   /* Look through the script to see where to place this section.  */
1809   if (!bfd_link_relocatable (&link_info)
1810       && (dollar = strchr (secname, '\$')) != NULL)
1811     {
1812       size_t len = dollar - secname;
1813       char *newname = xmalloc (len + 1);
1814       memcpy (newname, secname, len);
1815       newname[len] = '\0';
1816       secname = newname;
1817     }
1818
1819   lang_list_init (&add_child);
1820
1821   os = NULL;
1822   if (constraint == 0)
1823     for (os = lang_output_section_find (secname);
1824          os != NULL;
1825          os = next_matching_output_section_statement (os, 0))
1826       {
1827         /* If we don't match an existing output section, tell
1828            lang_insert_orphan to create a new output section.  */
1829         constraint = SPECIAL;
1830
1831         if (os->bfd_section != NULL
1832             && (os->bfd_section->flags == 0
1833                 || ((s->flags ^ os->bfd_section->flags)
1834                     & (SEC_LOAD | SEC_ALLOC)) == 0))
1835           {
1836             /* We already have an output section statement with this
1837                name, and its bfd section has compatible flags.
1838                If the section already exists but does not have any flags set,
1839                then it has been created by the linker, probably as a result of
1840                a --section-start command line switch.  */
1841             lang_add_section (&add_child, s, NULL, os);
1842             break;
1843           }
1844
1845         /* Save unused output sections in case we can match them
1846            against orphans later.  */
1847         if (os->bfd_section == NULL)
1848           match_by_name = os;
1849       }
1850
1851   /* If we didn't match an active output section, see if we matched an
1852      unused one and use that.  */
1853   if (os == NULL && match_by_name)
1854     {
1855       lang_add_section (&match_by_name->children, s, NULL, match_by_name);
1856       return match_by_name;
1857     }
1858
1859   if (os == NULL)
1860     {
1861       static struct orphan_save hold[] =
1862         {
1863           { ".text",
1864             SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE,
1865             0, 0, 0, 0 },
1866           { ".idata",
1867             SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
1868             0, 0, 0, 0 },
1869           { ".rdata",
1870             SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
1871             0, 0, 0, 0 },
1872           { ".data",
1873             SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA,
1874             0, 0, 0, 0 },
1875           { ".bss",
1876             SEC_ALLOC,
1877             0, 0, 0, 0 }
1878         };
1879       enum orphan_save_index
1880         {
1881           orphan_text = 0,
1882           orphan_idata,
1883           orphan_rodata,
1884           orphan_data,
1885           orphan_bss
1886         };
1887       static int orphan_init_done = 0;
1888       struct orphan_save *place;
1889       lang_output_section_statement_type *after;
1890       etree_type *address;
1891       flagword flags;
1892       asection *nexts;
1893
1894       if (!orphan_init_done)
1895         {
1896           struct orphan_save *ho;
1897           for (ho = hold; ho < hold + sizeof (hold) / sizeof (hold[0]); ++ho)
1898             if (ho->name != NULL)
1899               {
1900                 ho->os = lang_output_section_find (ho->name);
1901                 if (ho->os != NULL && ho->os->flags == 0)
1902                   ho->os->flags = ho->flags;
1903               }
1904           orphan_init_done = 1;
1905         }
1906
1907       flags = s->flags;
1908       if (!bfd_link_relocatable (&link_info))
1909         {
1910           nexts = s;
1911           while ((nexts = bfd_get_next_section_by_name (nexts->owner,
1912                                                         nexts)))
1913             if (nexts->output_section == NULL
1914                 && (nexts->flags & SEC_EXCLUDE) == 0
1915                 && ((nexts->flags ^ flags) & (SEC_LOAD | SEC_ALLOC)) == 0
1916                 && (nexts->owner->flags & DYNAMIC) == 0
1917                 && nexts->owner->usrdata != NULL
1918                 && !(((lang_input_statement_type *) nexts->owner->usrdata)
1919                      ->flags.just_syms))
1920               flags = (((flags ^ SEC_READONLY)
1921                         | (nexts->flags ^ SEC_READONLY))
1922                        ^ SEC_READONLY);
1923         }
1924
1925       /* Try to put the new output section in a reasonable place based
1926          on the section name and section flags.  */
1927
1928       place = NULL;
1929       if ((flags & SEC_ALLOC) == 0)
1930         ;
1931       else if ((flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
1932         place = &hold[orphan_bss];
1933       else if ((flags & SEC_READONLY) == 0)
1934         place = &hold[orphan_data];
1935       else if ((flags & SEC_CODE) == 0)
1936         {
1937           place = (!strncmp (secname, ".idata\$", 7) ? &hold[orphan_idata]
1938                                                      : &hold[orphan_rodata]);
1939         }
1940       else
1941         place = &hold[orphan_text];
1942
1943       after = NULL;
1944       if (place != NULL)
1945         {
1946           if (place->os == NULL)
1947             place->os = lang_output_section_find (place->name);
1948           after = place->os;
1949           if (after == NULL)
1950             after = lang_output_section_find_by_flags (s, flags, &place->os,
1951                                                        NULL);
1952           if (after == NULL)
1953             /* *ABS* is always the first output section statement.  */
1954             after = (&lang_output_section_statement.head
1955                      ->output_section_statement);
1956         }
1957
1958       /* All sections in an executable must be aligned to a page boundary.
1959          In a relocatable link, just preserve the incoming alignment; the
1960          address is discarded by lang_insert_orphan in that case, anyway.  */
1961       address = exp_unop (ALIGN_K, exp_nameop (NAME, "__section_alignment__"));
1962       os = lang_insert_orphan (s, secname, constraint, after, place, address,
1963                                &add_child);
1964       if (bfd_link_relocatable (&link_info))
1965         {
1966           os->section_alignment = exp_intop (1U << s->alignment_power);
1967           os->bfd_section->alignment_power = s->alignment_power;
1968         }
1969     }
1970
1971   /* If the section name has a '\$', sort it with the other '\$'
1972      sections.  */
1973   for (pl = &os->children.head; *pl != NULL; pl = &(*pl)->header.next)
1974     {
1975       lang_input_section_type *ls;
1976       const char *lname;
1977
1978       if ((*pl)->header.type != lang_input_section_enum)
1979         continue;
1980
1981       ls = &(*pl)->input_section;
1982
1983       lname = bfd_get_section_name (ls->section->owner, ls->section);
1984       if (strchr (lname, '\$') != NULL
1985           && (dollar == NULL || strcmp (orig_secname, lname) < 0))
1986         break;
1987     }
1988
1989   if (add_child.head != NULL)
1990     {
1991       *add_child.tail = *pl;
1992       *pl = add_child.head;
1993     }
1994
1995   return os;
1996 }
1997
1998 static bfd_boolean
1999 gld_${EMULATION_NAME}_open_dynamic_archive
2000   (const char *arch ATTRIBUTE_UNUSED,
2001    search_dirs_type *search,
2002    lang_input_statement_type *entry)
2003 {
2004   static const struct
2005     {
2006       const char * format;
2007       bfd_boolean use_prefix;
2008     }
2009   libname_fmt [] =
2010     {
2011       /* Preferred explicit import library for dll's.  */
2012       { "lib%s.dll.a", FALSE },
2013       /* Alternate explicit import library for dll's.  */
2014       { "%s.dll.a", FALSE },
2015       /* "libfoo.a" could be either an import lib or a static lib.
2016          For backwards compatibility, libfoo.a needs to precede
2017          libfoo.dll and foo.dll in the search.  */
2018       { "lib%s.a", FALSE },
2019       /* The 'native' spelling of an import lib name is "foo.lib".  */
2020       { "%s.lib", FALSE },
2021       /* PR 22948 - Check for an import library.  */
2022       { "lib%s.lib", FALSE },
2023 #ifdef DLL_SUPPORT
2024       /* Try "<prefix>foo.dll" (preferred dll name, if specified).  */
2025       { "%s%s.dll", TRUE },
2026 #endif
2027       /* Try "libfoo.dll" (default preferred dll name).  */
2028       { "lib%s.dll", FALSE },
2029       /* Finally try 'native' dll name "foo.dll".  */
2030       {  "%s.dll", FALSE },
2031       /* Note: If adding more formats to this table, make sure to check to
2032          see if their length is longer than libname_fmt[0].format, and if
2033          so, update the call to xmalloc() below.  */
2034       { NULL, FALSE }
2035     };
2036   static unsigned int format_max_len = 0;
2037   const char * filename;
2038   char * full_string;
2039   char * base_string;
2040   unsigned int i;
2041
2042
2043   if (! entry->flags.maybe_archive || entry->flags.full_name_provided)
2044     return FALSE;
2045
2046   filename = entry->filename;
2047
2048   if (format_max_len == 0)
2049     /* We need to allow space in the memory that we are going to allocate
2050        for the characters in the format string.  Since the format array is
2051        static we only need to calculate this information once.  In theory
2052        this value could also be computed statically, but this introduces
2053        the possibility for a discrepancy and hence a possible memory
2054        corruption.  The lengths we compute here will be too long because
2055        they will include any formating characters (%s) in the strings, but
2056        this will not matter.  */
2057     for (i = 0; libname_fmt[i].format; i++)
2058       if (format_max_len < strlen (libname_fmt[i].format))
2059         format_max_len = strlen (libname_fmt[i].format);
2060
2061   full_string = xmalloc (strlen (search->name)
2062                          + strlen (filename)
2063                          + format_max_len
2064 #ifdef DLL_SUPPORT
2065                          + (pep_dll_search_prefix
2066                             ? strlen (pep_dll_search_prefix) : 0)
2067 #endif
2068                          /* Allow for the terminating NUL and for the path
2069                             separator character that is inserted between
2070                             search->name and the start of the format string.  */
2071                          + 2);
2072
2073   sprintf (full_string, "%s/", search->name);
2074   base_string = full_string + strlen (full_string);
2075
2076   for (i = 0; libname_fmt[i].format; i++)
2077     {
2078 #ifdef DLL_SUPPORT
2079       if (libname_fmt[i].use_prefix)
2080         {
2081           if (!pep_dll_search_prefix)
2082             continue;
2083           sprintf (base_string, libname_fmt[i].format, pep_dll_search_prefix, filename);
2084         }
2085       else
2086 #endif
2087         sprintf (base_string, libname_fmt[i].format, filename);
2088
2089       if (ldfile_try_open_bfd (full_string, entry))
2090         break;
2091     }
2092
2093   if (!libname_fmt[i].format)
2094     {
2095       free (full_string);
2096       return FALSE;
2097     }
2098
2099   entry->filename = full_string;
2100
2101   return TRUE;
2102 }
2103
2104 static int
2105 gld_${EMULATION_NAME}_find_potential_libraries
2106   (char *name, lang_input_statement_type *entry)
2107 {
2108   return ldfile_open_file_search (name, entry, "", ".lib");
2109 }
2110 \f
2111 static char *
2112 gld_${EMULATION_NAME}_get_script (int *isfile)
2113 EOF
2114 # Scripts compiled in.
2115 # sed commands to quote an ld script as a C string.
2116 sc="-f stringify.sed"
2117
2118 fragment <<EOF
2119 {
2120   *isfile = 0;
2121
2122   if (bfd_link_relocatable (&link_info) && config.build_constructors)
2123     return
2124 EOF
2125 sed $sc ldscripts/${EMULATION_NAME}.xu                  >> e${EMULATION_NAME}.c
2126 echo '  ; else if (bfd_link_relocatable (&link_info)) return' >> e${EMULATION_NAME}.c
2127 sed $sc ldscripts/${EMULATION_NAME}.xr                  >> e${EMULATION_NAME}.c
2128 echo '  ; else if (!config.text_read_only) return'      >> e${EMULATION_NAME}.c
2129 sed $sc ldscripts/${EMULATION_NAME}.xbn                 >> e${EMULATION_NAME}.c
2130 echo '  ; else if (!config.magic_demand_paged) return'  >> e${EMULATION_NAME}.c
2131 sed $sc ldscripts/${EMULATION_NAME}.xn                  >> e${EMULATION_NAME}.c
2132 if test -n "$GENERATE_AUTO_IMPORT_SCRIPT" ; then
2133 echo '  ; else if (link_info.pei386_auto_import == 1 && link_info.pei386_runtime_pseudo_reloc != 2) return'     >> e${EMULATION_NAME}.c
2134 sed $sc ldscripts/${EMULATION_NAME}.xa                  >> e${EMULATION_NAME}.c
2135 fi
2136 echo '  ; else return'                                  >> e${EMULATION_NAME}.c
2137 sed $sc ldscripts/${EMULATION_NAME}.x                   >> e${EMULATION_NAME}.c
2138 echo '; }'                                              >> e${EMULATION_NAME}.c
2139
2140 fragment <<EOF
2141
2142
2143 struct ld_emulation_xfer_struct ld_${EMULATION_NAME}_emulation =
2144 {
2145   gld_${EMULATION_NAME}_before_parse,
2146   syslib_default,
2147   hll_default,
2148   gld_${EMULATION_NAME}_after_parse,
2149   gld_${EMULATION_NAME}_after_open,
2150   after_check_relocs_default,
2151   after_allocation_default,
2152   set_output_arch_default,
2153   ldemul_default_target,
2154   gld_${EMULATION_NAME}_before_allocation,
2155   gld_${EMULATION_NAME}_get_script,
2156   "${EMULATION_NAME}",
2157   "${OUTPUT_FORMAT}",
2158   gld_${EMULATION_NAME}_finish,
2159   NULL, /* Create output section statements.  */
2160   gld_${EMULATION_NAME}_open_dynamic_archive,
2161   gld_${EMULATION_NAME}_place_orphan,
2162   gld_${EMULATION_NAME}_set_symbols,
2163   NULL, /* parse_args */
2164   gld${EMULATION_NAME}_add_options,
2165   gld${EMULATION_NAME}_handle_option,
2166   gld_${EMULATION_NAME}_unrecognized_file,
2167   gld_${EMULATION_NAME}_list_options,
2168   gld_${EMULATION_NAME}_recognized_file,
2169   gld_${EMULATION_NAME}_find_potential_libraries,
2170   NULL, /* new_vers_pattern.  */
2171   NULL  /* extra_map_file_text */
2172 };
2173 EOF