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