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
8
9case ${target} in
10  *-*-cygwin*)
11    cygwin_behavior=1
12    ;;
13  *)
14    cygwin_behavior=0;
15    ;;
16esac
17
18rm -f e${EMULATION_NAME}.c
19(echo;echo;echo;echo;echo)>e${EMULATION_NAME}.c # there, now line numbers match ;-)
20fragment <<EOF
21/* Copyright (C) 1995-2022 Free Software Foundation, Inc.
22
23   This file is part of the GNU Binutils.
24
25   This program is free software; you can redistribute it and/or modify
26   it under the terms of the GNU General Public License as published by
27   the Free Software Foundation; either version 3 of the License, or
28   (at your option) any later version.
29
30   This program is distributed in the hope that it will be useful,
31   but WITHOUT ANY WARRANTY; without even the implied warranty of
32   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
33   GNU General Public License for more details.
34
35   You should have received a copy of the GNU General Public License
36   along with this program; if not, write to the Free Software
37   Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
38   MA 02110-1301, USA.  */
39
40
41/* For WINDOWS_NT */
42/* The original file generated returned different default scripts depending
43   on whether certain switches were set, but these switches pertain to the
44   Linux system and that particular version of coff.  In the NT case, we
45   only determine if the subsystem is console or windows in order to select
46   the correct entry point by default. */
47
48#define TARGET_IS_${EMULATION_NAME}
49
50#include "sysdep.h"
51#include "bfd.h"
52#include "bfdlink.h"
53#include "ctf-api.h"
54#include "getopt.h"
55#include "libiberty.h"
56#include "filenames.h"
57#include "ld.h"
58#include "ldmain.h"
59#include "ldexp.h"
60#include "ldlang.h"
61#include "ldfile.h"
62#include "ldemul.h"
63#include <ldgram.h>
64#include "ldlex.h"
65#include "ldmisc.h"
66#include "ldctor.h"
67#include "ldbuildid.h"
68#include "coff/internal.h"
69
70/* FIXME: See bfd/peXXigen.c for why we include an architecture specific
71   header in generic PE code.  */
72#include "coff/i386.h"
73#include "coff/pe.h"
74
75/* FIXME: These are BFD internal header files, and we should not be
76   using it here.  */
77#include "../bfd/libcoff.h"
78#include "../bfd/libpei.h"
79
80#if defined(TARGET_IS_armpe) \
81    || defined(TARGET_IS_arm_wince_pe)
82#define bfd_arm_allocate_interworking_sections \
83	bfd_${EMULATION_NAME}_allocate_interworking_sections
84#define bfd_arm_get_bfd_for_interworking \
85	bfd_${EMULATION_NAME}_get_bfd_for_interworking
86#define bfd_arm_process_before_allocation \
87	bfd_${EMULATION_NAME}_process_before_allocation
88#include "coff-arm.h"
89#endif
90
91#include "deffile.h"
92#include "pe-dll.h"
93#include "safe-ctype.h"
94
95/* Permit the emulation parameters to override the default section
96   alignment by setting OVERRIDE_SECTION_ALIGNMENT.  FIXME: This makes
97   it seem that include/coff/internal.h should not define
98   PE_DEF_SECTION_ALIGNMENT.  */
99#if PE_DEF_SECTION_ALIGNMENT != ${OVERRIDE_SECTION_ALIGNMENT:-PE_DEF_SECTION_ALIGNMENT}
100#undef PE_DEF_SECTION_ALIGNMENT
101#define PE_DEF_SECTION_ALIGNMENT ${OVERRIDE_SECTION_ALIGNMENT}
102#endif
103
104#if defined(TARGET_IS_i386pe) \
105    || defined(TARGET_IS_shpe) \
106    || defined(TARGET_IS_armpe) \
107    || defined(TARGET_IS_arm_wince_pe)
108#define DLL_SUPPORT
109#endif
110
111#if defined(TARGET_IS_i386pe)
112#define DEFAULT_PSEUDO_RELOC_VERSION 2
113#else
114#define DEFAULT_PSEUDO_RELOC_VERSION 1
115#endif
116
117#define DEFAULT_DLL_CHARACTERISTICS	(${cygwin_behavior} ? 0 : \
118					   IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE \
119					 | IMAGE_DLL_CHARACTERISTICS_NX_COMPAT)
120
121#if defined(TARGET_IS_i386pe) || ! defined(DLL_SUPPORT)
122#define	PE_DEF_SUBSYSTEM		3
123#else
124#undef NT_EXE_IMAGE_BASE
125#undef PE_DEF_SECTION_ALIGNMENT
126#undef PE_DEF_FILE_ALIGNMENT
127#define NT_EXE_IMAGE_BASE		0x00010000
128
129#if defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_wince_pe)
130#define PE_DEF_SECTION_ALIGNMENT	0x00001000
131#define	PE_DEF_SUBSYSTEM		9
132#else
133#define PE_DEF_SECTION_ALIGNMENT	0x00000400
134#define	PE_DEF_SUBSYSTEM		2
135#endif
136#define PE_DEF_FILE_ALIGNMENT		0x00000200
137#endif
138
139static struct internal_extra_pe_aouthdr pe;
140static int dll;
141static int pe_subsystem = ${SUBSYSTEM};
142static flagword real_flags = 0;
143static int support_old_code = 0;
144static char * thumb_entry_symbol = NULL;
145static lang_assignment_statement_type *image_base_statement = 0;
146static unsigned short pe_dll_characteristics = DEFAULT_DLL_CHARACTERISTICS;
147static bool insert_timestamp = true;
148static const char *emit_build_id;
149
150#ifdef DLL_SUPPORT
151static int pe_enable_stdcall_fixup = -1; /* 0=disable 1=enable.  */
152static char *pe_out_def_filename = NULL;
153static int pe_enable_auto_image_base = 0;
154static unsigned long pe_auto_image_base = 0x61500000;
155static char *pe_dll_search_prefix = NULL;
156#endif
157
158extern const char *output_filename;
159
160static int is_underscoring (void)
161{
162  int u = 0;
163  if (pe_leading_underscore != -1)
164    return pe_leading_underscore;
165  if (!bfd_get_target_info ("${OUTPUT_FORMAT}", NULL, NULL, &u, NULL))
166    bfd_get_target_info ("${RELOCATEABLE_OUTPUT_FORMAT}", NULL, NULL, &u, NULL);
167
168  if (u == -1)
169    abort ();
170  pe_leading_underscore = (u != 0 ? 1 : 0);
171  return pe_leading_underscore;
172}
173
174static void
175gld${EMULATION_NAME}_before_parse (void)
176{
177  is_underscoring ();
178  ldfile_set_output_arch ("${OUTPUT_ARCH}", bfd_arch_`echo ${ARCH} | sed -e 's/:.*//'`);
179  output_filename = "${EXECUTABLE_NAME:-a.exe}";
180#ifdef DLL_SUPPORT
181  input_flags.dynamic = true;
182  config.has_shared = 1;
183EOF
184
185# Cygwin no longer wants these noisy warnings.  Other PE
186# targets might like to consider adding themselves here.
187# See also the mail thread starting here for the reason why
188# merge_rdata defaults to 0 for cygwin:
189#  http://cygwin.com/ml/cygwin-apps/2013-04/msg00187.html
190case ${target} in
191  *-*-cygwin*)
192    default_auto_import=1
193    default_merge_rdata=0
194    ;;
195  i[3-7]86-*-mingw* | x86_64-*-mingw*)
196    default_auto_import=1
197    default_merge_rdata=0
198    ;;
199  *)
200    default_auto_import=-1
201    default_merge_rdata=1
202    ;;
203esac
204
205fragment <<EOF
206  link_info.pei386_auto_import = ${default_auto_import};
207  /* Use by default version.  */
208  link_info.pei386_runtime_pseudo_reloc = DEFAULT_PSEUDO_RELOC_VERSION;
209#endif
210}
211
212/* Indicates if RDATA shall be merged into DATA when pseudo-relocation
213   version 2 is used and auto-import is enabled.  */
214#define MERGE_RDATA_V2 ${default_merge_rdata}
215
216/* PE format extra command line options.  */
217
218/* Used for setting flags in the PE header.  */
219#define OPTION_BASE_FILE		(300  + 1)
220#define OPTION_DLL			(OPTION_BASE_FILE + 1)
221#define OPTION_FILE_ALIGNMENT		(OPTION_DLL + 1)
222#define OPTION_IMAGE_BASE		(OPTION_FILE_ALIGNMENT + 1)
223#define OPTION_MAJOR_IMAGE_VERSION	(OPTION_IMAGE_BASE + 1)
224#define OPTION_MAJOR_OS_VERSION		(OPTION_MAJOR_IMAGE_VERSION + 1)
225#define OPTION_MAJOR_SUBSYSTEM_VERSION	(OPTION_MAJOR_OS_VERSION + 1)
226#define OPTION_MINOR_IMAGE_VERSION	(OPTION_MAJOR_SUBSYSTEM_VERSION + 1)
227#define OPTION_MINOR_OS_VERSION		(OPTION_MINOR_IMAGE_VERSION + 1)
228#define OPTION_MINOR_SUBSYSTEM_VERSION	(OPTION_MINOR_OS_VERSION + 1)
229#define OPTION_SECTION_ALIGNMENT	(OPTION_MINOR_SUBSYSTEM_VERSION + 1)
230#define OPTION_STACK			(OPTION_SECTION_ALIGNMENT + 1)
231#define OPTION_SUBSYSTEM		(OPTION_STACK + 1)
232#define OPTION_HEAP			(OPTION_SUBSYSTEM + 1)
233#define OPTION_SUPPORT_OLD_CODE		(OPTION_HEAP + 1)
234#define OPTION_OUT_DEF			(OPTION_SUPPORT_OLD_CODE + 1)
235#define OPTION_EXPORT_ALL		(OPTION_OUT_DEF + 1)
236#define OPTION_EXCLUDE_SYMBOLS		(OPTION_EXPORT_ALL + 1)
237#define OPTION_EXCLUDE_ALL_SYMBOLS	(OPTION_EXCLUDE_SYMBOLS + 1)
238#define OPTION_KILL_ATS			(OPTION_EXCLUDE_ALL_SYMBOLS + 1)
239#define OPTION_STDCALL_ALIASES		(OPTION_KILL_ATS + 1)
240#define OPTION_ENABLE_STDCALL_FIXUP	(OPTION_STDCALL_ALIASES + 1)
241#define OPTION_DISABLE_STDCALL_FIXUP	(OPTION_ENABLE_STDCALL_FIXUP + 1)
242#define OPTION_THUMB_ENTRY		(OPTION_DISABLE_STDCALL_FIXUP + 1)
243#define OPTION_WARN_DUPLICATE_EXPORTS	(OPTION_THUMB_ENTRY + 1)
244#define OPTION_IMP_COMPAT		(OPTION_WARN_DUPLICATE_EXPORTS + 1)
245#define OPTION_ENABLE_AUTO_IMAGE_BASE	(OPTION_IMP_COMPAT + 1)
246#define OPTION_DISABLE_AUTO_IMAGE_BASE	(OPTION_ENABLE_AUTO_IMAGE_BASE + 1)
247#define OPTION_DLL_SEARCH_PREFIX	(OPTION_DISABLE_AUTO_IMAGE_BASE + 1)
248#define OPTION_NO_DEFAULT_EXCLUDES	(OPTION_DLL_SEARCH_PREFIX + 1)
249#define OPTION_DLL_ENABLE_AUTO_IMPORT	(OPTION_NO_DEFAULT_EXCLUDES + 1)
250#define OPTION_DLL_DISABLE_AUTO_IMPORT	(OPTION_DLL_ENABLE_AUTO_IMPORT + 1)
251#define OPTION_ENABLE_EXTRA_PE_DEBUG	(OPTION_DLL_DISABLE_AUTO_IMPORT + 1)
252#define OPTION_EXCLUDE_LIBS		(OPTION_ENABLE_EXTRA_PE_DEBUG + 1)
253#define OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC	\
254					(OPTION_EXCLUDE_LIBS + 1)
255#define OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC	\
256					(OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC + 1)
257#define OPTION_LARGE_ADDRESS_AWARE	(OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC + 1)
258#define OPTION_DISABLE_LARGE_ADDRESS_AWARE \
259					(OPTION_LARGE_ADDRESS_AWARE + 1)
260#define OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V1	\
261					(OPTION_DISABLE_LARGE_ADDRESS_AWARE + 1)
262#define OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2	\
263					(OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V1 + 1)
264#define OPTION_EXCLUDE_MODULES_FOR_IMPLIB \
265					(OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2 + 1)
266#define OPTION_USE_NUL_PREFIXED_IMPORT_TABLES \
267					(OPTION_EXCLUDE_MODULES_FOR_IMPLIB + 1)
268#define OPTION_NO_LEADING_UNDERSCORE	(OPTION_USE_NUL_PREFIXED_IMPORT_TABLES + 1)
269#define OPTION_LEADING_UNDERSCORE	(OPTION_NO_LEADING_UNDERSCORE + 1)
270#define OPTION_ENABLE_LONG_SECTION_NAMES \
271					(OPTION_LEADING_UNDERSCORE + 1)
272#define OPTION_DISABLE_LONG_SECTION_NAMES \
273					(OPTION_ENABLE_LONG_SECTION_NAMES + 1)
274/* DLLCharacteristics flags.  */
275#define OPTION_DYNAMIC_BASE		(OPTION_DISABLE_LONG_SECTION_NAMES + 1)
276#define OPTION_FORCE_INTEGRITY		(OPTION_DYNAMIC_BASE + 1)
277#define OPTION_NX_COMPAT		(OPTION_FORCE_INTEGRITY + 1)
278#define OPTION_NO_ISOLATION		(OPTION_NX_COMPAT + 1)
279#define OPTION_NO_SEH			(OPTION_NO_ISOLATION + 1)
280#define OPTION_NO_BIND			(OPTION_NO_SEH + 1)
281#define OPTION_WDM_DRIVER		(OPTION_NO_BIND + 1)
282#define OPTION_TERMINAL_SERVER_AWARE	(OPTION_WDM_DRIVER + 1)
283/* Determinism.  */
284#define OPTION_INSERT_TIMESTAMP		(OPTION_TERMINAL_SERVER_AWARE + 1)
285#define OPTION_NO_INSERT_TIMESTAMP	(OPTION_INSERT_TIMESTAMP + 1)
286#define OPTION_BUILD_ID			(OPTION_NO_INSERT_TIMESTAMP + 1)
287#define OPTION_ENABLE_RELOC_SECTION	(OPTION_BUILD_ID + 1)
288#define OPTION_DISABLE_RELOC_SECTION	(OPTION_ENABLE_RELOC_SECTION + 1)
289/* DLL Characteristics flags.  */
290#define OPTION_DISABLE_DYNAMIC_BASE	(OPTION_DISABLE_RELOC_SECTION + 1)
291#define OPTION_DISABLE_FORCE_INTEGRITY	(OPTION_DISABLE_DYNAMIC_BASE + 1)
292#define OPTION_DISABLE_NX_COMPAT	(OPTION_DISABLE_FORCE_INTEGRITY + 1)
293#define OPTION_DISABLE_NO_ISOLATION	(OPTION_DISABLE_NX_COMPAT + 1)
294#define OPTION_DISABLE_NO_SEH		(OPTION_DISABLE_NO_ISOLATION + 1)
295#define OPTION_DISABLE_NO_BIND		(OPTION_DISABLE_NO_SEH + 1)
296#define OPTION_DISABLE_WDM_DRIVER	(OPTION_DISABLE_NO_BIND + 1)
297#define OPTION_DISABLE_TERMINAL_SERVER_AWARE \
298					(OPTION_DISABLE_WDM_DRIVER + 1)
299
300static void
301gld${EMULATION_NAME}_add_options
302  (int ns ATTRIBUTE_UNUSED,
303   char **shortopts ATTRIBUTE_UNUSED,
304   int nl,
305   struct option **longopts,
306   int nrl ATTRIBUTE_UNUSED,
307   struct option **really_longopts ATTRIBUTE_UNUSED)
308{
309  static const struct option xtra_long[] =
310  {
311    /* PE options.  */
312    {"base-file", required_argument, NULL, OPTION_BASE_FILE},
313    {"dll", no_argument, NULL, OPTION_DLL},
314    {"file-alignment", required_argument, NULL, OPTION_FILE_ALIGNMENT},
315    {"heap", required_argument, NULL, OPTION_HEAP},
316    {"image-base", required_argument, NULL, OPTION_IMAGE_BASE},
317    {"major-image-version", required_argument, NULL, OPTION_MAJOR_IMAGE_VERSION},
318    {"major-os-version", required_argument, NULL, OPTION_MAJOR_OS_VERSION},
319    {"major-subsystem-version", required_argument, NULL, OPTION_MAJOR_SUBSYSTEM_VERSION},
320    {"minor-image-version", required_argument, NULL, OPTION_MINOR_IMAGE_VERSION},
321    {"minor-os-version", required_argument, NULL, OPTION_MINOR_OS_VERSION},
322    {"minor-subsystem-version", required_argument, NULL, OPTION_MINOR_SUBSYSTEM_VERSION},
323    {"section-alignment", required_argument, NULL, OPTION_SECTION_ALIGNMENT},
324    {"stack", required_argument, NULL, OPTION_STACK},
325    {"subsystem", required_argument, NULL, OPTION_SUBSYSTEM},
326    {"support-old-code", no_argument, NULL, OPTION_SUPPORT_OLD_CODE},
327    {"thumb-entry", required_argument, NULL, OPTION_THUMB_ENTRY},
328    {"use-nul-prefixed-import-tables", no_argument, NULL,
329     OPTION_USE_NUL_PREFIXED_IMPORT_TABLES},
330    {"no-leading-underscore", no_argument, NULL, OPTION_NO_LEADING_UNDERSCORE},
331    {"leading-underscore", no_argument, NULL, OPTION_LEADING_UNDERSCORE},
332    {"insert-timestamp", no_argument, NULL, OPTION_INSERT_TIMESTAMP},
333    {"no-insert-timestamp", no_argument, NULL, OPTION_NO_INSERT_TIMESTAMP},
334#ifdef DLL_SUPPORT
335    /* getopt allows abbreviations, so we do this to stop it
336       from treating -o as an abbreviation for this option.  */
337    {"output-def", required_argument, NULL, OPTION_OUT_DEF},
338    {"output-def", required_argument, NULL, OPTION_OUT_DEF},
339    {"export-all-symbols", no_argument, NULL, OPTION_EXPORT_ALL},
340    {"exclude-symbols", required_argument, NULL, OPTION_EXCLUDE_SYMBOLS},
341    {"exclude-all-symbols", no_argument, NULL, OPTION_EXCLUDE_ALL_SYMBOLS},
342    {"exclude-libs", required_argument, NULL, OPTION_EXCLUDE_LIBS},
343    {"exclude-modules-for-implib", required_argument, NULL, OPTION_EXCLUDE_MODULES_FOR_IMPLIB},
344    {"kill-at", no_argument, NULL, OPTION_KILL_ATS},
345    {"add-stdcall-alias", no_argument, NULL, OPTION_STDCALL_ALIASES},
346    {"enable-stdcall-fixup", no_argument, NULL, OPTION_ENABLE_STDCALL_FIXUP},
347    {"disable-stdcall-fixup", no_argument, NULL, OPTION_DISABLE_STDCALL_FIXUP},
348    {"warn-duplicate-exports", no_argument, NULL, OPTION_WARN_DUPLICATE_EXPORTS},
349    /* getopt() allows abbreviations, so we do this to stop it from
350       treating -c as an abbreviation for these --compat-implib.  */
351    {"compat-implib", no_argument, NULL, OPTION_IMP_COMPAT},
352    {"compat-implib", no_argument, NULL, OPTION_IMP_COMPAT},
353    {"enable-auto-image-base", optional_argument, NULL, OPTION_ENABLE_AUTO_IMAGE_BASE},
354    {"disable-auto-image-base", no_argument, NULL, OPTION_DISABLE_AUTO_IMAGE_BASE},
355    {"dll-search-prefix", required_argument, NULL, OPTION_DLL_SEARCH_PREFIX},
356    {"no-default-excludes", no_argument, NULL, OPTION_NO_DEFAULT_EXCLUDES},
357    {"enable-auto-import", no_argument, NULL, OPTION_DLL_ENABLE_AUTO_IMPORT},
358    {"disable-auto-import", no_argument, NULL, OPTION_DLL_DISABLE_AUTO_IMPORT},
359    {"enable-extra-pe-debug", no_argument, NULL, OPTION_ENABLE_EXTRA_PE_DEBUG},
360    {"enable-runtime-pseudo-reloc", no_argument, NULL, OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC},
361    {"disable-runtime-pseudo-reloc", no_argument, NULL, OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC},
362    {"enable-runtime-pseudo-reloc-v1", no_argument, NULL, OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V1},
363    {"enable-runtime-pseudo-reloc-v2", no_argument, NULL, OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2},
364#endif
365    {"large-address-aware", no_argument, NULL, OPTION_LARGE_ADDRESS_AWARE},
366    {"disable-large-address-aware", no_argument, NULL, OPTION_DISABLE_LARGE_ADDRESS_AWARE},
367    {"enable-long-section-names", no_argument, NULL, OPTION_ENABLE_LONG_SECTION_NAMES},
368    {"disable-long-section-names", no_argument, NULL, OPTION_DISABLE_LONG_SECTION_NAMES},
369    {"dynamicbase",no_argument, NULL, OPTION_DYNAMIC_BASE},
370    {"disable-dynamicbase",no_argument, NULL, OPTION_DISABLE_DYNAMIC_BASE},
371    {"forceinteg", no_argument, NULL, OPTION_FORCE_INTEGRITY},
372    {"disable-forceinteg", no_argument, NULL, OPTION_DISABLE_FORCE_INTEGRITY},
373    {"nxcompat", no_argument, NULL, OPTION_NX_COMPAT},
374    {"disable-nxcompat", no_argument, NULL, OPTION_DISABLE_NX_COMPAT},
375    {"no-isolation", no_argument, NULL, OPTION_NO_ISOLATION},
376    {"disable-no-isolation", no_argument, NULL, OPTION_DISABLE_NO_ISOLATION},
377    {"no-seh", no_argument, NULL, OPTION_NO_SEH},
378    {"disable-no-seh", no_argument, NULL, OPTION_DISABLE_NO_SEH},
379    {"no-bind", no_argument, NULL, OPTION_NO_BIND},
380    {"disable-no-bind", no_argument, NULL, OPTION_DISABLE_NO_BIND},
381    {"wdmdriver", no_argument, NULL, OPTION_WDM_DRIVER},
382    {"disable-wdmdriver", no_argument, NULL, OPTION_DISABLE_WDM_DRIVER},
383    {"tsaware", no_argument, NULL, OPTION_TERMINAL_SERVER_AWARE},
384    {"disable-tsaware", no_argument, NULL, OPTION_DISABLE_TERMINAL_SERVER_AWARE},
385    {"build-id", optional_argument, NULL, OPTION_BUILD_ID},
386    {"enable-reloc-section", no_argument, NULL, OPTION_ENABLE_RELOC_SECTION},
387    {"disable-reloc-section", no_argument, NULL, OPTION_DISABLE_RELOC_SECTION},
388    {NULL, no_argument, NULL, 0}
389  };
390
391  *longopts
392    = xrealloc (*longopts, nl * sizeof (struct option) + sizeof (xtra_long));
393  memcpy (*longopts + nl, &xtra_long, sizeof (xtra_long));
394}
395
396/* PE/WIN32; added routines to get the subsystem type, heap and/or stack
397   parameters which may be input from the command line.  */
398
399typedef struct
400{
401  void *ptr;
402  int size;
403  int value;
404  char *symbol;
405  int inited;
406  /* FALSE for an assembly level symbol and TRUE for a C visible symbol.
407     C visible symbols can be prefixed by underscore dependent to target's
408     settings.  */
409  bool is_c_symbol;
410} definfo;
411
412/* Get symbol name dependent to kind and C visible state of
413   underscore.  */
414#define GET_INIT_SYMBOL_NAME(IDX) \
415  (init[(IDX)].symbol \
416   + ((!init[(IDX)].is_c_symbol || is_underscoring () != 0) ? 0 : 1))
417
418/* Decorates the C visible symbol by underscore, if target requires.  */
419#define U(CSTR) \
420  ((is_underscoring () == 0) ? CSTR : "_" CSTR)
421
422#define D(field,symbol,def,usc)  {&pe.field, sizeof (pe.field), def, symbol, 0, usc}
423
424static definfo init[] =
425{
426  /* imagebase must be first */
427#define IMAGEBASEOFF 0
428  D(ImageBase,"__image_base__", NT_EXE_IMAGE_BASE, false),
429#define DLLOFF 1
430  {&dll, sizeof(dll), 0, "__dll__", 0, false},
431#define MSIMAGEBASEOFF	2
432  D(ImageBase, "___ImageBase", NT_EXE_IMAGE_BASE, true),
433  D(SectionAlignment,"__section_alignment__", PE_DEF_SECTION_ALIGNMENT, false),
434  D(FileAlignment,"__file_alignment__", PE_DEF_FILE_ALIGNMENT, false),
435  D(MajorOperatingSystemVersion,"__major_os_version__", 4, false),
436  D(MinorOperatingSystemVersion,"__minor_os_version__", 0, false),
437  D(MajorImageVersion,"__major_image_version__", 1, false),
438  D(MinorImageVersion,"__minor_image_version__", 0, false),
439#if defined(TARGET_IS_armpe)  || defined(TARGET_IS_arm_wince_pe)
440  D(MajorSubsystemVersion,"__major_subsystem_version__", 3, false),
441#else
442  D(MajorSubsystemVersion,"__major_subsystem_version__", 4, false),
443#endif
444  D(MinorSubsystemVersion,"__minor_subsystem_version__", 0, false),
445  D(Subsystem,"__subsystem__", ${SUBSYSTEM}, false),
446  D(SizeOfStackReserve,"__size_of_stack_reserve__", 0x200000, false),
447  D(SizeOfStackCommit,"__size_of_stack_commit__", 0x1000, false),
448  D(SizeOfHeapReserve,"__size_of_heap_reserve__", 0x100000, false),
449  D(SizeOfHeapCommit,"__size_of_heap_commit__", 0x1000, false),
450  D(LoaderFlags,"__loader_flags__", 0x0, false),
451  D(DllCharacteristics, "__dll_characteristics__", DEFAULT_DLL_CHARACTERISTICS, false),
452  { NULL, 0, 0, NULL, 0 , false}
453};
454
455
456static void
457gld${EMULATION_NAME}_list_options (FILE *file)
458{
459  fprintf (file, _("  --base_file <basefile>             Generate a base file for relocatable DLLs\n"));
460  fprintf (file, _("  --dll                              Set image base to the default for DLLs\n"));
461  fprintf (file, _("  --file-alignment <size>            Set file alignment\n"));
462  fprintf (file, _("  --heap <size>                      Set initial size of the heap\n"));
463  fprintf (file, _("  --image-base <address>             Set start address of the executable\n"));
464  fprintf (file, _("  --major-image-version <number>     Set version number of the executable\n"));
465  fprintf (file, _("  --major-os-version <number>        Set minimum required OS version\n"));
466  fprintf (file, _("  --major-subsystem-version <number> Set minimum required OS subsystem version\n"));
467  fprintf (file, _("  --minor-image-version <number>     Set revision number of the executable\n"));
468  fprintf (file, _("  --minor-os-version <number>        Set minimum required OS revision\n"));
469  fprintf (file, _("  --minor-subsystem-version <number> Set minimum required OS subsystem revision\n"));
470  fprintf (file, _("  --section-alignment <size>         Set section alignment\n"));
471  fprintf (file, _("  --stack <size>                     Set size of the initial stack\n"));
472  fprintf (file, _("  --subsystem <name>[:<version>]     Set required OS subsystem [& version]\n"));
473  fprintf (file, _("  --support-old-code                 Support interworking with old code\n"));
474  fprintf (file, _("  --[no-]leading-underscore          Set explicit symbol underscore prefix mode\n"));
475  fprintf (file, _("  --thumb-entry=<symbol>             Set the entry point to be Thumb <symbol>\n"));
476  fprintf (file, _("  --[no-]insert-timestamp            Use a real timestamp rather than zero (default).\n"));
477  fprintf (file, _("                                     This makes binaries non-deterministic\n"));
478#ifdef DLL_SUPPORT
479  fprintf (file, _("  --add-stdcall-alias                Export symbols with and without @nn\n"));
480  fprintf (file, _("  --disable-stdcall-fixup            Don't link _sym to _sym@nn\n"));
481  fprintf (file, _("  --enable-stdcall-fixup             Link _sym to _sym@nn without warnings\n"));
482  fprintf (file, _("  --exclude-symbols sym,sym,...      Exclude symbols from automatic export\n"));
483  fprintf (file, _("  --exclude-all-symbols              Exclude all symbols from automatic export\n"));
484  fprintf (file, _("  --exclude-libs lib,lib,...         Exclude libraries from automatic export\n"));
485  fprintf (file, _("  --exclude-modules-for-implib mod,mod,...\n"));
486  fprintf (file, _("                                     Exclude objects, archive members from auto\n"));
487  fprintf (file, _("                                     export, place into import library instead.\n"));
488  fprintf (file, _("  --export-all-symbols               Automatically export all globals to DLL\n"));
489  fprintf (file, _("  --kill-at                          Remove @nn from exported symbols\n"));
490  fprintf (file, _("  --output-def <file>                Generate a .DEF file for the built DLL\n"));
491  fprintf (file, _("  --warn-duplicate-exports           Warn about duplicate exports\n"));
492  fprintf (file, _("  --compat-implib                    Create backward compatible import libs;\n\
493                                       create __imp_<SYMBOL> as well.\n"));
494  fprintf (file, _("  --enable-auto-image-base[=<address>] Automatically choose image base for DLLs\n\
495                                       (optionally starting with address) unless\n\
496                                       specifically set with --image-base\n"));
497  fprintf (file, _("  --disable-auto-image-base          Do not auto-choose image base. (default)\n"));
498  fprintf (file, _("  --dll-search-prefix=<string>       When linking dynamically to a dll without\n\
499                                       an importlib, use <string><basename>.dll\n\
500                                       in preference to lib<basename>.dll \n"));
501  fprintf (file, _("  --enable-auto-import               Do sophisticated linking of _sym to\n\
502                                       __imp_sym for DATA references\n"));
503  fprintf (file, _("  --disable-auto-import              Do not auto-import DATA items from DLLs\n"));
504  fprintf (file, _("  --enable-runtime-pseudo-reloc      Work around auto-import limitations by\n\
505                                       adding pseudo-relocations resolved at\n\
506                                       runtime.\n"));
507  fprintf (file, _("  --disable-runtime-pseudo-reloc     Do not add runtime pseudo-relocations for\n\
508                                       auto-imported DATA.\n"));
509  fprintf (file, _("  --enable-extra-pe-debug            Enable verbose debug output when building\n\
510                                       or linking to DLLs (esp. auto-import)\n"));
511#endif
512  fprintf (file, _("  --large-address-aware              Executable supports virtual addresses\n\
513                                       greater than 2 gigabytes\n"));
514  fprintf (file, _("  --disable-large-address-aware      Executable does not support virtual\n\
515                                       addresses greater than 2 gigabytes\n"));
516  fprintf (file, _("  --enable-long-section-names        Use long COFF section names even in\n\
517                                       executable image files\n"));
518  fprintf (file, _("  --disable-long-section-names       Never use long COFF section names, even\n\
519                                       in object files\n"));
520  fprintf (file, _("  --[disable-]dynamicbase            Image base address may be relocated using\n\
521                                       address space layout randomization (ASLR)\n"));
522  fprintf (file, _("  --enable-reloc-section             Create the base relocation table\n"));
523  fprintf (file, _("  --disable-reloc-section            Do not create the base relocation table\n"));
524  fprintf (file, _("  --[disable-]forceinteg             Code integrity checks are enforced\n"));
525  fprintf (file, _("  --[disable-]nxcompat               Image is compatible with data execution\n\
526                                       prevention\n"));
527  fprintf (file, _("  --[disable-]no-isolation           Image understands isolation but do not\n\
528                                       isolate the image\n"));
529  fprintf (file, _("  --[disable-]no-seh                 Image does not use SEH. No SE handler may\n\
530                                       be called in this image\n"));
531  fprintf (file, _("  --[disable-]no-bind                Do not bind this image\n"));
532  fprintf (file, _("  --[disable-]wdmdriver              Driver uses the WDM model\n"));
533  fprintf (file, _("  --[disable-]tsaware                Image is Terminal Server aware\n"));
534  fprintf (file, _("  --build-id[=STYLE]                 Generate build ID\n"));
535}
536
537
538static void
539set_pe_name (char *name, long val)
540{
541  int i;
542  is_underscoring ();
543
544  /* Find the name and set it.  */
545  for (i = 0; init[i].ptr; i++)
546    {
547      if (strcmp (name, GET_INIT_SYMBOL_NAME (i)) == 0)
548	{
549	  init[i].value = val;
550	  init[i].inited = 1;
551	  if (strcmp (name,"__image_base__") == 0)
552	    set_pe_name (U ("__ImageBase"), val);
553	  return;
554	}
555    }
556  abort ();
557}
558
559static void
560set_entry_point (void)
561{
562  const char *entry;
563  const char *initial_symbol_char;
564  int i;
565
566  static const struct
567  {
568    const int value;
569    const char *entry;
570  }
571  v[] =
572    {
573      { 1, "NtProcessStartup"  },
574      { 2, "WinMainCRTStartup" },
575      { 3, "mainCRTStartup"    },
576      { 7, "__PosixProcessStartup"},
577      { 9, "WinMainCRTStartup" },
578      {14, "mainCRTStartup"    },
579      { 0, NULL          }
580    };
581
582  /* Entry point name for arbitrary subsystem numbers.  */
583  static const char default_entry[] = "mainCRTStartup";
584
585  if (bfd_link_dll (&link_info) || dll)
586    {
587#if defined (TARGET_IS_i386pe)
588      entry = "DllMainCRTStartup@12";
589#else
590      entry = "DllMainCRTStartup";
591#endif
592    }
593  else
594    {
595      for (i = 0; v[i].entry; i++)
596	if (v[i].value == pe_subsystem)
597	  break;
598
599      /* If no match, use the default.  */
600      if (v[i].entry != NULL)
601	entry = v[i].entry;
602      else
603	entry = default_entry;
604    }
605
606  initial_symbol_char = (is_underscoring () != 0 ? "_" : "");
607
608  if (*initial_symbol_char != '\0')
609    {
610      char *alc_entry;
611
612      /* lang_default_entry expects its argument to be permanently
613	 allocated, so we don't free this string.  */
614      alc_entry = xmalloc (strlen (initial_symbol_char)
615			   + strlen (entry)
616			   + 1);
617      strcpy (alc_entry, initial_symbol_char);
618      strcat (alc_entry, entry);
619      entry = alc_entry;
620    }
621
622  lang_default_entry (entry);
623}
624
625static void
626set_pe_subsystem (void)
627{
628  const char *sver;
629  char *end;
630  int len;
631  int i;
632  unsigned long temp_subsystem;
633  static const struct
634    {
635      const char *name;
636      const int value;
637    }
638  v[] =
639    {
640      { "native",  1},
641      { "windows", 2},
642      { "console", 3},
643      { "posix",   7},
644      { "wince",   9},
645      { "xbox",   14},
646      { NULL, 0 }
647    };
648
649  /* Check for the presence of a version number.  */
650  sver = strchr (optarg, ':');
651  if (sver == NULL)
652    len = strlen (optarg);
653  else
654    {
655      len = sver - optarg;
656      set_pe_name ("__major_subsystem_version__",
657		    strtoul (sver + 1, &end, 0));
658      if (*end == '.')
659	set_pe_name ("__minor_subsystem_version__",
660		      strtoul (end + 1, &end, 0));
661      if (*end != '\0')
662	einfo (_("%P: warning: bad version number in -subsystem option\n"));
663    }
664
665  /* Check for numeric subsystem.  */
666  temp_subsystem = strtoul (optarg, & end, 0);
667  if ((*end == ':' || *end == '\0') && (temp_subsystem < 65536))
668    {
669      /* Search list for a numeric match to use its entry point.  */
670      for (i = 0; v[i].name; i++)
671	if (v[i].value == (int) temp_subsystem)
672	  break;
673
674      /* Use this subsystem.  */
675      pe_subsystem = (int) temp_subsystem;
676    }
677  else
678    {
679      /* Search for subsystem by name.  */
680      for (i = 0; v[i].name; i++)
681	if (strncmp (optarg, v[i].name, len) == 0
682	    && v[i].name[len] == '\0')
683	  break;
684
685      if (v[i].name == NULL)
686	{
687	  einfo (_("%F%P: invalid subsystem type %s\n"), optarg);
688	  return;
689	}
690
691      pe_subsystem = v[i].value;
692    }
693
694  set_pe_name ("__subsystem__", pe_subsystem);
695
696  return;
697}
698
699
700static void
701set_pe_value (char *name)
702{
703  char *end;
704
705  set_pe_name (name,  strtoul (optarg, &end, 0));
706
707  if (end == optarg)
708    einfo (_("%F%P: invalid hex number for PE parameter '%s'\n"), optarg);
709
710  optarg = end;
711}
712
713
714static void
715set_pe_stack_heap (char *resname, char *comname)
716{
717  set_pe_value (resname);
718
719  if (*optarg == ',')
720    {
721      optarg++;
722      set_pe_value (comname);
723    }
724  else if (*optarg)
725    einfo (_("%F%P: strange hex info for PE parameter '%s'\n"), optarg);
726}
727
728#define DEFAULT_BUILD_ID_STYLE	"md5"
729
730static bool
731gld${EMULATION_NAME}_handle_option (int optc)
732{
733  switch (optc)
734    {
735    default:
736      return false;
737
738    case OPTION_BASE_FILE:
739      link_info.base_file = fopen (optarg, FOPEN_WB);
740      if (link_info.base_file == NULL)
741	einfo (_("%F%P: cannot open base file %s\n"), optarg);
742      break;
743
744      /* PE options.  */
745    case OPTION_HEAP:
746      set_pe_stack_heap ("__size_of_heap_reserve__", "__size_of_heap_commit__");
747      break;
748    case OPTION_STACK:
749      set_pe_stack_heap ("__size_of_stack_reserve__", "__size_of_stack_commit__");
750      break;
751    case OPTION_SUBSYSTEM:
752      set_pe_subsystem ();
753      break;
754    case OPTION_MAJOR_OS_VERSION:
755      set_pe_value ("__major_os_version__");
756      break;
757    case OPTION_MINOR_OS_VERSION:
758      set_pe_value ("__minor_os_version__");
759      break;
760    case OPTION_MAJOR_SUBSYSTEM_VERSION:
761      set_pe_value ("__major_subsystem_version__");
762      break;
763    case OPTION_MINOR_SUBSYSTEM_VERSION:
764      set_pe_value ("__minor_subsystem_version__");
765      break;
766    case OPTION_MAJOR_IMAGE_VERSION:
767      set_pe_value ("__major_image_version__");
768      break;
769    case OPTION_MINOR_IMAGE_VERSION:
770      set_pe_value ("__minor_image_version__");
771      break;
772    case OPTION_FILE_ALIGNMENT:
773      set_pe_value ("__file_alignment__");
774      break;
775    case OPTION_SECTION_ALIGNMENT:
776      set_pe_value ("__section_alignment__");
777      break;
778    case OPTION_DLL:
779      set_pe_name ("__dll__", 1);
780      break;
781    case OPTION_IMAGE_BASE:
782      set_pe_value ("__image_base__");
783      break;
784    case OPTION_SUPPORT_OLD_CODE:
785      support_old_code = 1;
786      break;
787    case OPTION_THUMB_ENTRY:
788      thumb_entry_symbol = optarg;
789      break;
790    case OPTION_USE_NUL_PREFIXED_IMPORT_TABLES:
791      pe_use_nul_prefixed_import_tables = true;
792      break;
793    case OPTION_NO_LEADING_UNDERSCORE:
794      pe_leading_underscore = 0;
795      break;
796    case OPTION_LEADING_UNDERSCORE:
797      pe_leading_underscore = 1;
798      break;
799    case OPTION_INSERT_TIMESTAMP:
800      insert_timestamp = true;
801      break;
802    case OPTION_NO_INSERT_TIMESTAMP:
803      insert_timestamp = false;
804      break;
805#ifdef DLL_SUPPORT
806    case OPTION_OUT_DEF:
807      pe_out_def_filename = xstrdup (optarg);
808      break;
809    case OPTION_EXPORT_ALL:
810      pe_dll_export_everything = 1;
811      break;
812    case OPTION_EXCLUDE_SYMBOLS:
813      pe_dll_add_excludes (optarg, EXCLUDESYMS);
814      break;
815    case OPTION_EXCLUDE_ALL_SYMBOLS:
816      pe_dll_exclude_all_symbols = 1;
817      break;
818    case OPTION_EXCLUDE_LIBS:
819      pe_dll_add_excludes (optarg, EXCLUDELIBS);
820      break;
821    case OPTION_EXCLUDE_MODULES_FOR_IMPLIB:
822      pe_dll_add_excludes (optarg, EXCLUDEFORIMPLIB);
823      break;
824    case OPTION_KILL_ATS:
825      pe_dll_kill_ats = 1;
826      break;
827    case OPTION_STDCALL_ALIASES:
828      pe_dll_stdcall_aliases = 1;
829      break;
830    case OPTION_ENABLE_STDCALL_FIXUP:
831      pe_enable_stdcall_fixup = 1;
832      break;
833    case OPTION_DISABLE_STDCALL_FIXUP:
834      pe_enable_stdcall_fixup = 0;
835      break;
836    case OPTION_WARN_DUPLICATE_EXPORTS:
837      pe_dll_warn_dup_exports = 1;
838      break;
839    case OPTION_IMP_COMPAT:
840      pe_dll_compat_implib = 1;
841      break;
842    case OPTION_ENABLE_AUTO_IMAGE_BASE:
843      pe_enable_auto_image_base = 1;
844      if (optarg && *optarg)
845	{
846	  char *end;
847	  pe_auto_image_base = strtoul (optarg, &end, 0);
848	  /* XXX should check that we actually parsed something */
849	}
850      break;
851    case OPTION_DISABLE_AUTO_IMAGE_BASE:
852      pe_enable_auto_image_base = 0;
853      break;
854    case OPTION_DLL_SEARCH_PREFIX:
855      pe_dll_search_prefix = xstrdup (optarg);
856      break;
857    case OPTION_NO_DEFAULT_EXCLUDES:
858      pe_dll_do_default_excludes = 0;
859      break;
860    case OPTION_DLL_ENABLE_AUTO_IMPORT:
861      link_info.pei386_auto_import = 1;
862      break;
863    case OPTION_DLL_DISABLE_AUTO_IMPORT:
864      link_info.pei386_auto_import = 0;
865      break;
866    case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC:
867      link_info.pei386_runtime_pseudo_reloc =
868	DEFAULT_PSEUDO_RELOC_VERSION;
869      break;
870    case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V1:
871      link_info.pei386_runtime_pseudo_reloc = 1;
872      break;
873    case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2:
874      link_info.pei386_runtime_pseudo_reloc = 2;
875      break;
876    case OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC:
877      link_info.pei386_runtime_pseudo_reloc = 0;
878      break;
879    case OPTION_ENABLE_EXTRA_PE_DEBUG:
880      pe_dll_extra_pe_debug = 1;
881      break;
882#endif
883    case OPTION_LARGE_ADDRESS_AWARE:
884      real_flags |= IMAGE_FILE_LARGE_ADDRESS_AWARE;
885      break;
886    case OPTION_DISABLE_LARGE_ADDRESS_AWARE:
887      real_flags &= ~ IMAGE_FILE_LARGE_ADDRESS_AWARE;
888      break;
889    case OPTION_ENABLE_LONG_SECTION_NAMES:
890      pe_use_coff_long_section_names = 1;
891      break;
892    case OPTION_DISABLE_LONG_SECTION_NAMES:
893      pe_use_coff_long_section_names = 0;
894      break;
895/*  Get DLLCharacteristics bits  */
896    case OPTION_DYNAMIC_BASE:
897      pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
898      /* fall through */
899    case OPTION_ENABLE_RELOC_SECTION:
900      pe_dll_enable_reloc_section = 1;
901      break;
902    case OPTION_DISABLE_RELOC_SECTION:
903      pe_dll_enable_reloc_section = 0;
904      /* fall through */
905    case OPTION_DISABLE_DYNAMIC_BASE:
906      pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
907      break;
908    case OPTION_FORCE_INTEGRITY:
909      pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
910      break;
911    case OPTION_DISABLE_FORCE_INTEGRITY:
912      pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
913      break;
914    case OPTION_NX_COMPAT:
915      pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
916      break;
917    case OPTION_DISABLE_NX_COMPAT:
918      pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
919      break;
920    case OPTION_NO_ISOLATION:
921      pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_ISOLATION;
922      break;
923    case OPTION_DISABLE_NO_ISOLATION:
924      pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_ISOLATION;
925      break;
926    case OPTION_NO_SEH:
927      pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_SEH;
928      break;
929    case OPTION_DISABLE_NO_SEH:
930      pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_SEH;
931      break;
932    case OPTION_NO_BIND:
933      pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_BIND;
934      break;
935    case OPTION_DISABLE_NO_BIND:
936      pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_BIND;
937      break;
938    case OPTION_WDM_DRIVER:
939      pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_WDM_DRIVER;
940      break;
941    case OPTION_DISABLE_WDM_DRIVER:
942      pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_WDM_DRIVER;
943      break;
944    case OPTION_TERMINAL_SERVER_AWARE:
945      pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
946      break;
947    case OPTION_DISABLE_TERMINAL_SERVER_AWARE:
948      pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
949      break;
950    case OPTION_BUILD_ID:
951      free ((char *) emit_build_id);
952      emit_build_id = NULL;
953      if (optarg == NULL)
954	optarg = DEFAULT_BUILD_ID_STYLE;
955      if (strcmp (optarg, "none"))
956	emit_build_id = xstrdup (optarg);
957      break;
958    }
959
960  /*  Set DLLCharacteristics bits  */
961  set_pe_name ("__dll_characteristics__", pe_dll_characteristics);
962
963  return true;
964}
965
966
967#ifdef DLL_SUPPORT
968static unsigned long
969strhash (const char *str)
970{
971  const unsigned char *s;
972  unsigned long hash;
973  unsigned int c;
974  unsigned int len;
975
976  hash = 0;
977  len = 0;
978  s = (const unsigned char *) str;
979  while ((c = *s++) != '\0')
980    {
981      hash += c + (c << 17);
982      hash ^= hash >> 2;
983      ++len;
984    }
985  hash += len + (len << 17);
986  hash ^= hash >> 2;
987
988  return hash;
989}
990
991/* Use the output file to create a image base for relocatable DLLs.  */
992
993static unsigned long
994compute_dll_image_base (const char *ofile)
995{
996  unsigned long hash = strhash (ofile);
997  return pe_auto_image_base + ((hash << 16) & 0x0FFC0000);
998}
999#endif
1000
1001/* Assign values to the special symbols before the linker script is
1002   read.  */
1003
1004static void
1005gld${EMULATION_NAME}_set_symbols (void)
1006{
1007  /* Run through and invent symbols for all the
1008     names and insert the defaults.  */
1009  int j;
1010
1011  is_underscoring ();
1012
1013  if (!init[IMAGEBASEOFF].inited)
1014    {
1015      if (bfd_link_relocatable (&link_info))
1016	init[IMAGEBASEOFF].value = 0;
1017      else if (init[DLLOFF].value || bfd_link_dll (&link_info))
1018	{
1019#ifdef DLL_SUPPORT
1020	  init[IMAGEBASEOFF].value = (pe_enable_auto_image_base
1021				      ? compute_dll_image_base (output_filename)
1022				      : NT_DLL_IMAGE_BASE);
1023#else
1024	  init[IMAGEBASEOFF].value = NT_DLL_IMAGE_BASE;
1025#endif
1026	}
1027      else
1028	init[IMAGEBASEOFF].value = NT_EXE_IMAGE_BASE;
1029      init[MSIMAGEBASEOFF].value = init[IMAGEBASEOFF].value;
1030    }
1031
1032  /* Don't do any symbol assignments if this is a relocatable link.  */
1033  if (bfd_link_relocatable (&link_info))
1034    return;
1035
1036  /* Glue the assignments into the abs section.  */
1037  push_stat_ptr (&abs_output_section->children);
1038
1039  for (j = 0; init[j].ptr; j++)
1040    {
1041      long val = init[j].value;
1042      lang_assignment_statement_type *rv;
1043
1044      rv = lang_add_assignment (exp_assign (GET_INIT_SYMBOL_NAME (j),
1045					    exp_intop (val), false));
1046      if (init[j].size == sizeof (short))
1047	*(short *) init[j].ptr = val;
1048      else if (init[j].size == sizeof (int))
1049	*(int *) init[j].ptr = val;
1050      else if (init[j].size == sizeof (long))
1051	*(long *) init[j].ptr = val;
1052      /* This might be a long long or other special type.  */
1053      else if (init[j].size == sizeof (bfd_vma))
1054	*(bfd_vma *) init[j].ptr = val;
1055      else	abort ();
1056      if (j == IMAGEBASEOFF)
1057	image_base_statement = rv;
1058    }
1059  /* Restore the pointer.  */
1060  pop_stat_ptr ();
1061
1062  if (pe.FileAlignment > pe.SectionAlignment)
1063    {
1064      einfo (_("%P: warning, file alignment > section alignment\n"));
1065    }
1066}
1067
1068/* This is called after the linker script and the command line options
1069   have been read.  */
1070
1071static void
1072gld${EMULATION_NAME}_after_parse (void)
1073{
1074  /* PR ld/6744:  Warn the user if they have used an ELF-only
1075     option hoping it will work on PE.  */
1076  if (link_info.export_dynamic)
1077    einfo (_("%P: warning: --export-dynamic is not supported for PE "
1078      "targets, did you mean --export-all-symbols?\n"));
1079
1080  set_entry_point ();
1081
1082  after_parse_default ();
1083}
1084
1085#ifdef DLL_SUPPORT
1086static struct bfd_link_hash_entry *pe_undef_found_sym;
1087
1088static bool
1089pe_undef_cdecl_match (struct bfd_link_hash_entry *h, void *inf)
1090{
1091  int sl;
1092  char *string = inf;
1093  const char *hs = h->root.string;
1094
1095  sl = strlen (string);
1096  if (h->type == bfd_link_hash_defined
1097      && ((*hs == '@' && *string == '_'
1098		   && strncmp (hs + 1, string + 1, sl - 1) == 0)
1099		  || strncmp (hs, string, sl) == 0)
1100      && h->root.string[sl] == '@')
1101    {
1102      pe_undef_found_sym = h;
1103      return false;
1104    }
1105  return true;
1106}
1107
1108/* Change UNDEF to a defined symbol, taking data from SYM.  */
1109
1110static void
1111change_undef (struct bfd_link_hash_entry * undef,
1112	      struct bfd_link_hash_entry * sym)
1113{
1114  static bool  gave_warning_message = false;
1115
1116  undef->type = bfd_link_hash_defined;
1117  undef->u.def.value = sym->u.def.value;
1118  undef->u.def.section = sym->u.def.section;
1119
1120  if (pe_enable_stdcall_fixup == -1)
1121    {
1122      einfo (_("%P: warning: resolving %s by linking to %s\n"),
1123	     undef->root.string, sym->root.string);
1124
1125      if (! gave_warning_message)
1126	{
1127	  einfo (_("Use --enable-stdcall-fixup to disable these warnings\n"));
1128	  einfo (_("Use --disable-stdcall-fixup to disable these fixups\n"));
1129	  gave_warning_message = true;
1130	}
1131    }
1132
1133  /* PR 19803: Make sure that the linked symbol is not garbage collected.  */
1134  lang_add_gc_name (sym->root.string);
1135}
1136
1137static void
1138pe_fixup_stdcalls (void)
1139{
1140  struct bfd_link_hash_entry *undef, *sym;
1141
1142  if (pe_dll_extra_pe_debug)
1143    printf ("%s\n", __FUNCTION__);
1144
1145  for (undef = link_info.hash->undefs; undef; undef=undef->u.undef.next)
1146    if (undef->type == bfd_link_hash_undefined)
1147      {
1148	const char * name = undef->root.string;
1149	char * at;
1150	int lead_at = (*name == '@');
1151
1152	if (lead_at)
1153	  at = strchr (name + 1, '@');
1154	else
1155	  at = strchr (name, '@');
1156
1157	if (at || lead_at)
1158	  {
1159	    /* The symbol is a stdcall symbol, so let's look for a
1160	       cdecl symbol with the same name and resolve to that.  */
1161	    char *cname = xstrdup (name);
1162
1163	    if (lead_at)
1164	      *cname = '_';
1165	    if (at)
1166	      * strchr (cname, '@') = 0;
1167	    sym = bfd_link_hash_lookup (link_info.hash, cname, false, false, true);
1168
1169	    if (sym && sym->type == bfd_link_hash_defined)
1170	      change_undef (undef, sym);
1171	  }
1172	else
1173	  {
1174	    /* The symbol is a cdecl symbol, so we look for stdcall
1175	       symbols - which means scanning the whole symbol table.  */
1176	    pe_undef_found_sym = NULL;
1177	    bfd_link_hash_traverse (link_info.hash, pe_undef_cdecl_match,
1178				    (char *) name);
1179	    if (pe_undef_found_sym)
1180	      change_undef (undef, pe_undef_found_sym);
1181	  }
1182      }
1183}
1184
1185static void
1186make_import_fixup (arelent *rel, asection *s, char *name, const char *symname)
1187{
1188  struct bfd_symbol *sym = *rel->sym_ptr_ptr;
1189  char addend[4];
1190  bfd_vma _addend;
1191
1192  if (pe_dll_extra_pe_debug)
1193    printf ("arelent: %s@%#lx: add=%li\n", sym->name,
1194	    (unsigned long) rel->address, (long) rel->addend);
1195
1196  if (! bfd_get_section_contents (s->owner, s, addend, rel->address, sizeof (addend)))
1197    einfo (_("%P: %C: cannot get section contents - auto-import exception\n"),
1198	   s->owner, s, rel->address);
1199
1200  _addend = bfd_get_32 (s->owner, addend);
1201  pe_create_import_fixup (rel, s, _addend, name, symname);
1202}
1203
1204static bool
1205pr_sym (struct bfd_hash_entry *h, void *inf ATTRIBUTE_UNUSED)
1206{
1207  printf ("+%s\n", h->string);
1208
1209  return true;
1210}
1211#endif /* DLL_SUPPORT */
1212
1213static void
1214debug_section_p (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
1215{
1216  int *found = (int *) obj;
1217  if (strncmp (".debug_", sect->name, sizeof (".debug_") - 1) == 0)
1218    *found = 1;
1219}
1220
1221static bool
1222pecoff_checksum_contents (bfd *abfd,
1223			  void (*process) (const void *, size_t, void *),
1224			  void *arg)
1225{
1226  file_ptr filepos = (file_ptr) 0;
1227
1228  while (1)
1229    {
1230      unsigned char b;
1231      int status;
1232
1233      if (bfd_seek (abfd, filepos, SEEK_SET) != 0)
1234	return 0;
1235
1236      status = bfd_bread (&b, (bfd_size_type) 1, abfd);
1237      if (status < 1)
1238	{
1239	  break;
1240	}
1241
1242      (*process) (&b, 1, arg);
1243      filepos += 1;
1244    }
1245
1246  return true;
1247}
1248
1249static bool
1250write_build_id (bfd *abfd)
1251{
1252  struct pe_tdata *t = pe_data (abfd);
1253  asection *asec;
1254  struct bfd_link_order *link_order = NULL;
1255  unsigned char *contents;
1256  bfd_size_type size;
1257  bfd_size_type build_id_size;
1258  unsigned char *build_id;
1259
1260  /* Find the section the .buildid output section has been merged info.  */
1261  for (asec = abfd->sections; asec != NULL; asec = asec->next)
1262    {
1263      struct bfd_link_order *l = NULL;
1264      for (l = asec->map_head.link_order; l != NULL; l = l->next)
1265	{
1266	  if (l->type == bfd_indirect_link_order)
1267	    {
1268	      if (l->u.indirect.section == t->build_id.sec)
1269		{
1270		  link_order = l;
1271		  break;
1272		}
1273	    }
1274	}
1275
1276      if (link_order)
1277	break;
1278    }
1279
1280  if (!link_order)
1281    {
1282      einfo (_("%P: warning: .buildid section discarded,"
1283	       " --build-id ignored\n"));
1284      return true;
1285    }
1286
1287  if (t->build_id.sec->contents == NULL)
1288    t->build_id.sec->contents = (unsigned char *) xmalloc (t->build_id.sec->size);
1289  contents = t->build_id.sec->contents;
1290  size = t->build_id.sec->size;
1291
1292  build_id_size = compute_build_id_size (t->build_id.style);
1293  build_id = xmalloc (build_id_size);
1294  generate_build_id (abfd, t->build_id.style, pecoff_checksum_contents, build_id, build_id_size);
1295
1296  bfd_vma ib = pe_data (link_info.output_bfd)->pe_opthdr.ImageBase;
1297
1298  /* Construct a debug directory entry which points to an immediately following CodeView record.  */
1299  struct internal_IMAGE_DEBUG_DIRECTORY idd;
1300  idd.Characteristics = 0;
1301  idd.TimeDateStamp = 0;
1302  idd.MajorVersion = 0;
1303  idd.MinorVersion = 0;
1304  idd.Type = PE_IMAGE_DEBUG_TYPE_CODEVIEW;
1305  idd.SizeOfData = sizeof (CV_INFO_PDB70) + 1;
1306  idd.AddressOfRawData = asec->vma - ib + link_order->offset
1307    + sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1308  idd.PointerToRawData = asec->filepos + link_order->offset
1309    + sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1310
1311  struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *)contents;
1312  _bfd_XXi_swap_debugdir_out (abfd, &idd, ext);
1313
1314  /* Write the debug directory entry.  */
1315  if (bfd_seek (abfd, asec->filepos + link_order->offset, SEEK_SET) != 0)
1316    return 0;
1317
1318  if (bfd_bwrite (contents, size, abfd) != size)
1319    return 0;
1320
1321  /* Construct the CodeView record.  */
1322  CODEVIEW_INFO cvinfo;
1323  cvinfo.CVSignature = CVINFO_PDB70_CVSIGNATURE;
1324  cvinfo.Age = 1;
1325
1326  /* Zero pad or truncate the generated build_id to fit in the CodeView record.  */
1327  memset (&(cvinfo.Signature), 0, CV_INFO_SIGNATURE_LENGTH);
1328  memcpy (&(cvinfo.Signature), build_id, (build_id_size > CV_INFO_SIGNATURE_LENGTH)
1329	  ? CV_INFO_SIGNATURE_LENGTH :  build_id_size);
1330
1331  free (build_id);
1332
1333  /* Write the codeview record.  */
1334  if (_bfd_XXi_write_codeview_record (abfd, idd.PointerToRawData, &cvinfo) == 0)
1335    return 0;
1336
1337  /* Record the location of the debug directory in the data directory.  */
1338  pe_data (link_info.output_bfd)->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
1339    = asec->vma  - ib + link_order->offset;
1340  pe_data (link_info.output_bfd)->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
1341    = sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1342
1343  return true;
1344}
1345
1346/* Make .buildid section, and set up coff_tdata->build_id. */
1347static bool
1348setup_build_id (bfd *ibfd)
1349{
1350  asection *s;
1351  flagword flags;
1352
1353  if (!validate_build_id_style (emit_build_id))
1354    {
1355      einfo (_("%P: warning: unrecognized --build-id style ignored\n"));
1356      return false;
1357    }
1358
1359  flags = (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1360	   | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1361  s = bfd_make_section_anyway_with_flags (ibfd, ".buildid", flags);
1362  if (s != NULL)
1363    {
1364      struct pe_tdata *t = pe_data (link_info.output_bfd);
1365      t->build_id.after_write_object_contents = &write_build_id;
1366      t->build_id.style = emit_build_id;
1367      t->build_id.sec = s;
1368
1369      /* Section is a fixed size:
1370	 One IMAGE_DEBUG_DIRECTORY entry, of type IMAGE_DEBUG_TYPE_CODEVIEW,
1371	 pointing at a CV_INFO_PDB70 record containing the build-id, with a
1372	 null byte for PdbFileName.  */
1373      s->size = sizeof (struct external_IMAGE_DEBUG_DIRECTORY)
1374	+ sizeof (CV_INFO_PDB70) + 1;
1375
1376      return true;
1377    }
1378
1379  einfo (_("%P: warning: cannot create .buildid section,"
1380	   " --build-id ignored\n"));
1381  return false;
1382}
1383
1384static void
1385gld${EMULATION_NAME}_after_open (void)
1386{
1387  after_open_default ();
1388
1389#ifdef DLL_SUPPORT
1390  if (pe_dll_extra_pe_debug)
1391    {
1392      bfd *a;
1393      struct bfd_link_hash_entry *sym;
1394
1395      printf ("%s()\n", __FUNCTION__);
1396
1397      for (sym = link_info.hash->undefs; sym; sym=sym->u.undef.next)
1398	printf ("-%s\n", sym->root.string);
1399      bfd_hash_traverse (&link_info.hash->table, pr_sym, NULL);
1400
1401      for (a = link_info.input_bfds; a; a = a->link.next)
1402	printf ("*%s\n", bfd_get_filename (a));
1403    }
1404#endif
1405
1406  if (emit_build_id != NULL)
1407    {
1408      bfd *abfd;
1409
1410      /* Find a COFF input.  */
1411      for (abfd = link_info.input_bfds;
1412	   abfd != (bfd *) NULL; abfd = abfd->link.next)
1413	if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
1414	  break;
1415
1416      /* If there are no COFF input files do not try to
1417	 add a build-id section.  */
1418      if (abfd == NULL
1419	  || !setup_build_id (abfd))
1420	{
1421	  free ((char *) emit_build_id);
1422	  emit_build_id = NULL;
1423	}
1424    }
1425
1426  /* Pass the wacky PE command line options into the output bfd.
1427     FIXME: This should be done via a function, rather than by
1428     including an internal BFD header.  */
1429
1430  if (bfd_get_flavour (link_info.output_bfd) != bfd_target_coff_flavour
1431      || coff_data (link_info.output_bfd) == NULL
1432      || coff_data (link_info.output_bfd)->pe == 0)
1433    einfo (_("%F%P: cannot perform PE operations on non PE output file '%pB'\n"),
1434	   link_info.output_bfd);
1435
1436  pe_data (link_info.output_bfd)->pe_opthdr = pe;
1437  pe_data (link_info.output_bfd)->dll = init[DLLOFF].value;
1438  pe_data (link_info.output_bfd)->real_flags |= real_flags;
1439  if (insert_timestamp)
1440    pe_data (link_info.output_bfd)->timestamp = -1;
1441  else
1442    pe_data (link_info.output_bfd)->timestamp = 0;
1443
1444  /* At this point we must decide whether to use long section names
1445     in the output or not.  If the user hasn't explicitly specified
1446     on the command line, we leave it to the default for the format
1447     (object files yes, image files no), except if there is debug
1448     information present; GDB relies on the long section names to
1449     find it, so enable it in that case.  */
1450  if (pe_use_coff_long_section_names < 0 && link_info.strip == strip_none)
1451    {
1452      if (bfd_link_relocatable (&link_info))
1453	pe_use_coff_long_section_names = 1;
1454      else
1455	{
1456	  /* Iterate over all sections of all input BFDs, checking
1457	     for any that begin 'debug_' and are long names.  */
1458	  LANG_FOR_EACH_INPUT_STATEMENT (is)
1459	  {
1460	    int found_debug = 0;
1461
1462	    bfd_map_over_sections (is->the_bfd, debug_section_p, &found_debug);
1463	    if (found_debug)
1464	      {
1465		pe_use_coff_long_section_names = 1;
1466		break;
1467	      }
1468	  }
1469	}
1470    }
1471
1472  pe_output_file_set_long_section_names (link_info.output_bfd);
1473
1474#ifdef DLL_SUPPORT
1475  pe_process_import_defs (link_info.output_bfd, &link_info);
1476
1477  if (link_info.pei386_auto_import) /* -1=warn or 1=enable */
1478    pe_find_data_imports (U ("_head_"), make_import_fixup);
1479
1480  /* The implementation of the feature is rather dumb and would cause the
1481     compilation time to go through the roof if there are many undefined
1482     symbols in the link, so it needs to be run after auto-import.  */
1483  if (pe_enable_stdcall_fixup) /* -1=warn or 1=enable */
1484    pe_fixup_stdcalls ();
1485
1486#if defined (TARGET_IS_i386pe) \
1487    || defined (TARGET_IS_armpe) \
1488    || defined (TARGET_IS_arm_wince_pe)
1489  if (!bfd_link_relocatable (&link_info))
1490    pe_dll_build_sections (link_info.output_bfd, &link_info);
1491#else
1492  if (bfd_link_pic (&link_info))
1493    pe_dll_build_sections (link_info.output_bfd, &link_info);
1494  else
1495    pe_exe_build_sections (link_info.output_bfd, &link_info);
1496#endif
1497#endif /* DLL_SUPPORT */
1498
1499#if defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_wince_pe)
1500  if (strstr (bfd_get_target (link_info.output_bfd), "arm") == NULL)
1501    {
1502      /* The arm backend needs special fields in the output hash structure.
1503	 These will only be created if the output format is an arm format,
1504	 hence we do not support linking and changing output formats at the
1505	 same time.  Use a link followed by objcopy to change output formats.  */
1506      einfo (_("%F%P: error: cannot change output format "
1507	       "whilst linking %s binaries\n"), "ARM");
1508      return;
1509    }
1510  {
1511    /* Find a BFD that can hold the interworking stubs.  */
1512    LANG_FOR_EACH_INPUT_STATEMENT (is)
1513      {
1514	if (bfd_arm_get_bfd_for_interworking (is->the_bfd, & link_info))
1515	  break;
1516      }
1517  }
1518#endif
1519
1520  {
1521    /* This next chunk of code tries to detect the case where you have
1522       two import libraries for the same DLL (specifically,
1523       symbolically linking libm.a and libc.a in cygwin to
1524       libcygwin.a).  In those cases, it's possible for function
1525       thunks from the second implib to be used but without the
1526       head/tail objects, causing an improper import table.  We detect
1527       those cases and rename the "other" import libraries to match
1528       the one the head/tail come from, so that the linker will sort
1529       things nicely and produce a valid import table.  */
1530
1531    LANG_FOR_EACH_INPUT_STATEMENT (is)
1532      {
1533	if (is->the_bfd->my_archive)
1534	  {
1535	    int idata2 = 0, reloc_count=0, is_imp = 0;
1536	    asection *sec;
1537
1538	    /* See if this is an import library thunk.  */
1539	    for (sec = is->the_bfd->sections; sec; sec = sec->next)
1540	      {
1541		if (strcmp (sec->name, ".idata\$2") == 0)
1542		  idata2 = 1;
1543		if (startswith (sec->name, ".idata\$"))
1544		  is_imp = 1;
1545		reloc_count += sec->reloc_count;
1546	      }
1547
1548	    if (is_imp && !idata2 && reloc_count)
1549	      {
1550		/* It is, look for the reference to head and see if it's
1551		   from our own library.  */
1552		for (sec = is->the_bfd->sections; sec; sec = sec->next)
1553		  {
1554		    int i;
1555		    long relsize;
1556		    asymbol **symbols;
1557		    arelent **relocs;
1558		    int nrelocs;
1559
1560		    relsize = bfd_get_reloc_upper_bound (is->the_bfd, sec);
1561		    if (relsize < 1)
1562		      break;
1563
1564		    if (!bfd_generic_link_read_symbols (is->the_bfd))
1565		      {
1566			einfo (_("%F%P: %pB: could not read symbols: %E\n"),
1567			       is->the_bfd);
1568			return;
1569		      }
1570		    symbols = bfd_get_outsymbols (is->the_bfd);
1571
1572		    relocs = xmalloc ((size_t) relsize);
1573		    nrelocs = bfd_canonicalize_reloc (is->the_bfd, sec,
1574						      relocs, symbols);
1575		    if (nrelocs < 0)
1576		      {
1577			free (relocs);
1578			einfo (_("%X%P: unable to process relocs: %E\n"));
1579			return;
1580		      }
1581
1582		    for (i = 0; i < nrelocs; i++)
1583		      {
1584			struct bfd_symbol *s;
1585			struct bfd_link_hash_entry * blhe;
1586			const char *other_bfd_filename;
1587
1588			s = (relocs[i]->sym_ptr_ptr)[0];
1589
1590			if (s->flags & BSF_LOCAL)
1591			  continue;
1592
1593			/* Thunk section with reloc to another bfd.  */
1594			blhe = bfd_link_hash_lookup (link_info.hash,
1595						     s->name,
1596						     false, false, true);
1597
1598			if (blhe == NULL
1599			    || blhe->type != bfd_link_hash_defined)
1600			  continue;
1601
1602			other_bfd_filename
1603			  = blhe->u.def.section->owner->my_archive
1604			    ? bfd_get_filename (blhe->u.def.section->owner->my_archive)
1605			    : bfd_get_filename (blhe->u.def.section->owner);
1606
1607			if (filename_cmp (bfd_get_filename
1608					    (is->the_bfd->my_archive),
1609					  other_bfd_filename) == 0)
1610			  continue;
1611
1612			/* Rename this implib to match the other one.  */
1613			if (!bfd_set_filename (is->the_bfd->my_archive,
1614					       other_bfd_filename))
1615			  einfo ("%F%P: %pB: %E\n", is->the_bfd);
1616		      }
1617
1618		    free (relocs);
1619		    /* Note - we do not free the symbols,
1620		       they are now cached in the BFD.  */
1621		  }
1622	      }
1623	  }
1624      }
1625  }
1626
1627  {
1628    int is_ms_arch = 0;
1629    bfd *cur_arch = 0;
1630    lang_input_statement_type *is2;
1631    lang_input_statement_type *is3;
1632
1633    /* Careful - this is a shell script.  Watch those dollar signs! */
1634    /* Microsoft import libraries have every member named the same,
1635       and not in the right order for us to link them correctly.  We
1636       must detect these and rename the members so that they'll link
1637       correctly.  There are three types of objects: the head, the
1638       thunks, and the sentinel(s).  The head is easy; it's the one
1639       with idata2.  We assume that the sentinels won't have relocs,
1640       and the thunks will.  It's easier than checking the symbol
1641       table for external references.  */
1642    LANG_FOR_EACH_INPUT_STATEMENT (is)
1643      {
1644	if (is->the_bfd->my_archive)
1645	  {
1646	    char *pnt;
1647	    bfd *arch = is->the_bfd->my_archive;
1648
1649	    if (cur_arch != arch)
1650	      {
1651		cur_arch = arch;
1652		is_ms_arch = 1;
1653
1654		for (is3 = is;
1655		     is3 && is3->the_bfd->my_archive == arch;
1656		     is3 = (lang_input_statement_type *) is3->next)
1657		  {
1658		    /* A MS dynamic import library can also contain static
1659		       members, so look for the first element with a .dll
1660		       extension, and use that for the remainder of the
1661		       comparisons.  */
1662		    pnt = strrchr (bfd_get_filename (is3->the_bfd), '.');
1663		    if (pnt != NULL && filename_cmp (pnt, ".dll") == 0)
1664		      break;
1665		  }
1666
1667		if (is3 == NULL)
1668		  is_ms_arch = 0;
1669		else
1670		  {
1671		    /* OK, found one.  Now look to see if the remaining
1672		       (dynamic import) members use the same name.  */
1673		    for (is2 = is;
1674			 is2 && is2->the_bfd->my_archive == arch;
1675			 is2 = (lang_input_statement_type *) is2->next)
1676		      {
1677			/* Skip static members, ie anything with a .obj
1678			   extension.  */
1679			pnt = strrchr (bfd_get_filename (is2->the_bfd), '.');
1680			if (pnt != NULL && filename_cmp (pnt, ".obj") == 0)
1681			  continue;
1682
1683			if (filename_cmp (bfd_get_filename (is3->the_bfd),
1684					  bfd_get_filename (is2->the_bfd)))
1685			  {
1686			    is_ms_arch = 0;
1687			    break;
1688			  }
1689		      }
1690		  }
1691	      }
1692
1693	    /* This fragment might have come from an .obj file in a Microsoft
1694	       import, and not an actual import record. If this is the case,
1695	       then leave the filename alone.  */
1696	    pnt = strrchr (bfd_get_filename (is->the_bfd), '.');
1697
1698	    if (is_ms_arch && (filename_cmp (pnt, ".dll") == 0))
1699	      {
1700		int idata2 = 0, reloc_count=0;
1701		asection *sec;
1702		char *new_name, seq;
1703
1704		for (sec = is->the_bfd->sections; sec; sec = sec->next)
1705		  {
1706		    if (strcmp (sec->name, ".idata\$2") == 0)
1707		      idata2 = 1;
1708		    reloc_count += sec->reloc_count;
1709		  }
1710
1711		if (idata2) /* .idata2 is the TOC */
1712		  seq = 'a';
1713		else if (reloc_count > 0) /* thunks */
1714		  seq = 'b';
1715		else /* sentinel */
1716		  seq = 'c';
1717
1718		new_name
1719		  = xmalloc (strlen (bfd_get_filename (is->the_bfd)) + 3);
1720		sprintf (new_name, "%s.%c",
1721			 bfd_get_filename (is->the_bfd), seq);
1722		is->filename = bfd_set_filename (is->the_bfd, new_name);
1723		free (new_name);
1724		if (!is->filename)
1725		  einfo ("%F%P: %pB: %E\n", is->the_bfd);
1726	      }
1727	  }
1728      }
1729  }
1730
1731  {
1732    /* The following chunk of code tries to identify jump stubs in
1733       import libraries which are dead code and eliminates them
1734       from the final link. For each exported symbol <sym>, there
1735       is a object file in the import library with a .text section
1736       and several .idata\$* sections. The .text section contains the
1737       symbol definition for <sym> which is a jump stub of the form
1738       jmp *__imp_<sym>. The .idata\$5 contains the symbol definition
1739       for __imp_<sym> which is the address of the slot for <sym> in
1740       the import address table. When a symbol is imported explicitly
1741       using __declspec(dllimport) declaration, the compiler generates
1742       a reference to __imp_<sym> which directly resolves to the
1743       symbol in .idata\$5, in which case the jump stub code is not
1744       needed. The following code tries to identify jump stub sections
1745       in import libraries which are not referred to by anyone and
1746       marks them for exclusion from the final link.  */
1747    LANG_FOR_EACH_INPUT_STATEMENT (is)
1748      {
1749	if (is->the_bfd->my_archive)
1750	  {
1751	    int is_imp = 0;
1752	    asection *sec, *stub_sec = NULL;
1753
1754	    /* See if this is an import library thunk.  */
1755	    for (sec = is->the_bfd->sections; sec; sec = sec->next)
1756	      {
1757		if (strncmp (sec->name, ".idata\$", 7) == 0)
1758		  is_imp = 1;
1759		/* The section containing the jmp stub has code
1760		   and has a reloc.  */
1761		if ((sec->flags & SEC_CODE) && sec->reloc_count)
1762		  stub_sec = sec;
1763	      }
1764
1765	    if (is_imp && stub_sec)
1766	      {
1767		asymbol **symbols;
1768		long nsyms, src_count;
1769		struct bfd_link_hash_entry * blhe;
1770
1771		if (!bfd_generic_link_read_symbols (is->the_bfd))
1772		  {
1773		    einfo (_("%F%P: %pB: could not read symbols: %E\n"),
1774			   is->the_bfd);
1775		    return;
1776		  }
1777		symbols = bfd_get_outsymbols (is->the_bfd);
1778		nsyms = bfd_get_symcount (is->the_bfd);
1779
1780		for (src_count = 0; src_count < nsyms; src_count++)
1781		  {
1782		    if (symbols[src_count]->section->id == stub_sec->id)
1783		      {
1784			/* This symbol belongs to the section containing
1785			   the stub.  */
1786			blhe = bfd_link_hash_lookup (link_info.hash,
1787						     symbols[src_count]->name,
1788						     false, false, true);
1789			/* If the symbol in the stub section has no other
1790			   undefined references, exclude the stub section
1791			   from the final link.  */
1792			if (blhe != NULL
1793			    && blhe->type == bfd_link_hash_defined
1794			    && blhe->u.undef.next == NULL
1795			    && blhe != link_info.hash->undefs_tail)
1796			  stub_sec->flags |= SEC_EXCLUDE;
1797		      }
1798		  }
1799	      }
1800	  }
1801      }
1802  }
1803}
1804
1805static void
1806gld${EMULATION_NAME}_before_allocation (void)
1807{
1808#if defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_wince_pe)
1809  /* FIXME: we should be able to set the size of the interworking stub
1810     section.
1811
1812     Here we rummage through the found bfds to collect glue
1813     information.  FIXME: should this be based on a command line
1814     option?  krk@cygnus.com.  */
1815  {
1816    LANG_FOR_EACH_INPUT_STATEMENT (is)
1817      {
1818	if (! bfd_arm_process_before_allocation
1819	    (is->the_bfd, & link_info, support_old_code))
1820	  {
1821	    /* xgettext:c-format */
1822	    einfo (_("%P: errors encountered processing file %s for interworking\n"),
1823		   is->filename);
1824	  }
1825      }
1826  }
1827
1828  /* We have seen it all. Allocate it, and carry on.  */
1829  bfd_arm_allocate_interworking_sections (& link_info);
1830#endif /* TARGET_IS_armpe || TARGET_IS_arm_wince_pe */
1831
1832  before_allocation_default ();
1833}
1834
1835#ifdef DLL_SUPPORT
1836/* This is called when an input file isn't recognized as a BFD.  We
1837   check here for .DEF files and pull them in automatically.  */
1838
1839static int
1840saw_option (char *option)
1841{
1842  int i;
1843
1844  for (i = 0; init[i].ptr; i++)
1845    if (strcmp (GET_INIT_SYMBOL_NAME (i), option) == 0)
1846      return init[i].inited;
1847  return 0;
1848}
1849#endif /* DLL_SUPPORT */
1850
1851static bool
1852gld${EMULATION_NAME}_unrecognized_file (lang_input_statement_type *entry ATTRIBUTE_UNUSED)
1853{
1854#ifdef DLL_SUPPORT
1855  const char *ext = entry->filename + strlen (entry->filename) - 4;
1856
1857  if (filename_cmp (ext, ".def") == 0 || filename_cmp (ext, ".DEF") == 0)
1858    {
1859      pe_def_file = def_file_parse (entry->filename, pe_def_file);
1860
1861      if (pe_def_file)
1862	{
1863	  int i, buflen=0, len;
1864	  char *buf;
1865
1866	  for (i = 0; i < pe_def_file->num_exports; i++)
1867	    {
1868	      len = strlen (pe_def_file->exports[i].internal_name);
1869	      if (buflen < len + 2)
1870		buflen = len + 2;
1871	    }
1872
1873	  buf = xmalloc (buflen);
1874
1875	  for (i = 0; i < pe_def_file->num_exports; i++)
1876	    {
1877	      struct bfd_link_hash_entry *h;
1878
1879	      sprintf (buf, "%s%s", U (""),
1880		       pe_def_file->exports[i].internal_name);
1881
1882	      h = bfd_link_hash_lookup (link_info.hash, buf, true, true, true);
1883	      if (h == (struct bfd_link_hash_entry *) NULL)
1884		einfo (_("%F%P: bfd_link_hash_lookup failed: %E\n"));
1885	      if (h->type == bfd_link_hash_new)
1886		{
1887		  h->type = bfd_link_hash_undefined;
1888		  h->u.undef.abfd = NULL;
1889		  bfd_link_add_undef (link_info.hash, h);
1890		}
1891	    }
1892	  free (buf);
1893
1894	  /* def_file_print (stdout, pe_def_file); */
1895	  if (pe_def_file->is_dll == 1)
1896	    link_info.type = type_dll;
1897
1898	  if (pe_def_file->base_address != (bfd_vma)(-1))
1899	    {
1900	      pe.ImageBase
1901		= pe_data (link_info.output_bfd)->pe_opthdr.ImageBase
1902		= init[IMAGEBASEOFF].value
1903		= pe_def_file->base_address;
1904	      init[IMAGEBASEOFF].inited = 1;
1905	      if (image_base_statement)
1906		image_base_statement->exp
1907		  = exp_assign ("__image_base__", exp_intop (pe.ImageBase),
1908				false);
1909	    }
1910
1911	  if (pe_def_file->stack_reserve != -1
1912	      && ! saw_option ("__size_of_stack_reserve__"))
1913	    {
1914	      pe.SizeOfStackReserve = pe_def_file->stack_reserve;
1915	      if (pe_def_file->stack_commit != -1)
1916		pe.SizeOfStackCommit = pe_def_file->stack_commit;
1917	    }
1918	  if (pe_def_file->heap_reserve != -1
1919	      && ! saw_option ("__size_of_heap_reserve__"))
1920	    {
1921	      pe.SizeOfHeapReserve = pe_def_file->heap_reserve;
1922	      if (pe_def_file->heap_commit != -1)
1923		pe.SizeOfHeapCommit = pe_def_file->heap_commit;
1924	    }
1925	  return true;
1926	}
1927    }
1928#endif
1929  return false;
1930}
1931
1932static bool
1933gld${EMULATION_NAME}_recognized_file (lang_input_statement_type *entry ATTRIBUTE_UNUSED)
1934{
1935#ifdef DLL_SUPPORT
1936#ifdef TARGET_IS_i386pe
1937  pe_dll_id_target ("pei-i386");
1938#endif
1939#ifdef TARGET_IS_shpe
1940  pe_dll_id_target ("pei-shl");
1941#endif
1942#ifdef TARGET_IS_armpe
1943  pe_dll_id_target ("pei-arm-little");
1944#endif
1945#ifdef TARGET_IS_arm_wince_pe
1946  pe_dll_id_target ("pei-arm-wince-little");
1947#endif
1948  if (pe_bfd_is_dll (entry->the_bfd))
1949    return pe_implied_import_dll (entry->filename);
1950#endif
1951  return false;
1952}
1953
1954static void
1955gld${EMULATION_NAME}_finish (void)
1956{
1957#if defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_wince_pe)
1958  struct bfd_link_hash_entry * h;
1959
1960  if (thumb_entry_symbol != NULL)
1961    {
1962      h = bfd_link_hash_lookup (link_info.hash, thumb_entry_symbol,
1963				false, false, true);
1964
1965      if (h != (struct bfd_link_hash_entry *) NULL
1966	  && (h->type == bfd_link_hash_defined
1967	      || h->type == bfd_link_hash_defweak)
1968	  && h->u.def.section->output_section != NULL)
1969	{
1970	  static char buffer[32];
1971	  bfd_vma val;
1972
1973	  /* Special procesing is required for a Thumb entry symbol.  The
1974	     bottom bit of its address must be set.  */
1975	  val = (h->u.def.value
1976		 + bfd_section_vma (h->u.def.section->output_section)
1977		 + h->u.def.section->output_offset);
1978
1979	  val |= 1;
1980
1981	  /* Now convert this value into a string and store it in entry_symbol
1982	     where the lang_finish() function will pick it up.  */
1983	  buffer[0] = '0';
1984	  buffer[1] = 'x';
1985
1986	  sprintf_vma (buffer + 2, val);
1987
1988	  if (entry_symbol.name != NULL && entry_from_cmdline)
1989	    einfo (_("%P: warning: '--thumb-entry %s' is overriding '-e %s'\n"),
1990		   thumb_entry_symbol, entry_symbol.name);
1991	  entry_symbol.name = buffer;
1992	}
1993      else
1994	einfo (_("%P: warning: cannot find thumb start symbol %s\n"), thumb_entry_symbol);
1995    }
1996#endif /* defined(TARGET_IS_armpe) || defined(TARGET_IS_arm_wince_pe) */
1997
1998  finish_default ();
1999
2000#ifdef DLL_SUPPORT
2001  if (bfd_link_pic (&link_info)
2002#if !defined(TARGET_IS_shpe)
2003      || pe_dll_enable_reloc_section
2004      || (!bfd_link_relocatable (&link_info)
2005	  && pe_def_file->num_exports != 0)
2006#endif
2007    )
2008    {
2009      pe_dll_fill_sections (link_info.output_bfd, &link_info);
2010      if (command_line.out_implib_filename
2011          && (pe_def_file->num_exports != 0
2012              || bfd_link_pic (&link_info)))
2013	pe_dll_generate_implib (pe_def_file, command_line.out_implib_filename,
2014				&link_info);
2015    }
2016#if defined(TARGET_IS_shpe)
2017  /* ARM doesn't need relocs.  */
2018  else
2019    {
2020      pe_exe_fill_sections (link_info.output_bfd, &link_info);
2021    }
2022#endif
2023
2024  if (pe_out_def_filename)
2025    pe_dll_generate_def_file (pe_out_def_filename);
2026#endif /* DLL_SUPPORT */
2027
2028  /* I don't know where .idata gets set as code, but it shouldn't be.  */
2029  {
2030    asection *asec = bfd_get_section_by_name (link_info.output_bfd, ".idata");
2031
2032    if (asec)
2033      {
2034	asec->flags &= ~SEC_CODE;
2035	asec->flags |= SEC_DATA;
2036      }
2037  }
2038}
2039
2040
2041/* Place an orphan section.
2042
2043   We use this to put sections in a reasonable place in the file, and
2044   to ensure that they are aligned as required.
2045
2046   We handle grouped sections here as well.  A section named .foo\$nn
2047   goes into the output section .foo.  All grouped sections are sorted
2048   by name.
2049
2050   Grouped sections for the default sections are handled by the
2051   default linker script using wildcards, and are sorted by
2052   sort_sections.  */
2053
2054static lang_output_section_statement_type *
2055gld${EMULATION_NAME}_place_orphan (asection *s,
2056				   const char *secname,
2057				   int constraint)
2058{
2059  const char *orig_secname = secname;
2060  char *dollar = NULL;
2061  lang_output_section_statement_type *os;
2062  lang_statement_list_type add_child;
2063  lang_output_section_statement_type *match_by_name = NULL;
2064  lang_statement_union_type **pl;
2065
2066  /* Look through the script to see where to place this section.  */
2067  if (!bfd_link_relocatable (&link_info)
2068      && (dollar = strchr (secname, '\$')) != NULL)
2069    {
2070      size_t len = dollar - secname;
2071      char *newname = xmalloc (len + 1);
2072      memcpy (newname, secname, len);
2073      newname[len] = '\0';
2074      secname = newname;
2075    }
2076
2077  lang_list_init (&add_child);
2078
2079  os = NULL;
2080  if (constraint == 0)
2081    for (os = lang_output_section_find (secname);
2082	 os != NULL;
2083	 os = next_matching_output_section_statement (os, 0))
2084      {
2085	/* If we don't match an existing output section, tell
2086	   lang_insert_orphan to create a new output section.  */
2087	constraint = SPECIAL;
2088
2089	if (os->bfd_section != NULL
2090	    && (os->bfd_section->flags == 0
2091		|| ((s->flags ^ os->bfd_section->flags)
2092		    & (SEC_LOAD | SEC_ALLOC)) == 0))
2093	  {
2094	    /* We already have an output section statement with this
2095	       name, and its bfd section has compatible flags.
2096	       If the section already exists but does not have any flags set,
2097	       then it has been created by the linker, probably as a result of
2098	       a --section-start command line switch.  */
2099	    lang_add_section (&add_child, s, NULL, NULL, os);
2100	    break;
2101	  }
2102
2103	/* Save unused output sections in case we can match them
2104	   against orphans later.  */
2105	if (os->bfd_section == NULL)
2106	  match_by_name = os;
2107      }
2108
2109  /* If we didn't match an active output section, see if we matched an
2110     unused one and use that.  */
2111  if (os == NULL && match_by_name)
2112    {
2113      lang_add_section (&match_by_name->children, s, NULL, NULL, match_by_name);
2114      return match_by_name;
2115    }
2116
2117  if (os == NULL)
2118    {
2119      static struct orphan_save hold[] =
2120	{
2121	  { ".text",
2122	    SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE,
2123	    0, 0, 0, 0 },
2124	  { ".idata",
2125	    SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2126	    0, 0, 0, 0 },
2127	  { ".rdata",
2128	    SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2129	    0, 0, 0, 0 },
2130	  { ".data",
2131	    SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA,
2132	    0, 0, 0, 0 },
2133	  { ".bss",
2134	    SEC_ALLOC,
2135	    0, 0, 0, 0 }
2136	};
2137      enum orphan_save_index
2138	{
2139	  orphan_text = 0,
2140	  orphan_idata,
2141	  orphan_rodata,
2142	  orphan_data,
2143	  orphan_bss
2144	};
2145      static int orphan_init_done = 0;
2146      struct orphan_save *place;
2147      lang_output_section_statement_type *after;
2148      etree_type *address;
2149      flagword flags;
2150      asection *nexts;
2151
2152      if (!orphan_init_done)
2153	{
2154	  struct orphan_save *ho;
2155	  for (ho = hold; ho < hold + sizeof (hold) / sizeof (hold[0]); ++ho)
2156	    if (ho->name != NULL)
2157	      {
2158		ho->os = lang_output_section_find (ho->name);
2159		if (ho->os != NULL && ho->os->flags == 0)
2160		  ho->os->flags = ho->flags;
2161	      }
2162	  orphan_init_done = 1;
2163	}
2164
2165      flags = s->flags;
2166      if (!bfd_link_relocatable (&link_info))
2167	{
2168	  nexts = s;
2169	  while ((nexts = bfd_get_next_section_by_name (nexts->owner,
2170							nexts)))
2171	    if (nexts->output_section == NULL
2172		&& (nexts->flags & SEC_EXCLUDE) == 0
2173		&& ((nexts->flags ^ flags) & (SEC_LOAD | SEC_ALLOC)) == 0
2174		&& (nexts->owner->flags & DYNAMIC) == 0
2175		&& !bfd_input_just_syms (nexts->owner))
2176	      flags = (((flags ^ SEC_READONLY)
2177			| (nexts->flags ^ SEC_READONLY))
2178		       ^ SEC_READONLY);
2179	}
2180
2181      /* Try to put the new output section in a reasonable place based
2182	 on the section name and section flags.  */
2183
2184      place = NULL;
2185      if ((flags & SEC_ALLOC) == 0)
2186	;
2187      else if ((flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
2188	place = &hold[orphan_bss];
2189      else if ((flags & SEC_READONLY) == 0)
2190	place = &hold[orphan_data];
2191      else if ((flags & SEC_CODE) == 0)
2192	{
2193	  place = (!strncmp (secname, ".idata\$", 7) ? &hold[orphan_idata]
2194						     : &hold[orphan_rodata]);
2195	}
2196      else
2197	place = &hold[orphan_text];
2198
2199      after = NULL;
2200      if (place != NULL)
2201	{
2202	  if (place->os == NULL)
2203	    place->os = lang_output_section_find (place->name);
2204	  after = place->os;
2205	  if (after == NULL)
2206	    after = lang_output_section_find_by_flags (s, flags, &place->os,
2207						       NULL);
2208	  if (after == NULL)
2209	    /* *ABS* is always the first output section statement.  */
2210	    after = (void *) lang_os_list.head;
2211	}
2212
2213      /* All sections in an executable must be aligned to a page boundary.
2214	 In a relocatable link, just preserve the incoming alignment; the
2215	 address is discarded by lang_insert_orphan in that case, anyway.  */
2216      address = exp_unop (ALIGN_K, exp_nameop (NAME, "__section_alignment__"));
2217      os = lang_insert_orphan (s, secname, constraint, after, place, address,
2218			       &add_child);
2219      if (bfd_link_relocatable (&link_info))
2220	{
2221	  os->section_alignment = exp_intop (1U << s->alignment_power);
2222	  os->bfd_section->alignment_power = s->alignment_power;
2223	}
2224    }
2225
2226  /* If the section name has a '\$', sort it with the other '\$'
2227     sections.  */
2228  for (pl = &os->children.head; *pl != NULL; pl = &(*pl)->header.next)
2229    {
2230      lang_input_section_type *ls;
2231      const char *lname;
2232
2233      if ((*pl)->header.type != lang_input_section_enum)
2234	continue;
2235
2236      ls = &(*pl)->input_section;
2237
2238      lname = bfd_section_name (ls->section);
2239      if (strchr (lname, '\$') != NULL
2240	  && (dollar == NULL || strcmp (orig_secname, lname) < 0))
2241	break;
2242    }
2243
2244  if (add_child.head != NULL)
2245    {
2246      *add_child.tail = *pl;
2247      *pl = add_child.head;
2248    }
2249
2250  return os;
2251}
2252
2253static bool
2254gld${EMULATION_NAME}_open_dynamic_archive
2255  (const char *arch ATTRIBUTE_UNUSED,
2256   search_dirs_type *search,
2257   lang_input_statement_type *entry)
2258{
2259  static const struct
2260    {
2261      const char * format;
2262      bool use_prefix;
2263    }
2264  libname_fmt [] =
2265    {
2266      /* Preferred explicit import library for dll's.  */
2267      { "lib%s.dll.a", false },
2268      /* Alternate explicit import library for dll's.  */
2269      { "%s.dll.a", false },
2270      /* "libfoo.a" could be either an import lib or a static lib.
2271	 For backwards compatibility, libfoo.a needs to precede
2272	 libfoo.dll and foo.dll in the search.  */
2273      { "lib%s.a", false },
2274      /* The 'native' spelling of an import lib name is "foo.lib".  */
2275      { "%s.lib", false },
2276      /* PR 22948 - Check for an import library.  */
2277      { "lib%s.lib", false },
2278#ifdef DLL_SUPPORT
2279      /* Try "<prefix>foo.dll" (preferred dll name, if specified).  */
2280      {	"%s%s.dll", true },
2281#endif
2282      /* Try "libfoo.dll" (default preferred dll name).  */
2283      {	"lib%s.dll", false },
2284      /* Finally try 'native' dll name "foo.dll".  */
2285      {  "%s.dll", false },
2286      /* Note: If adding more formats to this table, make sure to check to
2287	 see if their length is longer than libname_fmt[0].format, and if
2288	 so, update the call to xmalloc() below.  */
2289      { NULL, false }
2290    };
2291  static unsigned int format_max_len = 0;
2292  const char * filename;
2293  char * full_string;
2294  char * base_string;
2295  unsigned int i;
2296
2297
2298  if (! entry->flags.maybe_archive || entry->flags.full_name_provided)
2299    return false;
2300
2301  filename = entry->filename;
2302
2303  if (format_max_len == 0)
2304    /* We need to allow space in the memory that we are going to allocate
2305       for the characters in the format string.  Since the format array is
2306       static we only need to calculate this information once.  In theory
2307       this value could also be computed statically, but this introduces
2308       the possibility for a discrepancy and hence a possible memory
2309       corruption.  The lengths we compute here will be too long because
2310       they will include any formating characters (%s) in the strings, but
2311       this will not matter.  */
2312    for (i = 0; libname_fmt[i].format; i++)
2313      if (format_max_len < strlen (libname_fmt[i].format))
2314	format_max_len = strlen (libname_fmt[i].format);
2315
2316  full_string = xmalloc (strlen (search->name)
2317			 + strlen (filename)
2318			 + format_max_len
2319#ifdef DLL_SUPPORT
2320			 + (pe_dll_search_prefix
2321			    ? strlen (pe_dll_search_prefix) : 0)
2322#endif
2323			 /* Allow for the terminating NUL and for the path
2324			    separator character that is inserted between
2325			    search->name and the start of the format string.  */
2326			 + 2);
2327
2328  sprintf (full_string, "%s/", search->name);
2329  base_string = full_string + strlen (full_string);
2330
2331  for (i = 0; libname_fmt[i].format; i++)
2332    {
2333#ifdef DLL_SUPPORT
2334      if (libname_fmt[i].use_prefix)
2335	{
2336	  if (!pe_dll_search_prefix)
2337	    continue;
2338	  sprintf (base_string, libname_fmt[i].format, pe_dll_search_prefix, filename);
2339	}
2340      else
2341#endif
2342	sprintf (base_string, libname_fmt[i].format, filename);
2343
2344      if (ldfile_try_open_bfd (full_string, entry))
2345	break;
2346    }
2347
2348  if (!libname_fmt[i].format)
2349    {
2350      free (full_string);
2351      return false;
2352    }
2353
2354  entry->filename = full_string;
2355
2356  return true;
2357}
2358
2359static int
2360gld${EMULATION_NAME}_find_potential_libraries
2361  (char *name, lang_input_statement_type *entry)
2362{
2363  return ldfile_open_file_search (name, entry, "", ".lib");
2364}
2365
2366static char *
2367gld${EMULATION_NAME}_get_script (int *isfile)
2368EOF
2369
2370if test x"$COMPILE_IN" = xyes
2371then
2372# Scripts compiled in.
2373
2374# sed commands to quote an ld script as a C string.
2375sc="-f stringify.sed"
2376
2377fragment <<EOF
2378{
2379  *isfile = 0;
2380
2381  if (bfd_link_relocatable (&link_info) && config.build_constructors)
2382    return
2383EOF
2384sed $sc ldscripts/${EMULATION_NAME}.xu			>> e${EMULATION_NAME}.c
2385echo '  ; else if (bfd_link_relocatable (&link_info)) return' >> e${EMULATION_NAME}.c
2386sed $sc ldscripts/${EMULATION_NAME}.xr			>> e${EMULATION_NAME}.c
2387echo '  ; else if (!config.text_read_only) return'	>> e${EMULATION_NAME}.c
2388sed $sc ldscripts/${EMULATION_NAME}.xbn			>> e${EMULATION_NAME}.c
2389echo '  ; else if (!config.magic_demand_paged) return'	>> e${EMULATION_NAME}.c
2390sed $sc ldscripts/${EMULATION_NAME}.xn			>> e${EMULATION_NAME}.c
2391if test -n "$GENERATE_AUTO_IMPORT_SCRIPT" ; then
2392echo '  ; else if (link_info.pei386_auto_import == 1 && (MERGE_RDATA_V2 || link_info.pei386_runtime_pseudo_reloc != 2)) return'	>> e${EMULATION_NAME}.c
2393sed $sc ldscripts/${EMULATION_NAME}.xa			>> e${EMULATION_NAME}.c
2394fi
2395echo '  ; else return'					>> e${EMULATION_NAME}.c
2396sed $sc ldscripts/${EMULATION_NAME}.x			>> e${EMULATION_NAME}.c
2397echo '; }'						>> e${EMULATION_NAME}.c
2398
2399else
2400# Scripts read from the filesystem.
2401
2402fragment <<EOF
2403{
2404  *isfile = 1;
2405
2406  if (bfd_link_relocatable (&link_info) && config.build_constructors)
2407    return "ldscripts/${EMULATION_NAME}.xu";
2408  else if (bfd_link_relocatable (&link_info))
2409    return "ldscripts/${EMULATION_NAME}.xr";
2410  else if (!config.text_read_only)
2411    return "ldscripts/${EMULATION_NAME}.xbn";
2412  else if (!config.magic_demand_paged)
2413    return "ldscripts/${EMULATION_NAME}.xn";
2414EOF
2415if test -n "$GENERATE_AUTO_IMPORT_SCRIPT" ; then
2416fragment <<EOF
2417  else if (link_info.pei386_auto_import == 1
2418	   && (MERGE_RDATA_V2 || link_info.pei386_runtime_pseudo_reloc != 2))
2419    return "ldscripts/${EMULATION_NAME}.xa";
2420EOF
2421fi
2422fragment <<EOF
2423  else
2424    return "ldscripts/${EMULATION_NAME}.x";
2425}
2426EOF
2427fi
2428
2429LDEMUL_AFTER_PARSE=gld${EMULATION_NAME}_after_parse
2430LDEMUL_AFTER_OPEN=gld${EMULATION_NAME}_after_open
2431LDEMUL_BEFORE_ALLOCATION=gld${EMULATION_NAME}_before_allocation
2432LDEMUL_FINISH=gld${EMULATION_NAME}_finish
2433LDEMUL_OPEN_DYNAMIC_ARCHIVE=gld${EMULATION_NAME}_open_dynamic_archive
2434LDEMUL_PLACE_ORPHAN=gld${EMULATION_NAME}_place_orphan
2435LDEMUL_SET_SYMBOLS=gld${EMULATION_NAME}_set_symbols
2436LDEMUL_ADD_OPTIONS=gld${EMULATION_NAME}_add_options
2437LDEMUL_HANDLE_OPTION=gld${EMULATION_NAME}_handle_option
2438LDEMUL_UNRECOGNIZED_FILE=gld${EMULATION_NAME}_unrecognized_file
2439LDEMUL_LIST_OPTIONS=gld${EMULATION_NAME}_list_options
2440LDEMUL_RECOGNIZED_FILE=gld${EMULATION_NAME}_recognized_file
2441LDEMUL_FIND_POTENTIAL_LIBRARIES=gld${EMULATION_NAME}_find_potential_libraries
2442
2443source_em ${srcdir}/emultempl/emulation.em
2444