OSDN Git Service

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