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