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