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