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