Update release readme after making 2.43.1 release
[binutils-gdb.git] / ld / emultempl / pep.em
blob00c4ea9e15a765c29b15b621f53d6bfcb499e5ed
1 # This shell script emits a C file. -*- C -*-
2 # It does some substitutions.
3 if [ -z "$MACHINE" ]; then
4   OUTPUT_ARCH=${ARCH}
5 else
6   OUTPUT_ARCH=${ARCH}:${MACHINE}
7 fi
9 case ${target} in
10   *-*-cygwin*)
11     move_default_addr_high=1
12     cygwin_behavior=1
13     ;;
14   *)
15     move_default_addr_high=0;
16     cygwin_behavior=0;
17     ;;
18 esac
20 rm -f e${EMULATION_NAME}.c
21 (echo;echo;echo;echo;echo)>e${EMULATION_NAME}.c # there, now line numbers match ;-)
22 fragment <<EOF
23 /* Copyright (C) 2006-2024 Free Software Foundation, Inc.
24    Written by Kai Tietz, OneVision Software GmbH&CoKg.
26    This file is part of the GNU Binutils.
28    This program is free software; you can redistribute it and/or modify
29    it under the terms of the GNU General Public License as published by
30    the Free Software Foundation; either version 3 of the License, or
31    (at your option) any later version.
33    This program is distributed in the hope that it will be useful,
34    but WITHOUT ANY WARRANTY; without even the implied warranty of
35    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
36    GNU General Public License for more details.
38    You should have received a copy of the GNU General Public License
39    along with this program; if not, write to the Free Software
40    Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
41    MA 02110-1301, USA.  */
44 /* For WINDOWS_XP64 and higher */
45 /* Based on pe.em, but modified for 64 bit support.  */
47 #define TARGET_IS_${EMULATION_NAME}
49 #define COFF_IMAGE_WITH_PE
50 #define COFF_WITH_PE
51 #ifdef TARGET_IS_aarch64pe
52 #define COFF_WITH_peAArch64
53 #elif defined TARGET_IS_arm64pe
54 #define COFF_WITH_peAArch64
55 #elif defined (TARGET_IS_i386pep)
56 #define COFF_WITH_pex64
57 #endif
59 #include "sysdep.h"
60 #include "bfd.h"
61 #include "bfdlink.h"
62 #include "ctf-api.h"
63 #include "getopt.h"
64 #include "libiberty.h"
65 #include "filenames.h"
66 #include "ld.h"
67 #include "ldmain.h"
68 #include "ldexp.h"
69 #include "ldlang.h"
70 #include "ldfile.h"
71 #include "ldemul.h"
72 #include <ldgram.h>
73 #include "ldlex.h"
74 #include "ldmisc.h"
75 #include "ldctor.h"
76 #include "ldbuildid.h"
77 #include "coff/internal.h"
78 EOF
80 case ${target} in
81   x86_64-*-mingw* | x86_64-*-pe | x86_64-*-pep | x86_64-*-cygwin | \
82   i[3-7]86-*-mingw32* | i[3-7]86-*-cygwin* | i[3-7]86-*-winnt | i[3-7]86-*-pe | \
83   aarch64-*-mingw* | aarch64-*-pe* )
84 fragment <<EOF
85 #include "pdb.h"
86 EOF
87     ;;
88 esac
90 fragment <<EOF
92 /* FIXME: See bfd/peXXigen.c for why we include an architecture specific
93    header in generic PE code.  */
94 #ifdef TARGET_IS_i386pep
95 # include "coff/x86_64.h"
96 #elif defined TARGET_IS_aarch64pe
97 # include "coff/aarch64.h"
98 #elif defined TARGET_IS_arm64pe
99 # include "coff/aarch64.h"
100 #endif
101 #include "coff/pe.h"
103 /* FIXME: These are BFD internal header files, and we should not be
104    using it here.  */
105 #include "../bfd/libcoff.h"
106 #include "../bfd/libpei.h"
108 #undef  AOUTSZ
109 #define AOUTSZ          PEPAOUTSZ
110 #define PEAOUTHDR       PEPAOUTHDR
112 #include "deffile.h"
113 #include "pep-dll.h"
114 #include "safe-ctype.h"
116 /* Permit the emulation parameters to override the default section
117    alignment by setting OVERRIDE_SECTION_ALIGNMENT.  FIXME: This makes
118    it seem that include/coff/internal.h should not define
119    PE_DEF_SECTION_ALIGNMENT.  */
120 #if PE_DEF_SECTION_ALIGNMENT != ${OVERRIDE_SECTION_ALIGNMENT:-PE_DEF_SECTION_ALIGNMENT}
121 #undef  PE_DEF_SECTION_ALIGNMENT
122 #define PE_DEF_SECTION_ALIGNMENT ${OVERRIDE_SECTION_ALIGNMENT}
123 #endif
125 #if defined(TARGET_IS_i386pep) || defined(COFF_WITH_peAArch64)
126 #define DLL_SUPPORT
127 #endif
129 #define DEFAULT_DLL_CHARACTERISTICS     (${cygwin_behavior} ? 0 : \
130                                            IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE \
131                                          | IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA \
132                                          | IMAGE_DLL_CHARACTERISTICS_NX_COMPAT)
134 #if defined(TARGET_IS_i386pep) || defined(COFF_WITH_peAArch64) || ! defined(DLL_SUPPORT)
135 #define PE_DEF_SUBSYSTEM                IMAGE_SUBSYSTEM_WINDOWS_CUI
136 #undef NT_EXE_IMAGE_BASE
137 #define NT_EXE_IMAGE_BASE \
138   ((bfd_vma) (${move_default_addr_high} ? 0x100400000LL \
139                                         : 0x140000000LL))
140 #undef NT_DLL_IMAGE_BASE
141 #define NT_DLL_IMAGE_BASE \
142   ((bfd_vma) (${move_default_addr_high} ? 0x400000000LL \
143                                         : 0x180000000LL))
144 #undef NT_DLL_AUTO_IMAGE_BASE
145 #define NT_DLL_AUTO_IMAGE_BASE \
146   ((bfd_vma) (${move_default_addr_high} ? 0x400000000LL \
147                                         : 0x1C0000000LL))
148 #undef NT_DLL_AUTO_IMAGE_MASK
149 #define NT_DLL_AUTO_IMAGE_MASK \
150   ((bfd_vma) (${move_default_addr_high} ? 0x1ffff0000LL \
151                                         : 0x1ffff0000LL))
152 #else
153 #undef  NT_EXE_IMAGE_BASE
154 #define NT_EXE_IMAGE_BASE \
155   ((bfd_vma) (${move_default_addr_high} ? 0x100010000LL \
156                                         : 0x10000LL))
157 #undef NT_DLL_IMAGE_BASE
158 #define NT_DLL_IMAGE_BASE \
159   ((bfd_vma) (${move_default_addr_high} ? 0x110000000LL \
160                                         : 0x10000000LL))
161 #undef NT_DLL_AUTO_IMAGE_BASE
162 #define NT_DLL_AUTO_IMAGE_BASE \
163   ((bfd_vma) (${move_default_addr_high} ? 0x120000000LL \
164                                         : 0x61300000LL))
165 #undef NT_DLL_AUTO_IMAGE_MASK
166 #define NT_DLL_AUTO_IMAGE_MASK \
167   ((bfd_vma) (${move_default_addr_high} ? 0x0ffff0000LL \
168                                         : 0x0ffc0000LL))
169 #undef  PE_DEF_SECTION_ALIGNMENT
170 #define PE_DEF_SUBSYSTEM                IMAGE_SUBSYSTEM_WINDOWS_GUI
171 #undef  PE_DEF_FILE_ALIGNMENT
172 #define PE_DEF_FILE_ALIGNMENT           0x00000200
173 #define PE_DEF_SECTION_ALIGNMENT        0x00000400
174 #endif
176 static struct internal_extra_pe_aouthdr pep;
177 static int dll;
178 static int pep_subsystem = ${SUBSYSTEM};
179 static flagword real_flags = IMAGE_FILE_LARGE_ADDRESS_AWARE;
180 static int support_old_code = 0;
181 static lang_assignment_statement_type *image_base_statement = 0;
182 static unsigned short pe_dll_characteristics = DEFAULT_DLL_CHARACTERISTICS;
183 static bool insert_timestamp = true;
184 static const char *emit_build_id;
185 #ifdef PDB_H
186 static int pdb;
187 static char *pdb_name;
188 #endif
190 #ifdef DLL_SUPPORT
191 static int    pep_enable_stdcall_fixup = 1; /* 0=disable 1=enable (default).  */
192 static char * pep_out_def_filename = NULL;
193 static int    pep_enable_auto_image_base = 0;
194 static char * pep_dll_search_prefix = NULL;
195 #endif
197 extern const char *output_filename;
199 static int
200 is_underscoring (void)
202   int u = 0;
203   if (pep_leading_underscore != -1)
204     return pep_leading_underscore;
205   if (!bfd_get_target_info ("${OUTPUT_FORMAT}", NULL, NULL, &u, NULL))
206     bfd_get_target_info ("${RELOCATEABLE_OUTPUT_FORMAT}", NULL, NULL, &u, NULL);
208   if (u == -1)
209     abort ();
210   pep_leading_underscore = (u != 0 ? 1 : 0);
211   return pep_leading_underscore;
214 /* A case insensitive comparison, regardless of the host platform, used for
215    comparing file extensions.  */
216 static int
217 fileext_cmp (const char *s1, const char *s2)
219   for (;;)
220     {
221       int c1 = TOLOWER (*s1++);
222       int c2 = *s2++; /* Assumed to be lower case from the caller.  */
224       if (c1 != c2)
225         return (c1 - c2);
227       if (c1 == '\0')
228         return 0;
229     }
232 static void
233 gld${EMULATION_NAME}_before_parse (void)
235   is_underscoring ();
236   ldfile_set_output_arch ("${OUTPUT_ARCH}", bfd_arch_`echo ${ARCH} | sed -e 's/:.*//'`);
237   output_filename = "${EXECUTABLE_NAME:-a.exe}";
238 #ifdef DLL_SUPPORT
239   input_flags.dynamic = true;
240   config.has_shared = 1;
241   link_info.pei386_auto_import = 1;
242   link_info.pei386_runtime_pseudo_reloc = 2; /* Use by default version 2.  */
243 #endif
246 /* PE format extra command line options.  */
248 static void
249 gld${EMULATION_NAME}_add_options
250   (int ns ATTRIBUTE_UNUSED,
251    char **shortopts ATTRIBUTE_UNUSED,
252    int nl,
253    struct option **longopts,
254    int nrl ATTRIBUTE_UNUSED,
255    struct option **really_longopts ATTRIBUTE_UNUSED)
257   static const struct option xtra_long[] =
258   {
259     /* PE options */
260     {"base-file", required_argument, NULL, OPTION_BASE_FILE},
261     {"dll", no_argument, NULL, OPTION_DLL},
262     {"file-alignment", required_argument, NULL, OPTION_FILE_ALIGNMENT},
263     {"heap", required_argument, NULL, OPTION_HEAP},
264     {"image-base", required_argument, NULL, OPTION_IMAGE_BASE},
265     {"major-image-version", required_argument, NULL, OPTION_MAJOR_IMAGE_VERSION},
266     {"major-os-version", required_argument, NULL, OPTION_MAJOR_OS_VERSION},
267     {"major-subsystem-version", required_argument, NULL, OPTION_MAJOR_SUBSYSTEM_VERSION},
268     {"minor-image-version", required_argument, NULL, OPTION_MINOR_IMAGE_VERSION},
269     {"minor-os-version", required_argument, NULL, OPTION_MINOR_OS_VERSION},
270     {"minor-subsystem-version", required_argument, NULL, OPTION_MINOR_SUBSYSTEM_VERSION},
271     {"section-alignment", required_argument, NULL, OPTION_SECTION_ALIGNMENT},
272     {"stack", required_argument, NULL, OPTION_STACK},
273     {"subsystem", required_argument, NULL, OPTION_SUBSYSTEM},
274     {"support-old-code", no_argument, NULL, OPTION_SUPPORT_OLD_CODE},
275     {"use-nul-prefixed-import-tables", no_argument, NULL,
276      OPTION_USE_NUL_PREFIXED_IMPORT_TABLES},
277     {"no-leading-underscore", no_argument, NULL, OPTION_NO_LEADING_UNDERSCORE},
278     {"leading-underscore", no_argument, NULL, OPTION_LEADING_UNDERSCORE},
279 #ifdef DLL_SUPPORT
280     /* getopt allows abbreviations, so we do this to stop it
281        from treating -o as an abbreviation for this option.  */
282     {"output-def", required_argument, NULL, OPTION_OUT_DEF},
283     {"output-def", required_argument, NULL, OPTION_OUT_DEF},
284     {"export-all-symbols", no_argument, NULL, OPTION_EXPORT_ALL},
285     {"exclude-symbols", required_argument, NULL, OPTION_EXCLUDE_SYMBOLS},
286     {"exclude-all-symbols", no_argument, NULL, OPTION_EXCLUDE_ALL_SYMBOLS},
287     {"exclude-libs", required_argument, NULL, OPTION_EXCLUDE_LIBS},
288     {"exclude-modules-for-implib", required_argument, NULL, OPTION_EXCLUDE_MODULES_FOR_IMPLIB},
289     {"kill-at", no_argument, NULL, OPTION_KILL_ATS},
290     {"add-stdcall-alias", no_argument, NULL, OPTION_STDCALL_ALIASES},
291     {"enable-stdcall-fixup", no_argument, NULL, OPTION_ENABLE_STDCALL_FIXUP},
292     {"disable-stdcall-fixup", no_argument, NULL, OPTION_DISABLE_STDCALL_FIXUP},
293     {"warn-duplicate-exports", no_argument, NULL, OPTION_WARN_DUPLICATE_EXPORTS},
294     /* getopt() allows abbreviations, so we do this to stop it from
295        treating -c as an abbreviation for these --compat-implib.  */
296     {"compat-implib", no_argument, NULL, OPTION_IMP_COMPAT},
297     {"compat-implib", no_argument, NULL, OPTION_IMP_COMPAT},
298     {"enable-auto-image-base", no_argument, NULL, OPTION_ENABLE_AUTO_IMAGE_BASE},
299     {"disable-auto-image-base", no_argument, NULL, OPTION_DISABLE_AUTO_IMAGE_BASE},
300     {"dll-search-prefix", required_argument, NULL, OPTION_DLL_SEARCH_PREFIX},
301     {"no-default-excludes", no_argument, NULL, OPTION_NO_DEFAULT_EXCLUDES},
302     {"enable-auto-import", no_argument, NULL, OPTION_DLL_ENABLE_AUTO_IMPORT},
303     {"disable-auto-import", no_argument, NULL, OPTION_DLL_DISABLE_AUTO_IMPORT},
304     {"enable-extra-pep-debug", no_argument, NULL, OPTION_ENABLE_EXTRA_PE_DEBUG},
305     {"enable-runtime-pseudo-reloc", no_argument, NULL, OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC},
306     {"disable-runtime-pseudo-reloc", no_argument, NULL, OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC},
307     {"enable-runtime-pseudo-reloc-v2", no_argument, NULL, OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2},
308 #endif
309     {"enable-long-section-names", no_argument, NULL, OPTION_ENABLE_LONG_SECTION_NAMES},
310     {"disable-long-section-names", no_argument, NULL, OPTION_DISABLE_LONG_SECTION_NAMES},
311     {"high-entropy-va", no_argument, NULL, OPTION_HIGH_ENTROPY_VA},
312     {"dynamicbase",no_argument, NULL, OPTION_DYNAMIC_BASE},
313     {"forceinteg", no_argument, NULL, OPTION_FORCE_INTEGRITY},
314     {"nxcompat", no_argument, NULL, OPTION_NX_COMPAT},
315     {"no-isolation", no_argument, NULL, OPTION_NO_ISOLATION},
316     {"no-seh", no_argument, NULL, OPTION_NO_SEH},
317     {"no-bind", no_argument, NULL, OPTION_NO_BIND},
318     {"wdmdriver", no_argument, NULL, OPTION_WDM_DRIVER},
319     {"tsaware", no_argument, NULL, OPTION_TERMINAL_SERVER_AWARE},
320     {"insert-timestamp", no_argument, NULL, OPTION_INSERT_TIMESTAMP},
321     {"no-insert-timestamp", no_argument, NULL, OPTION_NO_INSERT_TIMESTAMP},
322     {"build-id", optional_argument, NULL, OPTION_BUILD_ID},
323 #ifdef PDB_H
324     {"pdb", required_argument, NULL, OPTION_PDB},
325 #endif
326     {"enable-reloc-section", no_argument, NULL, OPTION_ENABLE_RELOC_SECTION},
327     {"disable-reloc-section", no_argument, NULL, OPTION_DISABLE_RELOC_SECTION},
328     {"disable-high-entropy-va", no_argument, NULL, OPTION_DISABLE_HIGH_ENTROPY_VA},
329     {"disable-dynamicbase",no_argument, NULL, OPTION_DISABLE_DYNAMIC_BASE},
330     {"disable-forceinteg", no_argument, NULL, OPTION_DISABLE_FORCE_INTEGRITY},
331     {"disable-nxcompat", no_argument, NULL, OPTION_DISABLE_NX_COMPAT},
332     {"disable-no-isolation", no_argument, NULL, OPTION_DISABLE_NO_ISOLATION},
333     {"disable-no-seh", no_argument, NULL, OPTION_DISABLE_NO_SEH},
334     {"disable-no-bind", no_argument, NULL, OPTION_DISABLE_NO_BIND},
335     {"disable-wdmdriver", no_argument, NULL, OPTION_DISABLE_WDM_DRIVER},
336     {"disable-tsaware", no_argument, NULL, OPTION_DISABLE_TERMINAL_SERVER_AWARE},
337     {NULL, no_argument, NULL, 0}
338   };
340   *longopts
341     = xrealloc (*longopts, nl * sizeof (struct option) + sizeof (xtra_long));
342   memcpy (*longopts + nl, &xtra_long, sizeof (xtra_long));
345 /* PE/WIN32; added routines to get the subsystem type, heap and/or stack
346    parameters which may be input from the command line.  */
348 typedef struct
350   void *ptr;
351   int size;
352   bfd_vma value;
353   char *symbol;
354   int inited;
355   /* FALSE for an assembly level symbol and TRUE for a C visible symbol.
356      C visible symbols can be prefixed by underscore dependent on target's
357      settings.  */
358   bool is_c_symbol;
359 } definfo;
361 #define GET_INIT_SYMBOL_NAME(IDX) \
362   (init[(IDX)].symbol \
363    + ((!init[(IDX)].is_c_symbol || is_underscoring () == 1) ? 0 : 1))
365 /* Decorates the C visible symbol by underscore, if target requires.  */
366 #define U(CSTR) \
367   ((is_underscoring () == 0) ? CSTR : "_" CSTR)
369 #define D(field,symbol,def,usc)  {&pep.field, sizeof (pep.field), def, symbol, 0, usc}
371 static definfo init[] =
373   /* imagebase must be first */
374 #define IMAGEBASEOFF 0
375   D(ImageBase,"__image_base__", NT_EXE_IMAGE_BASE, false),
376 #define DLLOFF 1
377   {&dll, sizeof(dll), 0, "__dll__", 0, false},
378 #define MSIMAGEBASEOFF  2
379   D(ImageBase, "___ImageBase", NT_EXE_IMAGE_BASE, true),
380   D(SectionAlignment,"__section_alignment__", PE_DEF_SECTION_ALIGNMENT, false),
381   D(FileAlignment,"__file_alignment__", PE_DEF_FILE_ALIGNMENT, false),
382   D(MajorOperatingSystemVersion,"__major_os_version__", 4, false),
383   D(MinorOperatingSystemVersion,"__minor_os_version__", 0, false),
384   D(MajorImageVersion,"__major_image_version__", 0, false),
385   D(MinorImageVersion,"__minor_image_version__", 0, false),
386   D(MajorSubsystemVersion,"__major_subsystem_version__", 5, false),
387   D(MinorSubsystemVersion,"__minor_subsystem_version__", 2, false),
388   D(Subsystem,"__subsystem__", ${SUBSYSTEM}, false),
389   D(SizeOfStackReserve,"__size_of_stack_reserve__", 0x200000, false),
390   D(SizeOfStackCommit,"__size_of_stack_commit__", 0x1000, false),
391   D(SizeOfHeapReserve,"__size_of_heap_reserve__", 0x100000, false),
392   D(SizeOfHeapCommit,"__size_of_heap_commit__", 0x1000, false),
393   D(LoaderFlags,"__loader_flags__", 0x0, false),
394   D(DllCharacteristics, "__dll_characteristics__", DEFAULT_DLL_CHARACTERISTICS, false),
395   { NULL, 0, 0, NULL, 0, false}
399 static void
400 gld${EMULATION_NAME}_list_options (FILE *file)
402   fprintf (file, _("  --base_file <basefile>             Generate a base file for relocatable DLLs\n"));
403   fprintf (file, _("  --dll                              Set image base to the default for DLLs\n"));
404   fprintf (file, _("  --file-alignment <size>            Set file alignment\n"));
405   fprintf (file, _("  --heap <size>                      Set initial size of the heap\n"));
406   fprintf (file, _("  --image-base <address>             Set start address of the executable\n"));
407   fprintf (file, _("  --major-image-version <number>     Set version number of the executable\n"));
408   fprintf (file, _("  --major-os-version <number>        Set minimum required OS version\n"));
409   fprintf (file, _("  --major-subsystem-version <number> Set minimum required OS subsystem version\n"));
410   fprintf (file, _("  --minor-image-version <number>     Set revision number of the executable\n"));
411   fprintf (file, _("  --minor-os-version <number>        Set minimum required OS revision\n"));
412   fprintf (file, _("  --minor-subsystem-version <number> Set minimum required OS subsystem revision\n"));
413   fprintf (file, _("  --section-alignment <size>         Set section alignment\n"));
414   fprintf (file, _("  --stack <size>                     Set size of the initial stack\n"));
415   fprintf (file, _("  --subsystem <name>[:<version>]     Set required OS subsystem [& version]\n"));
416   fprintf (file, _("  --support-old-code                 Support interworking with old code\n"));
417   fprintf (file, _("  --[no-]leading-underscore          Set explicit symbol underscore prefix mode\n"));
418   fprintf (file, _("  --[no-]insert-timestamp            Use a real timestamp rather than zero (default)\n"));
419   fprintf (file, _("                                     This makes binaries non-deterministic\n"));
420 #ifdef DLL_SUPPORT
421   fprintf (file, _("  --add-stdcall-alias                Export symbols with and without @nn\n"));
422   fprintf (file, _("  --disable-stdcall-fixup            Don't link _sym to _sym@nn\n"));
423   fprintf (file, _("  --enable-stdcall-fixup             Link _sym to _sym@nn without warnings\n"));
424   fprintf (file, _("  --exclude-symbols sym,sym,...      Exclude symbols from automatic export\n"));
425   fprintf (file, _("  --exclude-all-symbols              Exclude all symbols from automatic export\n"));
426   fprintf (file, _("  --exclude-libs lib,lib,...         Exclude libraries from automatic export\n"));
427   fprintf (file, _("  --exclude-modules-for-implib mod,mod,...\n"));
428   fprintf (file, _("                                     Exclude objects, archive members from auto\n"));
429   fprintf (file, _("                                     export, place into import library instead\n"));
430   fprintf (file, _("  --export-all-symbols               Automatically export all globals to DLL\n"));
431   fprintf (file, _("  --kill-at                          Remove @nn from exported symbols\n"));
432   fprintf (file, _("  --output-def <file>                Generate a .DEF file for the built DLL\n"));
433   fprintf (file, _("  --warn-duplicate-exports           Warn about duplicate exports\n"));
434   fprintf (file, _("  --compat-implib                    Create backward compatible import libs;\n\
435                                        create __imp_<SYMBOL> as well\n"));
436   fprintf (file, _("  --enable-auto-image-base           Automatically choose image base for DLLs\n\
437                                        unless user specifies one\n"));
438   fprintf (file, _("  --disable-auto-image-base          Do not auto-choose image base (default)\n"));
439   fprintf (file, _("  --dll-search-prefix=<string>       When linking dynamically to a dll without\n\
440                                        an importlib, use <string><basename>.dll\n\
441                                        in preference to lib<basename>.dll \n"));
442   fprintf (file, _("  --enable-auto-import               Do sophisticated linking of _sym to\n\
443                                        __imp_sym for DATA references\n"));
444   fprintf (file, _("  --disable-auto-import              Do not auto-import DATA items from DLLs\n"));
445   fprintf (file, _("  --enable-runtime-pseudo-reloc      Work around auto-import limitations by\n\
446                                        adding pseudo-relocations resolved at\n\
447                                        runtime\n"));
448   fprintf (file, _("  --disable-runtime-pseudo-reloc     Do not add runtime pseudo-relocations for\n\
449                                        auto-imported DATA\n"));
450   fprintf (file, _("  --enable-extra-pep-debug            Enable verbose debug output when building\n\
451                                        or linking to DLLs (esp. auto-import)\n"));
452   fprintf (file, _("  --enable-long-section-names        Use long COFF section names even in\n\
453                                        executable image files\n"));
454   fprintf (file, _("  --disable-long-section-names       Never use long COFF section names, even\n\
455                                        in object files\n"));
456   fprintf (file, _("  --[disable-]high-entropy-va        Image is compatible with 64-bit address space\n\
457                                        layout randomization (ASLR)\n"));
458   fprintf (file, _("  --[disable-]dynamicbase            Image base address may be relocated using\n\
459                                        address space layout randomization (ASLR)\n"));
460   fprintf (file, _("  --enable-reloc-section             Create the base relocation table\n"));
461   fprintf (file, _("  --disable-reloc-section            Do not create the base relocation table\n"));
462   fprintf (file, _("  --[disable-]forceinteg             Code integrity checks are enforced\n"));
463   fprintf (file, _("  --[disable-]nxcompat               Image is compatible with data execution\n\
464                                        prevention\n"));
465   fprintf (file, _("  --[disable-]no-isolation           Image understands isolation but do not\n\
466                                        isolate the image\n"));
467   fprintf (file, _("  --[disable-]no-seh                 Image does not use SEH; no SE handler may\n\
468                                        be called in this image\n"));
469   fprintf (file, _("  --[disable-]no-bind                Do not bind this image\n"));
470   fprintf (file, _("  --[disable-]wdmdriver              Driver uses the WDM model\n"));
471   fprintf (file, _("  --[disable-]tsaware                Image is Terminal Server aware\n"));
472   fprintf (file, _("  --build-id[=STYLE]                 Generate build ID\n"));
473 #ifdef PDB_H
474   fprintf (file, _("  --pdb=[FILENAME]                   Generate PDB file\n"));
475 #endif
476 #endif
480 static void
481 set_pep_name (char *name, bfd_vma val)
483   int i;
484   is_underscoring ();
485   /* Find the name and set it.  */
486   for (i = 0; init[i].ptr; i++)
487     {
488       if (strcmp (name, GET_INIT_SYMBOL_NAME (i)) == 0)
489         {
490           init[i].value = val;
491           init[i].inited = 1;
492           if (strcmp (name,"__image_base__") == 0)
493             set_pep_name (U ("__ImageBase"), val);
494           return;
495         }
496     }
497   abort ();
500 static void
501 set_entry_point (void)
503   const char *entry;
504   const char *initial_symbol_char;
505   int i;
507   static const struct
508   {
509     const int value;
510     const char *entry;
511   }
512   v[] =
513     {
514       { 1, "NtProcessStartup"  },
515       { 2, "WinMainCRTStartup" },
516       { 3, "mainCRTStartup"    },
517       { 7, "__PosixProcessStartup" },
518       { 9, "WinMainCRTStartup" },
519       {14, "mainCRTStartup"    },
520       { 0, NULL          }
521     };
523   /* Entry point name for arbitrary subsystem numbers.  */
524   static const char default_entry[] = "mainCRTStartup";
526   if (bfd_link_dll (&link_info) || dll)
527     {
528       entry = "DllMainCRTStartup";
529     }
530   else
531     {
532       for (i = 0; v[i].entry; i++)
533         if (v[i].value == pep_subsystem)
534           break;
536       /* If no match, use the default.  */
537       if (v[i].entry != NULL)
538         entry = v[i].entry;
539       else
540         entry = default_entry;
541     }
543   /* Now we check target's default for getting proper symbol_char.  */
544   initial_symbol_char = (is_underscoring () != 0 ? "_" : "");
546   if (*initial_symbol_char != '\0')
547     {
548       char *alc_entry;
550       /* lang_default_entry expects its argument to be permanently
551          allocated, so we don't free this string.  */
552       alc_entry = xmalloc (strlen (initial_symbol_char)
553                            + strlen (entry)
554                            + 1);
555       strcpy (alc_entry, initial_symbol_char);
556       strcat (alc_entry, entry);
557       entry = alc_entry;
558     }
560   lang_default_entry (entry);
562   if (bfd_link_executable (&link_info) && ! entry_from_cmdline)
563     ldlang_add_undef (entry, false);  
566 static void
567 set_pep_subsystem (void)
569   const char *sver;
570   char *end;
571   int len;
572   int i;
573   unsigned long temp_subsystem;
574   static const struct
575     {
576       const char *name;
577       const int value;
578     }
579   v[] =
580     {
581       { "native",  1 },
582       { "windows", 2 },
583       { "console", 3 },
584       { "posix",   7 },
585       { "wince",   9 },
586       { "xbox",   14 },
587       { NULL, 0 }
588     };
590   /* Check for the presence of a version number.  */
591   sver = strchr (optarg, ':');
592   if (sver == NULL)
593     len = strlen (optarg);
594   else
595     {
596       len = sver - optarg;
597       set_pep_name ("__major_subsystem_version__",
598                     strtoul (sver + 1, &end, 0));
599       if (*end == '.')
600         set_pep_name ("__minor_subsystem_version__",
601                       strtoul (end + 1, &end, 0));
602       if (*end != '\0')
603         einfo (_("%P: warning: bad version number in -subsystem option\n"));
604     }
606   /* Check for numeric subsystem.  */
607   temp_subsystem = strtoul (optarg, & end, 0);
608   if ((*end == ':' || *end == '\0') && (temp_subsystem < 65536))
609     {
610       /* Search list for a numeric match to use its entry point.  */
611       for (i = 0; v[i].name; i++)
612         if (v[i].value == (int) temp_subsystem)
613           break;
615       /* Use this subsystem.  */
616       pep_subsystem = (int) temp_subsystem;
617     }
618   else
619     {
620       /* Search for subsystem by name.  */
621       for (i = 0; v[i].name; i++)
622         if (strncmp (optarg, v[i].name, len) == 0
623             && v[i].name[len] == '\0')
624           break;
626       if (v[i].name == NULL)
627         {
628           einfo (_("%F%P: invalid subsystem type %s\n"), optarg);
629           return;
630         }
632       pep_subsystem = v[i].value;
633     }
635   set_pep_name ("__subsystem__", pep_subsystem);
637   return;
641 static void
642 set_pep_value (char *name)
644   char *end;
646   set_pep_name (name,  (bfd_vma) strtoull (optarg, &end, 0));
648   if (end == optarg)
649     einfo (_("%F%P: invalid hex number for PE parameter '%s'\n"), optarg);
651   optarg = end;
655 static void
656 set_pep_stack_heap (char *resname, char *comname)
658   set_pep_value (resname);
660   if (*optarg == ',')
661     {
662       optarg++;
663       set_pep_value (comname);
664     }
665   else if (*optarg)
666     einfo (_("%F%P: strange hex info for PE parameter '%s'\n"), optarg);
669 #define DEFAULT_BUILD_ID_STYLE  "md5"
671 static bool
672 gld${EMULATION_NAME}_handle_option (int optc)
674   is_underscoring ();
675   switch (optc)
676     {
677     default:
678       return false;
680     case OPTION_BASE_FILE:
681       link_info.base_file = fopen (optarg, FOPEN_WB);
682       if (link_info.base_file == NULL)
683         einfo (_("%F%P: cannot open base file %s\n"), optarg);
684       break;
686       /* PE options.  */
687     case OPTION_HEAP:
688       set_pep_stack_heap ("__size_of_heap_reserve__", "__size_of_heap_commit__");
689       break;
690     case OPTION_STACK:
691       set_pep_stack_heap ("__size_of_stack_reserve__", "__size_of_stack_commit__");
692       break;
693     case OPTION_SUBSYSTEM:
694       set_pep_subsystem ();
695       break;
696     case OPTION_MAJOR_OS_VERSION:
697       set_pep_value ("__major_os_version__");
698       break;
699     case OPTION_MINOR_OS_VERSION:
700       set_pep_value ("__minor_os_version__");
701       break;
702     case OPTION_MAJOR_SUBSYSTEM_VERSION:
703       set_pep_value ("__major_subsystem_version__");
704       break;
705     case OPTION_MINOR_SUBSYSTEM_VERSION:
706       set_pep_value ("__minor_subsystem_version__");
707       break;
708     case OPTION_MAJOR_IMAGE_VERSION:
709       set_pep_value ("__major_image_version__");
710       break;
711     case OPTION_MINOR_IMAGE_VERSION:
712       set_pep_value ("__minor_image_version__");
713       break;
714     case OPTION_FILE_ALIGNMENT:
715       set_pep_value ("__file_alignment__");
716       break;
717     case OPTION_SECTION_ALIGNMENT:
718       set_pep_value ("__section_alignment__");
719       break;
720     case OPTION_DLL:
721       set_pep_name ("__dll__", 1);
722       break;
723     case OPTION_IMAGE_BASE:
724       set_pep_value ("__image_base__");
725       break;
726     case OPTION_SUPPORT_OLD_CODE:
727       support_old_code = 1;
728       break;
729     case OPTION_USE_NUL_PREFIXED_IMPORT_TABLES:
730       pep_use_nul_prefixed_import_tables = true;
731       break;
732     case OPTION_NO_LEADING_UNDERSCORE:
733       pep_leading_underscore = 0;
734       break;
735     case OPTION_LEADING_UNDERSCORE:
736       pep_leading_underscore = 1;
737       break;
738     case OPTION_INSERT_TIMESTAMP:
739       insert_timestamp = true;
740       break;
741     case OPTION_NO_INSERT_TIMESTAMP:
742       insert_timestamp = false;
743       break;
744 #ifdef DLL_SUPPORT
745     case OPTION_OUT_DEF:
746       pep_out_def_filename = xstrdup (optarg);
747       break;
748     case OPTION_EXPORT_ALL:
749       pep_dll_export_everything = 1;
750       break;
751     case OPTION_EXCLUDE_SYMBOLS:
752       pep_dll_add_excludes (optarg, EXCLUDESYMS);
753       break;
754     case OPTION_EXCLUDE_ALL_SYMBOLS:
755       pep_dll_exclude_all_symbols = 1;
756       break;
757     case OPTION_EXCLUDE_LIBS:
758       pep_dll_add_excludes (optarg, EXCLUDELIBS);
759       break;
760     case OPTION_EXCLUDE_MODULES_FOR_IMPLIB:
761       pep_dll_add_excludes (optarg, EXCLUDEFORIMPLIB);
762       break;
763     case OPTION_KILL_ATS:
764       pep_dll_kill_ats = 1;
765       break;
766     case OPTION_STDCALL_ALIASES:
767       pep_dll_stdcall_aliases = 1;
768       break;
769     case OPTION_ENABLE_STDCALL_FIXUP:
770       pep_enable_stdcall_fixup = 1;
771       break;
772     case OPTION_DISABLE_STDCALL_FIXUP:
773       pep_enable_stdcall_fixup = 0;
774       break;
775     case OPTION_WARN_DUPLICATE_EXPORTS:
776       pep_dll_warn_dup_exports = 1;
777       break;
778     case OPTION_IMP_COMPAT:
779       pep_dll_compat_implib = 1;
780       break;
781     case OPTION_ENABLE_AUTO_IMAGE_BASE:
782       pep_enable_auto_image_base = 1;
783       break;
784     case OPTION_DISABLE_AUTO_IMAGE_BASE:
785       pep_enable_auto_image_base = 0;
786       break;
787     case OPTION_DLL_SEARCH_PREFIX:
788       pep_dll_search_prefix = xstrdup (optarg);
789       break;
790     case OPTION_NO_DEFAULT_EXCLUDES:
791       pep_dll_do_default_excludes = 0;
792       break;
793     case OPTION_DLL_ENABLE_AUTO_IMPORT:
794       link_info.pei386_auto_import = 1;
795       break;
796     case OPTION_DLL_DISABLE_AUTO_IMPORT:
797       link_info.pei386_auto_import = 0;
798       break;
799     case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC:
800       link_info.pei386_runtime_pseudo_reloc = 2;
801       break;
802     case OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC:
803       link_info.pei386_runtime_pseudo_reloc = 0;
804       break;
805     case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2:
806       link_info.pei386_runtime_pseudo_reloc = 2;
807       break;
808     case OPTION_ENABLE_EXTRA_PE_DEBUG:
809       pep_dll_extra_pe_debug = 1;
810       break;
811 #endif
812     case OPTION_ENABLE_LONG_SECTION_NAMES:
813       pep_use_coff_long_section_names = 1;
814       break;
815     case OPTION_DISABLE_LONG_SECTION_NAMES:
816       pep_use_coff_long_section_names = 0;
817       break;
818     /*  Get DLLCharacteristics bits  */
819     case OPTION_HIGH_ENTROPY_VA:
820       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
821       /* fall through */
822     case OPTION_DYNAMIC_BASE:
823       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
824       /* fall through */
825     case OPTION_ENABLE_RELOC_SECTION:
826       pep_dll_enable_reloc_section = 1;
827       break;
828     case OPTION_DISABLE_RELOC_SECTION:
829       pep_dll_enable_reloc_section = 0;
830       /* fall through */
831     case OPTION_DISABLE_DYNAMIC_BASE:
832       pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
833       /* fall through */
834     case OPTION_DISABLE_HIGH_ENTROPY_VA:
835       pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
836       break;
837     case OPTION_FORCE_INTEGRITY:
838       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
839       break;
840     case OPTION_DISABLE_FORCE_INTEGRITY:
841       pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
842       break;
843     case OPTION_NX_COMPAT:
844       pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
845       break;
846     case OPTION_DISABLE_NX_COMPAT:
847       pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
848       break;
849     case OPTION_NO_ISOLATION:
850       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_ISOLATION;
851       break;
852     case OPTION_DISABLE_NO_ISOLATION:
853       pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_ISOLATION;
854       break;
855     case OPTION_NO_SEH:
856       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_SEH;
857       break;
858     case OPTION_DISABLE_NO_SEH:
859       pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_SEH;
860       break;
861     case OPTION_NO_BIND:
862       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_BIND;
863       break;
864     case OPTION_DISABLE_NO_BIND:
865       pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_BIND;
866       break;
867     case OPTION_WDM_DRIVER:
868       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_WDM_DRIVER;
869       break;
870     case OPTION_DISABLE_WDM_DRIVER:
871       pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_WDM_DRIVER;
872       break;
873     case OPTION_TERMINAL_SERVER_AWARE:
874       pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
875       break;
876     case OPTION_DISABLE_TERMINAL_SERVER_AWARE:
877       pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
878       break;
879     case OPTION_BUILD_ID:
880       free ((char *) emit_build_id);
881       emit_build_id = NULL;
882       if (optarg == NULL)
883         optarg = DEFAULT_BUILD_ID_STYLE;
884       if (strcmp (optarg, "none"))
885         emit_build_id = xstrdup (optarg);
886       break;
887 #ifdef PDB_H
888     case OPTION_PDB:
889       pdb = 1;
890       if (optarg && optarg[0])
891         pdb_name = xstrdup (optarg);
892       break;
893 #endif
894     }
896   /*  Set DLLCharacteristics bits  */
897   set_pep_name ("__dll_characteristics__", pe_dll_characteristics);
899   return true;
903 #ifdef DLL_SUPPORT
904 static unsigned long
905 strhash (const char *str)
907   const unsigned char *s;
908   unsigned long hash;
909   unsigned int c;
910   unsigned int len;
912   hash = 0;
913   len = 0;
914   s = (const unsigned char *) str;
915   while ((c = *s++) != '\0')
916     {
917       hash += c + (c << 17);
918       hash ^= hash >> 2;
919       ++len;
920     }
921   hash += len + (len << 17);
922   hash ^= hash >> 2;
924   return hash;
927 /* Use the output file to create a image base for relocatable DLLs.  */
929 static bfd_vma
930 compute_dll_image_base (const char *ofile)
932   bfd_vma hash = (bfd_vma) strhash (ofile);
933   return NT_DLL_AUTO_IMAGE_BASE + ((hash << 16) & NT_DLL_AUTO_IMAGE_MASK);
935 #endif
937 /* Assign values to the special symbols before the linker script is
938    read.  */
940 static void
941 gld${EMULATION_NAME}_set_symbols (void)
943   /* Run through and invent symbols for all the
944      names and insert the defaults.  */
945   int j;
947   is_underscoring ();
949   if (!init[IMAGEBASEOFF].inited)
950     {
951       if (bfd_link_relocatable (&link_info))
952         init[IMAGEBASEOFF].value = 0;
953       else if (init[DLLOFF].value || bfd_link_dll (&link_info))
954         {
955 #ifdef DLL_SUPPORT
956           init[IMAGEBASEOFF].value = (pep_enable_auto_image_base
957                                       ? compute_dll_image_base (output_filename)
958                                       : NT_DLL_IMAGE_BASE);
959 #else
960           init[IMAGEBASEOFF].value = NT_DLL_IMAGE_BASE;
961 #endif
962         }
963       else
964         init[IMAGEBASEOFF].value = NT_EXE_IMAGE_BASE;
965       init[MSIMAGEBASEOFF].value = init[IMAGEBASEOFF].value;
966     }
968   /* Don't do any symbol assignments if this is a relocatable link.  */
969   if (bfd_link_relocatable (&link_info))
970     return;
972   /* Glue the assignments into the abs section.  */
973   push_stat_ptr (&abs_output_section->children);
975   for (j = 0; init[j].ptr; j++)
976     {
977       bfd_vma val = init[j].value;
978       lang_assignment_statement_type *rv;
980       rv = lang_add_assignment (exp_assign (GET_INIT_SYMBOL_NAME (j),
981                                             exp_intop (val), false));
982       if (init[j].size == sizeof (short))
983         *(short *) init[j].ptr = (short) val;
984       else if (init[j].size == sizeof (int))
985         *(int *) init[j].ptr = (int) val;
986       else if (init[j].size == sizeof (long))
987         *(long *) init[j].ptr = (long) val;
988       /* This might be a long long or other special type.  */
989       else if (init[j].size == sizeof (bfd_vma))
990         *(bfd_vma *) init[j].ptr = val;
991       else      abort ();
992       if (j == IMAGEBASEOFF)
993         image_base_statement = rv;
994     }
995   /* Restore the pointer.  */
996   pop_stat_ptr ();
998   if (pep.FileAlignment > pep.SectionAlignment)
999     {
1000       einfo (_("%P: warning, file alignment > section alignment\n"));
1001     }
1004 /* This is called after the linker script and the command line options
1005    have been read.  */
1007 static void
1008 gld${EMULATION_NAME}_after_parse (void)
1010   /* PR ld/6744:  Warn the user if they have used an ELF-only
1011      option hoping it will work on PE+.  */
1012   if (link_info.export_dynamic)
1013     einfo (_("%P: warning: --export-dynamic is not supported for PE+ "
1014       "targets, did you mean --export-all-symbols?\n"));
1016 #ifdef PDB_H
1017   if (pdb && emit_build_id == NULL)
1018     emit_build_id = xstrdup (DEFAULT_BUILD_ID_STYLE);
1019 #endif
1021   set_entry_point ();
1023   after_parse_default ();
1026 #ifdef DLL_SUPPORT
1027 static struct bfd_link_hash_entry *pep_undef_found_sym;
1029 static bool
1030 pep_undef_cdecl_match (struct bfd_link_hash_entry *h, void *inf)
1032   int sl;
1033   char *string = inf;
1034   const char *hs = h->root.string;
1036   sl = strlen (string);
1037   if (h->type == bfd_link_hash_defined
1038       && ((*hs == '@' && *string == '_'
1039                    && strncmp (hs + 1, string + 1, sl - 1) == 0)
1040                   || strncmp (hs, string, sl) == 0)
1041       && h->root.string[sl] == '@')
1042     {
1043       pep_undef_found_sym = h;
1044       return false;
1045     }
1046   return true;
1049 static void
1050 set_decoration (const char *undecorated_name,
1051                 struct bfd_link_hash_entry * decoration)
1053   static bool  gave_warning_message = false;
1054   struct decoration_hash_entry *entry;
1056   if (is_underscoring () && undecorated_name[0] == '_')
1057     undecorated_name++;
1059   entry = (struct decoration_hash_entry *)
1060           bfd_hash_lookup (&(coff_hash_table (&link_info)->decoration_hash),
1061                            undecorated_name, true /* create */, false /* copy */);
1063   if (entry->decorated_link != NULL && !gave_warning_message)
1064     {
1065       einfo (_("%P: warning: overwriting decorated name %s with %s\n"),
1066              entry->decorated_link->root.string, undecorated_name);
1067       gave_warning_message = true;
1068     }
1070   entry->decorated_link = decoration;
1073 static void
1074 pep_fixup_stdcalls (void)
1076   static int gave_warning_message = 0;
1077   struct bfd_link_hash_entry *undef, *sym;
1079   if (pep_dll_extra_pe_debug)
1080     printf ("%s\n", __func__);
1082   for (undef = link_info.hash->undefs; undef; undef=undef->u.undef.next)
1083     if (undef->type == bfd_link_hash_undefined)
1084       {
1085         char* at = strchr (undef->root.string, '@');
1086         int lead_at = (*undef->root.string == '@');
1087         if (lead_at)
1088           at = strchr (undef->root.string + 1, '@');
1089         if (at || lead_at)
1090           {
1091             /* The symbol is a stdcall symbol, so let's look for a
1092                cdecl symbol with the same name and resolve to that.  */
1093             char *cname = xstrdup (undef->root.string);
1095             if (lead_at)
1096               *cname = '_';
1097             at = strchr (cname, '@');
1098             if (at)
1099               *at = 0;
1100             sym = bfd_link_hash_lookup (link_info.hash, cname, 0, 0, 1);
1102             if (sym && sym->type == bfd_link_hash_defined)
1103               {
1104                 undef->type = bfd_link_hash_defined;
1105                 undef->u.def.value = sym->u.def.value;
1106                 undef->u.def.section = sym->u.def.section;
1108                 if (pep_enable_stdcall_fixup == -1)
1109                   {
1110                     einfo (_("warning: resolving %s by linking to %s\n"),
1111                            undef->root.string, cname);
1112                     if (! gave_warning_message)
1113                       {
1114                         gave_warning_message = 1;
1115                         einfo (_("Use --enable-stdcall-fixup to disable these warnings\n"));
1116                         einfo (_("Use --disable-stdcall-fixup to disable these fixups\n"));
1117                       }
1118                   }
1119               }
1120           }
1121         else
1122           {
1123             /* The symbol is a cdecl symbol, so we look for stdcall
1124                symbols - which means scanning the whole symbol table.  */
1125             pep_undef_found_sym = 0;
1126             bfd_link_hash_traverse (link_info.hash, pep_undef_cdecl_match,
1127                                     (char *) undef->root.string);
1128             sym = pep_undef_found_sym;
1129             if (sym)
1130               {
1131                 undef->type = bfd_link_hash_defined;
1132                 undef->u.def.value = sym->u.def.value;
1133                 undef->u.def.section = sym->u.def.section;
1134                 set_decoration (undef->root.string, sym);
1136                 if (pep_enable_stdcall_fixup == -1)
1137                   {
1138                     einfo (_("warning: resolving %s by linking to %s\n"),
1139                            undef->root.string, sym->root.string);
1140                     if (! gave_warning_message)
1141                       {
1142                         gave_warning_message = 1;
1143                         einfo (_("Use --enable-stdcall-fixup to disable these warnings\n"));
1144                         einfo (_("Use --disable-stdcall-fixup to disable these fixups\n"));
1145                       }
1146                   }
1147               }
1148           }
1149       }
1152 static bfd_vma
1153 read_addend (arelent *rel, asection *s)
1155   char buf[8];
1156   bfd_vma addend = 0;
1157   bool ok = false;
1159   switch (rel->howto->bitsize)
1160     {
1161     case 8:
1162       ok = bfd_get_section_contents (s->owner, s, buf, rel->address, 1);
1163       if (ok)
1164         {
1165           if (rel->howto->pc_relative)
1166             addend = bfd_get_signed_8 (s->owner, buf);
1167           else
1168             addend = bfd_get_8 (s->owner, buf);
1169         }
1170       break;
1171     case 16:
1172       ok = bfd_get_section_contents (s->owner, s, buf, rel->address, 2);
1173       if (ok)
1174         {
1175           if (rel->howto->pc_relative)
1176             addend = bfd_get_signed_16 (s->owner, buf);
1177           else
1178             addend = bfd_get_16 (s->owner, buf);
1179         }
1180       break;
1181     case 26:
1182     case 32:
1183       ok = bfd_get_section_contents (s->owner, s, buf, rel->address, 4);
1184       if (ok)
1185         {
1186           if (rel->howto->pc_relative)
1187             addend = bfd_get_signed_32 (s->owner, buf);
1188           else
1189             addend = bfd_get_32 (s->owner, buf);
1190         }
1191       break;
1192     case 64:
1193       ok = bfd_get_section_contents (s->owner, s, buf, rel->address, 8);
1194       if (ok)
1195         addend = bfd_get_64 (s->owner, buf);
1196       break;
1197     }
1198   if (!ok)
1199     einfo (_("%P: %H: cannot get section contents - auto-import exception\n"),
1200            s->owner, s, rel->address);
1201   return addend;
1204 static void
1205 make_import_fixup (arelent *rel, asection *s, char *name, const char *symname)
1207   struct bfd_symbol *sym = *rel->sym_ptr_ptr;
1208   bfd_vma addend;
1210   if (pep_dll_extra_pe_debug)
1211     printf ("arelent: %s@%#lx: add=%li\n", sym->name,
1212             (unsigned long) rel->address, (long) rel->addend);
1214   addend = read_addend (rel, s);
1216   if (pep_dll_extra_pe_debug)
1217     {
1218       printf ("import of 0x%lx(0x%lx) sec_addr=0x%lx",
1219               (long) addend, (long) rel->addend, (long) rel->address);
1220       if (rel->howto->pc_relative)
1221         printf (" pcrel");
1222       printf (" %d bit rel.\n", (int) rel->howto->bitsize);
1223     }
1225   pep_create_import_fixup (rel, s, addend, name, symname);
1228 static void
1229 make_runtime_ref (void)
1231   const char *rr = U ("_pei386_runtime_relocator");
1232   struct bfd_link_hash_entry *h
1233     = bfd_wrapped_link_hash_lookup (link_info.output_bfd, &link_info,
1234                                     rr, true, false, true);
1235   if (!h)
1236     einfo (_("%F%P: bfd_link_hash_lookup failed: %E\n"));
1237   else
1238     {
1239       if (h->type == bfd_link_hash_new)
1240         {
1241           h->type = bfd_link_hash_undefined;
1242           h->u.undef.abfd = NULL;
1243           if (h->u.undef.next == NULL && h != link_info.hash->undefs_tail)
1244             bfd_link_add_undef (link_info.hash, h);
1245         }
1246       h->non_ir_ref_regular = true;
1247     }
1250 static bool
1251 pr_sym (struct bfd_hash_entry *h, void *inf ATTRIBUTE_UNUSED)
1253   printf ("+%s\n", h->string);
1255   return true;
1257 #endif /* DLL_SUPPORT */
1259 static void
1260 debug_section_p (bfd *abfd ATTRIBUTE_UNUSED, asection *sect, void *obj)
1262   int *found = (int *) obj;
1264   if (strncmp (".debug_", sect->name, sizeof (".debug_") - 1) == 0)
1265     *found = 1;
1268 static bool
1269 pecoff_checksum_contents (bfd *abfd,
1270                           void (*process) (const void *, size_t, void *),
1271                           void *arg)
1273   file_ptr filepos = (file_ptr) 0;
1275   while (1)
1276     {
1277       unsigned char b;
1278       int status;
1280       if (bfd_seek (abfd, filepos, SEEK_SET) != 0)
1281         return 0;
1283       status = bfd_read (&b, 1, abfd);
1284       if (status < 1)
1285         {
1286           break;
1287         }
1289       (*process) (&b, 1, arg);
1290       filepos += 1;
1291     }
1293   return true;
1296 static bool
1297 write_build_id (bfd *abfd)
1299   struct pe_tdata *td = pe_data (abfd);
1300   asection *asec;
1301   struct bfd_link_order *link_order = NULL;
1302   unsigned char *contents;
1303   bfd_size_type build_id_size;
1304   unsigned char *build_id;
1305   const char *pdb_base_name = NULL;
1307   /* Find the section the .buildid output section has been merged info.  */
1308   for (asec = abfd->sections; asec != NULL; asec = asec->next)
1309     {
1310       struct bfd_link_order *l = NULL;
1311       for (l = asec->map_head.link_order; l != NULL; l = l->next)
1312         {
1313           if (l->type == bfd_indirect_link_order)
1314             {
1315               if (l->u.indirect.section == td->build_id.sec)
1316                 {
1317                   link_order = l;
1318                   break;
1319                 }
1320             }
1321         }
1323       if (link_order)
1324         break;
1325     }
1327   if (!link_order)
1328     {
1329       einfo (_("%P: warning: .buildid section discarded,"
1330                " --build-id ignored\n"));
1331       return true;
1332     }
1334   if (td->build_id.sec->contents == NULL)
1335     td->build_id.sec->contents = xmalloc (td->build_id.sec->size);
1336   contents = td->build_id.sec->contents;
1338   build_id_size = compute_build_id_size (td->build_id.style);
1339   build_id = xmalloc (build_id_size);
1340   generate_build_id (abfd, td->build_id.style, pecoff_checksum_contents,
1341                      build_id, build_id_size);
1343   bfd_vma ib = td->pe_opthdr.ImageBase;
1345 #ifdef PDB_H
1346   if (pdb_name)
1347     pdb_base_name = lbasename (pdb_name);
1348 #endif
1350   /* Construct a debug directory entry which points to an immediately following CodeView record.  */
1351   struct internal_IMAGE_DEBUG_DIRECTORY idd;
1352   idd.Characteristics = 0;
1353   idd.TimeDateStamp = 0;
1354   idd.MajorVersion = 0;
1355   idd.MinorVersion = 0;
1356   idd.Type = PE_IMAGE_DEBUG_TYPE_CODEVIEW;
1357   idd.SizeOfData = (sizeof (CV_INFO_PDB70)
1358 #ifdef PDB_H
1359                     + (pdb_base_name ? strlen (pdb_base_name) : 0)
1360 #endif
1361                     + 1);
1362   idd.AddressOfRawData = asec->vma - ib + link_order->offset
1363     + sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1364   idd.PointerToRawData = asec->filepos + link_order->offset
1365     + sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1367   struct external_IMAGE_DEBUG_DIRECTORY *ext = (struct external_IMAGE_DEBUG_DIRECTORY *)contents;
1368   _bfd_XXi_swap_debugdir_out (abfd, &idd, ext);
1370   /* Write the debug directory entry.  */
1371   if (bfd_seek (abfd, asec->filepos + link_order->offset, SEEK_SET) != 0)
1372     return 0;
1374   if (bfd_write (contents, sizeof (*ext), abfd) != sizeof (*ext))
1375     return 0;
1377 #ifdef PDB_H
1378   if (pdb)
1379     {
1380       if (!create_pdb_file (abfd, pdb_name, build_id))
1381         return 0;
1382     }
1383 #endif
1385   /* Construct the CodeView record.  */
1386   CODEVIEW_INFO cvinfo;
1387   cvinfo.CVSignature = CVINFO_PDB70_CVSIGNATURE;
1388   cvinfo.Age = 1;
1390   /* Zero pad or truncate the generated build_id to fit in the
1391      CodeView record.  */
1392   memset (&(cvinfo.Signature), 0, CV_INFO_SIGNATURE_LENGTH);
1393   memcpy (&(cvinfo.Signature), build_id,
1394           (build_id_size > CV_INFO_SIGNATURE_LENGTH
1395            ? CV_INFO_SIGNATURE_LENGTH : build_id_size));
1397   free (build_id);
1399   /* Write the codeview record.  */
1400   if (_bfd_XXi_write_codeview_record (abfd, idd.PointerToRawData, &cvinfo,
1401                                       pdb_base_name) == 0)
1402     return 0;
1404   /* Record the location of the debug directory in the data directory.  */
1405   td->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
1406     = asec->vma - ib + link_order->offset;
1407   td->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
1408     = sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
1410   return true;
1413 /* Make .buildid section, and set up coff_tdata->build_id. */
1414 static bool
1415 setup_build_id (bfd *ibfd)
1417   asection *s;
1418   flagword flags;
1420   if (!validate_build_id_style (emit_build_id))
1421     {
1422       einfo (_("%P: warning: unrecognized --build-id style ignored\n"));
1423       return false;
1424     }
1426   flags = (SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_IN_MEMORY
1427            | SEC_LINKER_CREATED | SEC_READONLY | SEC_DATA);
1428   s = bfd_make_section_anyway_with_flags (ibfd, ".buildid", flags);
1429   if (s != NULL)
1430     {
1431       struct pe_tdata *td = pe_data (link_info.output_bfd);
1432       td->build_id.after_write_object_contents = &write_build_id;
1433       td->build_id.style = emit_build_id;
1434       td->build_id.sec = s;
1436       /* Section is a fixed size:
1437          One IMAGE_DEBUG_DIRECTORY entry, of type IMAGE_DEBUG_TYPE_CODEVIEW,
1438          pointing at a CV_INFO_PDB70 record containing the build-id, followed by
1439          PdbFileName if relevant.  */
1440       s->size = (sizeof (struct external_IMAGE_DEBUG_DIRECTORY)
1441                  + sizeof (CV_INFO_PDB70) + 1);
1443 #ifdef PDB_H
1444       if (pdb_name)
1445         s->size += strlen (lbasename (pdb_name));
1446 #endif
1447       return true;
1448     }
1450   einfo (_("%P: warning: cannot create .buildid section,"
1451            " --build-id ignored\n"));
1452   return false;
1455 static void
1456 gld${EMULATION_NAME}_before_plugin_all_symbols_read (void)
1458 #ifdef DLL_SUPPORT
1459   if (link_info.lto_plugin_active
1460       && link_info.pei386_auto_import) /* -1=warn or 1=enable */
1461     make_runtime_ref ();
1462 #endif
1465 static void
1466 gld${EMULATION_NAME}_after_open (void)
1468   after_open_default ();
1470   is_underscoring ();
1471 #ifdef DLL_SUPPORT
1472   if (pep_dll_extra_pe_debug)
1473     {
1474       bfd *a;
1475       struct bfd_link_hash_entry *sym;
1477       printf ("%s()\n", __func__);
1479       for (sym = link_info.hash->undefs; sym; sym=sym->u.undef.next)
1480         printf ("-%s\n", sym->root.string);
1481       bfd_hash_traverse (&link_info.hash->table, pr_sym, NULL);
1483       for (a = link_info.input_bfds; a; a = a->link.next)
1484         printf ("*%s\n", bfd_get_filename (a));
1485     }
1486 #endif
1488 #ifdef PDB_H
1489   if (pdb && !pdb_name)
1490     {
1491       const char *base = lbasename (bfd_get_filename (link_info.output_bfd));
1492       size_t len = strlen (base);
1493       static const char suffix[] = ".pdb";
1495       while (len > 0 && base[len] != '.')
1496         {
1497           len--;
1498         }
1500       if (len == 0)
1501         len = strlen (base);
1503       pdb_name = xmalloc (len + sizeof (suffix));
1504       memcpy (pdb_name, base, len);
1505       memcpy (pdb_name + len, suffix, sizeof (suffix));
1506     }
1507 #endif
1509   if (emit_build_id != NULL)
1510     {
1511       bfd *abfd;
1513       /* Find a COFF input.  */
1514       for (abfd = link_info.input_bfds;
1515            abfd != (bfd *) NULL; abfd = abfd->link.next)
1516         if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
1517           break;
1519       /* If there are no COFF input files do not try to
1520          add a build-id section.  */
1521       if (abfd == NULL
1522           || !setup_build_id (abfd))
1523         {
1524           free ((char *) emit_build_id);
1525           emit_build_id = NULL;
1526         }
1527     }
1529   /* Pass the wacky PE command line options into the output bfd.
1530      FIXME: This should be done via a function, rather than by
1531      including an internal BFD header.  */
1533   if (bfd_get_flavour (link_info.output_bfd) != bfd_target_coff_flavour
1534       || coff_data (link_info.output_bfd) == NULL
1535       || !obj_pe (link_info.output_bfd))
1536     einfo (_("%F%P: cannot perform PE operations on non PE output file '%pB'\n"),
1537            link_info.output_bfd);
1539   pe_data (link_info.output_bfd)->pe_opthdr = pep;
1540   pe_data (link_info.output_bfd)->dll = init[DLLOFF].value;
1541   pe_data (link_info.output_bfd)->real_flags |= real_flags;
1542   if (insert_timestamp)
1543     pe_data (link_info.output_bfd)->timestamp = -1;
1544   else
1545     pe_data (link_info.output_bfd)->timestamp = 0;
1547   /* At this point we must decide whether to use long section names
1548      in the output or not.  If the user hasn't explicitly specified
1549      on the command line, we leave it to the default for the format
1550      (object files yes, image files no), except if there is debug
1551      information present; GDB relies on the long section names to
1552      find it, so enable it in that case.  */
1553   if (pep_use_coff_long_section_names < 0 && link_info.strip == strip_none)
1554     {
1555       if (bfd_link_relocatable (&link_info))
1556         pep_use_coff_long_section_names = 1;
1557       else
1558         {
1559           /* Iterate over all sections of all input BFDs, checking
1560              for any that begin 'debug_' and are long names.  */
1561           LANG_FOR_EACH_INPUT_STATEMENT (is)
1562           {
1563             int found_debug = 0;
1565             bfd_map_over_sections (is->the_bfd, debug_section_p, &found_debug);
1566             if (found_debug)
1567               {
1568                 pep_use_coff_long_section_names = 1;
1569                 break;
1570               }
1571           }
1572         }
1573     }
1575   pep_output_file_set_long_section_names (link_info.output_bfd);
1577 #ifdef DLL_SUPPORT
1578   pep_process_import_defs (link_info.output_bfd, &link_info);
1580   if (link_info.pei386_auto_import) /* -1=warn or 1=enable */
1581     pep_find_data_imports (U ("_head_"), make_import_fixup);
1583   /* The implementation of the feature is rather dumb and would cause the
1584      compilation time to go through the roof if there are many undefined
1585      symbols in the link, so it needs to be run after auto-import.  */
1586   if (pep_enable_stdcall_fixup) /* -1=warn or 1=enable */
1587     pep_fixup_stdcalls ();
1589 #if !defined(TARGET_IS_i386pep) && !defined(COFF_WITH_peAArch64)
1590   if (bfd_link_pic (&link_info))
1591 #else
1592   if (!bfd_link_relocatable (&link_info))
1593 #endif
1594     pep_dll_build_sections (link_info.output_bfd, &link_info);
1596 #if !defined(TARGET_IS_i386pep) && !defined(COFF_WITH_peAArch64)
1597   else
1598     pep_exe_build_sections (link_info.output_bfd, &link_info);
1599 #endif
1600 #endif /* DLL_SUPPORT */
1602   {
1603     /* This next chunk of code tries to detect the case where you have
1604        two import libraries for the same DLL (specifically,
1605        symbolically linking libm.a and libc.a in cygwin to
1606        libcygwin.a).  In those cases, it's possible for function
1607        thunks from the second implib to be used but without the
1608        head/tail objects, causing an improper import table.  We detect
1609        those cases and rename the "other" import libraries to match
1610        the one the head/tail come from, so that the linker will sort
1611        things nicely and produce a valid import table.  */
1613     LANG_FOR_EACH_INPUT_STATEMENT (is)
1614       {
1615         if (is->the_bfd->my_archive)
1616           {
1617             int idata2 = 0, reloc_count=0, is_imp = 0;
1618             asection *sec;
1620             /* See if this is an import library thunk.  */
1621             for (sec = is->the_bfd->sections; sec; sec = sec->next)
1622               {
1623                 if (strcmp (sec->name, ".idata\$2") == 0)
1624                   idata2 = 1;
1625                 if (startswith (sec->name, ".idata\$"))
1626                   is_imp = 1;
1627                 reloc_count += sec->reloc_count;
1628               }
1630             if (is_imp && !idata2 && reloc_count)
1631               {
1632                 /* It is, look for the reference to head and see if it's
1633                    from our own library.  */
1634                 for (sec = is->the_bfd->sections; sec; sec = sec->next)
1635                   {
1636                     int i;
1637                     long relsize;
1638                     asymbol **symbols;
1639                     arelent **relocs;
1640                     int nrelocs;
1642                     relsize = bfd_get_reloc_upper_bound (is->the_bfd, sec);
1643                     if (relsize < 1)
1644                       break;
1646                     if (!bfd_generic_link_read_symbols (is->the_bfd))
1647                       {
1648                         einfo (_("%F%P: %pB: could not read symbols: %E\n"),
1649                                is->the_bfd);
1650                         return;
1651                       }
1652                     symbols = bfd_get_outsymbols (is->the_bfd);
1654                     relocs = xmalloc ((size_t) relsize);
1655                     nrelocs = bfd_canonicalize_reloc (is->the_bfd, sec,
1656                                                       relocs, symbols);
1657                     if (nrelocs < 0)
1658                       {
1659                         free (relocs);
1660                         einfo (_("%X%P: unable to process relocs: %E\n"));
1661                         return;
1662                       }
1664                     for (i = 0; i < nrelocs; i++)
1665                       {
1666                         struct bfd_symbol *s;
1667                         struct bfd_link_hash_entry * blhe;
1668                         bfd *other_bfd;
1669                         const char *other_bfd_filename;
1671                         s = (relocs[i]->sym_ptr_ptr)[0];
1673                         if (s->flags & BSF_LOCAL)
1674                           continue;
1676                         /* Thunk section with reloc to another bfd.  */
1677                         blhe = bfd_link_hash_lookup (link_info.hash,
1678                                                      s->name,
1679                                                      false, false, true);
1681                         if (blhe == NULL
1682                             || blhe->type != bfd_link_hash_defined)
1683                           continue;
1685                         other_bfd = blhe->u.def.section->owner;
1686                         if (other_bfd->my_archive == is->the_bfd->my_archive)
1687                           continue;
1689                         other_bfd_filename
1690                           = (other_bfd->my_archive
1691                              ? bfd_get_filename (other_bfd->my_archive)
1692                              : bfd_get_filename (other_bfd));
1694                         if (filename_cmp (bfd_get_filename
1695                                             (is->the_bfd->my_archive),
1696                                           other_bfd_filename) == 0)
1697                           continue;
1699                         /* Sort this implib to match the other one.  */
1700                         lang_input_statement_type *arch_is
1701                           = bfd_usrdata (is->the_bfd->my_archive);
1702                         arch_is->sort_key = other_bfd_filename;
1703                         break;
1704                       }
1706                     free (relocs);
1707                     /* Note - we do not free the symbols,
1708                        they are now cached in the BFD.  */
1709                   }
1710               }
1711           }
1712       }
1713   }
1715   {
1717     /* Careful - this is a shell script.  Watch those dollar signs! */
1718     /* Microsoft import libraries have every member named the same,
1719        and not in the right order for us to link them correctly.  We
1720        must detect these and rename the members so that they'll link
1721        correctly.  There are three types of objects: the head, the
1722        thunks, and the sentinel(s).  The head is easy; it's the one
1723        with idata2.  We assume that the sentinels won't have relocs,
1724        and the thunks will.  It's easier than checking the symbol
1725        table for external references.  */
1726     LANG_FOR_EACH_INPUT_STATEMENT (is)
1727       {
1728         if (is->the_bfd->my_archive)
1729           {
1730             char *pnt;
1732             /* Microsoft import libraries may contain archive members for
1733                one or more DLLs, together with static object files.
1734                Inspect all members that are named *.dll - check whether
1735                they contain .idata sections. Do the renaming of all
1736                archive members that seem to be Microsoft style import
1737                objects.  */
1738             pnt = strrchr (bfd_get_filename (is->the_bfd), '.');
1740             if (pnt != NULL && (fileext_cmp (pnt + 1, "dll") == 0))
1741               {
1742                 int idata2 = 0, reloc_count = 0, idata = 0;
1743                 asection *sec;
1744                 char *new_name, seq;
1746                 for (sec = is->the_bfd->sections; sec; sec = sec->next)
1747                   {
1748                     if (strcmp (sec->name, ".idata\$2") == 0)
1749                       idata2 = 1;
1750                     if (strncmp (sec->name, ".idata\$", 6) == 0)
1751                       idata = 1;
1752                     reloc_count += sec->reloc_count;
1753                   }
1755                 /* An archive member named .dll, but not having any .idata
1756                    sections - apparently not a Microsoft import object
1757                    after all: Skip renaming it.  */
1758                 if (!idata)
1759                   continue;
1761                 if (idata2) /* .idata2 is the TOC */
1762                   seq = 'a';
1763                 else if (reloc_count > 0) /* thunks */
1764                   seq = 'b';
1765                 else /* sentinel */
1766                   seq = 'c';
1768                 new_name
1769                   = xmalloc (strlen (bfd_get_filename (is->the_bfd)) + 3);
1770                 sprintf (new_name, "%s.%c",
1771                          bfd_get_filename (is->the_bfd), seq);
1772                 is->sort_key = new_name;
1773               }
1774           }
1775       }
1776   }
1779 static void
1780 gld${EMULATION_NAME}_before_allocation (void)
1782   is_underscoring ();
1783   before_allocation_default ();
1786 #ifdef DLL_SUPPORT
1787 /* This is called when an input file isn't recognized as a BFD.  We
1788    check here for .DEF files and pull them in automatically.  */
1790 static int
1791 saw_option (char *option)
1793   int i;
1795   is_underscoring ();
1797   for (i = 0; init[i].ptr; i++)
1798     if (strcmp (GET_INIT_SYMBOL_NAME (i), option) == 0)
1799       return init[i].inited;
1800   return 0;
1802 #endif /* DLL_SUPPORT */
1804 static bool
1805 gld${EMULATION_NAME}_unrecognized_file (lang_input_statement_type *entry ATTRIBUTE_UNUSED)
1807 #ifdef DLL_SUPPORT
1808   const char *ext = strrchr (entry->filename, '.');
1810   if (ext != NULL && fileext_cmp (ext + 1, "def") == 0)
1811     {
1812       pep_def_file = def_file_parse (entry->filename, pep_def_file);
1814       if (pep_def_file)
1815         {
1816           int i, buflen=0, len;
1817           char *buf;
1819           for (i = 0; i < pep_def_file->num_exports; i++)
1820             {
1821               len = strlen (pep_def_file->exports[i].internal_name);
1822               if (buflen < len + 2)
1823                 buflen = len + 2;
1824             }
1826           buf = xmalloc (buflen);
1828           for (i = 0; i < pep_def_file->num_exports; i++)
1829             {
1830               struct bfd_link_hash_entry *h;
1832               sprintf (buf, "%s%s", U (""),
1833                        pep_def_file->exports[i].internal_name);
1835               h = bfd_link_hash_lookup (link_info.hash, buf, true, true, true);
1836               if (h == (struct bfd_link_hash_entry *) NULL)
1837                 einfo (_("%F%P: bfd_link_hash_lookup failed: %E\n"));
1838               if (h->type == bfd_link_hash_new)
1839                 {
1840                   h->type = bfd_link_hash_undefined;
1841                   h->u.undef.abfd = NULL;
1842                   bfd_link_add_undef (link_info.hash, h);
1843                 }
1844             }
1845           free (buf);
1847           /* def_file_print (stdout, pep_def_file); */
1848           if (pep_def_file->is_dll == 1)
1849             link_info.type = type_dll;
1851           if (pep_def_file->base_address != (bfd_vma)(-1))
1852             {
1853               pep.ImageBase
1854                 = pe_data (link_info.output_bfd)->pe_opthdr.ImageBase
1855                 = init[IMAGEBASEOFF].value
1856                 = pep_def_file->base_address;
1857               init[IMAGEBASEOFF].inited = 1;
1858               if (image_base_statement)
1859                 image_base_statement->exp
1860                   = exp_assign ("__image_base__", exp_intop (pep.ImageBase),
1861                                 false);
1862             }
1864           if (pep_def_file->stack_reserve != -1
1865               && ! saw_option ("__size_of_stack_reserve__"))
1866             {
1867               pep.SizeOfStackReserve = pep_def_file->stack_reserve;
1868               if (pep_def_file->stack_commit != -1)
1869                 pep.SizeOfStackCommit = pep_def_file->stack_commit;
1870             }
1871           if (pep_def_file->heap_reserve != -1
1872               && ! saw_option ("__size_of_heap_reserve__"))
1873             {
1874               pep.SizeOfHeapReserve = pep_def_file->heap_reserve;
1875               if (pep_def_file->heap_commit != -1)
1876                 pep.SizeOfHeapCommit = pep_def_file->heap_commit;
1877             }
1878           return true;
1879         }
1880     }
1881 #endif
1882   return false;
1885 static bool
1886 gld${EMULATION_NAME}_recognized_file (lang_input_statement_type *entry ATTRIBUTE_UNUSED)
1888   is_underscoring ();
1889 #ifdef DLL_SUPPORT
1890 #ifdef TARGET_IS_i386pep
1891   pep_dll_id_target ("pei-x86-64");
1892 #elif defined(COFF_WITH_peAArch64)
1893   pep_dll_id_target ("pei-aarch64-little");
1894 #endif
1895   if (pep_bfd_is_dll (entry->the_bfd))
1896     return pep_implied_import_dll (entry->filename);
1897 #endif
1898   return false;
1901 static void
1902 gld${EMULATION_NAME}_finish (void)
1904   is_underscoring ();
1905   finish_default ();
1907 #ifdef DLL_SUPPORT
1908   if (bfd_link_pic (&link_info)
1909       || pep_dll_enable_reloc_section
1910       || (!bfd_link_relocatable (&link_info)
1911           && pep_def_file->num_exports != 0))
1912     {
1913       pep_dll_fill_sections (link_info.output_bfd, &link_info);
1914       if (command_line.out_implib_filename
1915           && (pep_def_file->num_exports != 0
1916               || bfd_link_pic (&link_info)))
1917         pep_dll_generate_implib (pep_def_file,
1918                                  command_line.out_implib_filename, &link_info);
1919     }
1921   if (pep_out_def_filename)
1922     pep_dll_generate_def_file (pep_out_def_filename);
1923 #endif /* DLL_SUPPORT */
1925   /* I don't know where .idata gets set as code, but it shouldn't be.  */
1926   {
1927     asection *asec = bfd_get_section_by_name (link_info.output_bfd, ".idata");
1929     if (asec)
1930       {
1931         asec->flags &= ~SEC_CODE;
1932         asec->flags |= SEC_DATA;
1933       }
1934   }
1938 /* Place an orphan section.
1940    We use this to put sections in a reasonable place in the file, and
1941    to ensure that they are aligned as required.
1943    We handle grouped sections here as well.  A section named .foo\$nn
1944    goes into the output section .foo.  All grouped sections are sorted
1945    by name.
1947    Grouped sections for the default sections are handled by the
1948    default linker script using wildcards, and are sorted by
1949    sort_sections.  */
1951 static lang_output_section_statement_type *
1952 gld${EMULATION_NAME}_place_orphan (asection *s,
1953                                     const char *secname,
1954                                     int constraint)
1956   const char *orig_secname = secname;
1957   char *dollar = NULL;
1958   lang_output_section_statement_type *os;
1959   lang_statement_list_type add_child;
1960   lang_output_section_statement_type *match_by_name = NULL;
1961   lang_statement_union_type **pl;
1963   /* Look through the script to see where to place this section.  */
1964   if (!bfd_link_relocatable (&link_info)
1965       && (dollar = strchr (secname, '\$')) != NULL)
1966     {
1967       size_t len = dollar - secname;
1968       char *newname = xmalloc (len + 1);
1969       memcpy (newname, secname, len);
1970       newname[len] = '\0';
1971       secname = newname;
1972     }
1974   lang_list_init (&add_child);
1976   os = NULL;
1977   if (constraint == 0)
1978     for (os = lang_output_section_find (secname);
1979          os != NULL;
1980          os = next_matching_output_section_statement (os, 0))
1981       {
1982         /* If we don't match an existing output section, tell
1983            lang_insert_orphan to create a new output section.  */
1984         constraint = SPECIAL;
1986         if (os->bfd_section != NULL
1987             && (os->bfd_section->flags == 0
1988                 || ((s->flags ^ os->bfd_section->flags)
1989                     & (SEC_LOAD | SEC_ALLOC)) == 0))
1990           {
1991             /* We already have an output section statement with this
1992                name, and its bfd section has compatible flags.
1993                If the section already exists but does not have any flags set,
1994                then it has been created by the linker, probably as a result of
1995                a --section-start command line switch.  */
1996             lang_add_section (&add_child, s, NULL, NULL, os);
1997             break;
1998           }
2000         /* Save unused output sections in case we can match them
2001            against orphans later.  */
2002         if (os->bfd_section == NULL)
2003           match_by_name = os;
2004       }
2006   /* If we didn't match an active output section, see if we matched an
2007      unused one and use that.  */
2008   if (os == NULL && match_by_name)
2009     {
2010       lang_add_section (&match_by_name->children, s, NULL, NULL, match_by_name);
2011       return match_by_name;
2012     }
2014   if (os == NULL)
2015     {
2016       static struct orphan_save hold[] =
2017         {
2018           { ".text",
2019             SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_CODE,
2020             0, 0, 0, 0 },
2021           { ".idata",
2022             SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2023             0, 0, 0, 0 },
2024           { ".rdata",
2025             SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_READONLY | SEC_DATA,
2026             0, 0, 0, 0 },
2027           { ".data",
2028             SEC_HAS_CONTENTS | SEC_ALLOC | SEC_LOAD | SEC_DATA,
2029             0, 0, 0, 0 },
2030           { ".bss",
2031             SEC_ALLOC,
2032             0, 0, 0, 0 }
2033         };
2034       enum orphan_save_index
2035         {
2036           orphan_text = 0,
2037           orphan_idata,
2038           orphan_rodata,
2039           orphan_data,
2040           orphan_bss
2041         };
2042       static int orphan_init_done = 0;
2043       struct orphan_save *place;
2044       lang_output_section_statement_type *after;
2045       etree_type *address;
2046       flagword flags;
2047       asection *nexts;
2049       if (!orphan_init_done)
2050         {
2051           struct orphan_save *ho;
2052           for (ho = hold; ho < hold + sizeof (hold) / sizeof (hold[0]); ++ho)
2053             if (ho->name != NULL)
2054               {
2055                 ho->os = lang_output_section_find (ho->name);
2056                 if (ho->os != NULL && ho->os->flags == 0)
2057                   ho->os->flags = ho->flags;
2058               }
2059           orphan_init_done = 1;
2060         }
2062       flags = s->flags;
2063       if (!bfd_link_relocatable (&link_info))
2064         {
2065           nexts = s;
2066           while ((nexts = bfd_get_next_section_by_name (nexts->owner,
2067                                                         nexts)))
2068             if (nexts->output_section == NULL
2069                 && (nexts->flags & SEC_EXCLUDE) == 0
2070                 && ((nexts->flags ^ flags) & (SEC_LOAD | SEC_ALLOC)) == 0
2071                 && (nexts->owner->flags & DYNAMIC) == 0
2072                 && !bfd_input_just_syms (nexts->owner))
2073               flags = (((flags ^ SEC_READONLY)
2074                         | (nexts->flags ^ SEC_READONLY))
2075                        ^ SEC_READONLY);
2076         }
2078       /* Try to put the new output section in a reasonable place based
2079          on the section name and section flags.  */
2081       place = NULL;
2082       if ((flags & SEC_ALLOC) == 0)
2083         ;
2084       else if ((flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
2085         place = &hold[orphan_bss];
2086       else if ((flags & SEC_READONLY) == 0)
2087         place = &hold[orphan_data];
2088       else if ((flags & SEC_CODE) == 0)
2089         {
2090           place = (!strncmp (secname, ".idata\$", 7) ? &hold[orphan_idata]
2091                                                      : &hold[orphan_rodata]);
2092         }
2093       else
2094         place = &hold[orphan_text];
2096       after = NULL;
2097       if (place != NULL)
2098         {
2099           if (place->os == NULL)
2100             place->os = lang_output_section_find (place->name);
2101           after = place->os;
2102           if (after == NULL)
2103             after = lang_output_section_find_by_flags (s, flags, &place->os,
2104                                                        NULL);
2105           if (after == NULL)
2106             /* *ABS* is always the first output section statement.  */
2107             after = (void *) lang_os_list.head;
2108         }
2110       /* All sections in an executable must be aligned to a page boundary.
2111          In a relocatable link, just preserve the incoming alignment; the
2112          address is discarded by lang_insert_orphan in that case, anyway.  */
2113       address = exp_unop (ALIGN_K, exp_nameop (NAME, "__section_alignment__"));
2114       os = lang_insert_orphan (s, secname, constraint, after, place, address,
2115                                &add_child);
2116       if (bfd_link_relocatable (&link_info))
2117         {
2118           os->section_alignment = exp_intop (1U << s->alignment_power);
2119           os->bfd_section->alignment_power = s->alignment_power;
2120         }
2121     }
2123   /* If the section name has a '\$', sort it with the other '\$'
2124      sections.  */
2125   for (pl = &os->children.head; *pl != NULL; pl = &(*pl)->header.next)
2126     {
2127       lang_input_section_type *ls;
2128       const char *lname;
2130       if ((*pl)->header.type != lang_input_section_enum)
2131         continue;
2133       ls = &(*pl)->input_section;
2135       lname = bfd_section_name (ls->section);
2136       if (strchr (lname, '\$') != NULL
2137           && (dollar == NULL || strcmp (orig_secname, lname) < 0))
2138         break;
2139     }
2141   if (add_child.head != NULL)
2142     {
2143       *add_child.tail = *pl;
2144       *pl = add_child.head;
2145     }
2147   return os;
2150 static bool
2151 gld${EMULATION_NAME}_open_dynamic_archive
2152   (const char *arch ATTRIBUTE_UNUSED,
2153    search_dirs_type *search,
2154    lang_input_statement_type *entry)
2156   static const struct
2157     {
2158       const char * format;
2159       bool use_prefix;
2160     }
2161   libname_fmt [] =
2162     {
2163       /* Preferred explicit import library for dll's.  */
2164       { "lib%s.dll.a", false },
2165       /* Alternate explicit import library for dll's.  */
2166       { "%s.dll.a", false },
2167       /* "libfoo.a" could be either an import lib or a static lib.
2168          For backwards compatibility, libfoo.a needs to precede
2169          libfoo.dll and foo.dll in the search.  */
2170       { "lib%s.a", false },
2171       /* The 'native' spelling of an import lib name is "foo.lib".  */
2172       { "%s.lib", false },
2173       /* PR 22948 - Check for an import library.  */
2174       { "lib%s.lib", false },
2175 #ifdef DLL_SUPPORT
2176       /* Try "<prefix>foo.dll" (preferred dll name, if specified).  */
2177       { "%s%s.dll", true },
2178 #endif
2179       /* Try "libfoo.dll" (default preferred dll name).  */
2180       { "lib%s.dll", false },
2181       /* Finally try 'native' dll name "foo.dll".  */
2182       {  "%s.dll", false },
2183       /* Note: If adding more formats to this table, make sure to check to
2184          see if their length is longer than libname_fmt[0].format, and if
2185          so, update the call to xmalloc() below.  */
2186       { NULL, false }
2187     };
2188   static unsigned int format_max_len = 0;
2189   const char * filename;
2190   char * full_string;
2191   char * base_string;
2192   unsigned int i;
2195   if (! entry->flags.maybe_archive || entry->flags.full_name_provided)
2196     return false;
2198   filename = entry->filename;
2200   if (format_max_len == 0)
2201     /* We need to allow space in the memory that we are going to allocate
2202        for the characters in the format string.  Since the format array is
2203        static we only need to calculate this information once.  In theory
2204        this value could also be computed statically, but this introduces
2205        the possibility for a discrepancy and hence a possible memory
2206        corruption.  The lengths we compute here will be too long because
2207        they will include any formating characters (%s) in the strings, but
2208        this will not matter.  */
2209     for (i = 0; libname_fmt[i].format; i++)
2210       if (format_max_len < strlen (libname_fmt[i].format))
2211         format_max_len = strlen (libname_fmt[i].format);
2213   full_string = xmalloc (strlen (search->name)
2214                          + strlen (filename)
2215                          + format_max_len
2216 #ifdef DLL_SUPPORT
2217                          + (pep_dll_search_prefix
2218                             ? strlen (pep_dll_search_prefix) : 0)
2219 #endif
2220                          /* Allow for the terminating NUL and for the path
2221                             separator character that is inserted between
2222                             search->name and the start of the format string.  */
2223                          + 2);
2225   base_string = stpcpy (full_string, search->name);
2226   *base_string++ = '/';
2228   for (i = 0; libname_fmt[i].format; i++)
2229     {
2230 #ifdef DLL_SUPPORT
2231       if (libname_fmt[i].use_prefix)
2232         {
2233           if (!pep_dll_search_prefix)
2234             continue;
2235           sprintf (base_string, libname_fmt[i].format, pep_dll_search_prefix, filename);
2236         }
2237       else
2238 #endif
2239         sprintf (base_string, libname_fmt[i].format, filename);
2241       if (ldfile_try_open_bfd (full_string, entry))
2242         break;
2243     }
2245   if (!libname_fmt[i].format)
2246     {
2247       free (full_string);
2248       return false;
2249     }
2251   entry->filename = full_string;
2253   return true;
2256 static int
2257 gld${EMULATION_NAME}_find_potential_libraries
2258   (char *name, lang_input_statement_type *entry)
2260   return ldfile_open_file_search (name, entry, "", ".lib");
2263 static char *
2264 gld${EMULATION_NAME}_get_script (int *isfile)
2267 if test x"$COMPILE_IN" = xyes
2268 then
2269 # Scripts compiled in.
2271 # sed commands to quote an ld script as a C string.
2272 sc="-f ${srcdir}/emultempl/stringify.sed"
2274 fragment <<EOF
2276   *isfile = 0;
2278   if (bfd_link_relocatable (&link_info) && config.build_constructors)
2279     return
2281 sed $sc ldscripts/${EMULATION_NAME}.xu                  >> e${EMULATION_NAME}.c
2282 echo '  ; else if (bfd_link_relocatable (&link_info)) return' >> e${EMULATION_NAME}.c
2283 sed $sc ldscripts/${EMULATION_NAME}.xr                  >> e${EMULATION_NAME}.c
2284 echo '  ; else if (!config.text_read_only) return'      >> e${EMULATION_NAME}.c
2285 sed $sc ldscripts/${EMULATION_NAME}.xbn                 >> e${EMULATION_NAME}.c
2286 echo '  ; else if (!config.magic_demand_paged) return'  >> e${EMULATION_NAME}.c
2287 sed $sc ldscripts/${EMULATION_NAME}.xn                  >> e${EMULATION_NAME}.c
2288 if test -n "$GENERATE_AUTO_IMPORT_SCRIPT" ; then
2289 echo '  ; else if (link_info.pei386_auto_import == 1 && link_info.pei386_runtime_pseudo_reloc != 2) return'     >> e${EMULATION_NAME}.c
2290 sed $sc ldscripts/${EMULATION_NAME}.xa                  >> e${EMULATION_NAME}.c
2292 echo '  ; else return'                                  >> e${EMULATION_NAME}.c
2293 sed $sc ldscripts/${EMULATION_NAME}.x                   >> e${EMULATION_NAME}.c
2294 echo '; }'                                              >> e${EMULATION_NAME}.c
2296 else
2297 # Scripts read from the filesystem.
2299 fragment <<EOF
2301   *isfile = 1;
2303   if (bfd_link_relocatable (&link_info) && config.build_constructors)
2304     return "ldscripts/${EMULATION_NAME}.xu";
2305   else if (bfd_link_relocatable (&link_info))
2306     return "ldscripts/${EMULATION_NAME}.xr";
2307   else if (!config.text_read_only)
2308     return "ldscripts/${EMULATION_NAME}.xbn";
2309   else if (!config.magic_demand_paged)
2310     return "ldscripts/${EMULATION_NAME}.xn";
2312 if test -n "$GENERATE_AUTO_IMPORT_SCRIPT" ; then
2313 fragment <<EOF
2314   else if (link_info.pei386_auto_import == 1
2315            && link_info.pei386_runtime_pseudo_reloc != 2)
2316     return "ldscripts/${EMULATION_NAME}.xa";
2319 fragment <<EOF
2320   else
2321     return "ldscripts/${EMULATION_NAME}.x";
2326 LDEMUL_AFTER_PARSE=gld${EMULATION_NAME}_after_parse
2327 LDEMUL_BEFORE_PLUGIN_ALL_SYMBOLS_READ=gld${EMULATION_NAME}_before_plugin_all_symbols_read
2328 LDEMUL_AFTER_OPEN=gld${EMULATION_NAME}_after_open
2329 LDEMUL_BEFORE_ALLOCATION=gld${EMULATION_NAME}_before_allocation
2330 LDEMUL_FINISH=gld${EMULATION_NAME}_finish
2331 LDEMUL_OPEN_DYNAMIC_ARCHIVE=gld${EMULATION_NAME}_open_dynamic_archive
2332 LDEMUL_PLACE_ORPHAN=gld${EMULATION_NAME}_place_orphan
2333 LDEMUL_SET_SYMBOLS=gld${EMULATION_NAME}_set_symbols
2334 LDEMUL_ADD_OPTIONS=gld${EMULATION_NAME}_add_options
2335 LDEMUL_HANDLE_OPTION=gld${EMULATION_NAME}_handle_option
2336 LDEMUL_UNRECOGNIZED_FILE=gld${EMULATION_NAME}_unrecognized_file
2337 LDEMUL_LIST_OPTIONS=gld${EMULATION_NAME}_list_options
2338 LDEMUL_RECOGNIZED_FILE=gld${EMULATION_NAME}_recognized_file
2339 LDEMUL_FIND_POTENTIAL_LIBRARIES=gld${EMULATION_NAME}_find_potential_libraries
2341 source_em ${srcdir}/emultempl/emulation.em