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