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