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