# This shell script emits a C file. -*- C -*-
# It does some substitutions.
if [ -z "$MACHINE" ]; then
OUTPUT_ARCH=${ARCH}
else
OUTPUT_ARCH=${ARCH}:${MACHINE}
fi
case ${target} in
*-*-cygwin*)
move_default_addr_high=1
mingw_behavior=0
;;
*-*-mingw*)
move_default_addr_high=0
mingw_behavior=1
;;
*)
move_default_addr_high=0
mingw_behavior=0
;;
esac
rm -f e${EMULATION_NAME}.c
(echo;echo;echo;echo;echo)>e${EMULATION_NAME}.c # there, now line numbers match ;-)
fragment <<EOF
/* Copyright (C) 2006-2025 Free Software Foundation, Inc.
Written by Kai Tietz, OneVision Software GmbH&CoKg.
This file is part of the GNU Binutils.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
MA 02110-1301, USA. */
/* For WINDOWS_XP64 and higher */
/* Based on pe.em, but modified for 64 bit support. */
#define TARGET_IS_${EMULATION_NAME}
#define COFF_IMAGE_WITH_PE
#define COFF_WITH_PE
#ifdef TARGET_IS_aarch64pe
#define COFF_WITH_peAArch64
#elif defined TARGET_IS_arm64pe
#define COFF_WITH_peAArch64
#elif defined (TARGET_IS_i386pep)
#define COFF_WITH_pex64
#endif
/* FIXME: See bfd/peXXigen.c for why we include an architecture specific
header in generic PE code. */
#ifdef TARGET_IS_i386pep
# include "coff/x86_64.h"
#elif defined TARGET_IS_aarch64pe
# include "coff/aarch64.h"
#elif defined TARGET_IS_arm64pe
# include "coff/aarch64.h"
#endif
#include "coff/pe.h"
/* FIXME: These are BFD internal header files, and we should not be
using it here. */
#include "../bfd/libcoff.h"
#include "../bfd/libpei.h"
/* Permit the emulation parameters to override the default section
alignment by setting OVERRIDE_SECTION_ALIGNMENT. FIXME: This makes
it seem that include/coff/internal.h should not define
PE_DEF_SECTION_ALIGNMENT. */
#if PE_DEF_SECTION_ALIGNMENT != ${OVERRIDE_SECTION_ALIGNMENT:-PE_DEF_SECTION_ALIGNMENT}
#undef PE_DEF_SECTION_ALIGNMENT
#define PE_DEF_SECTION_ALIGNMENT ${OVERRIDE_SECTION_ALIGNMENT}
#endif
static int
is_underscoring (void)
{
int u = 0;
if (pep_leading_underscore != -1)
return pep_leading_underscore;
if (!bfd_get_target_info ("${OUTPUT_FORMAT}", NULL, NULL, &u, NULL))
bfd_get_target_info ("${RELOCATEABLE_OUTPUT_FORMAT}", NULL, NULL, &u, NULL);
if (u == -1)
abort ();
pep_leading_underscore = (u != 0 ? 1 : 0);
return pep_leading_underscore;
}
/* A case insensitive comparison, regardless of the host platform, used for
comparing file extensions. */
static int
fileext_cmp (const char *s1, const char *s2)
{
for (;;)
{
int c1 = TOLOWER (*s1++);
int c2 = *s2++; /* Assumed to be lower case from the caller. */
/* PE/WIN32; added routines to get the subsystem type, heap and/or stack
parameters which may be input from the command line. */
typedef struct
{
void *ptr;
int size;
bfd_vma value;
char *symbol;
int inited;
/* FALSE for an assembly level symbol and TRUE for a C visible symbol.
C visible symbols can be prefixed by underscore dependent on target's
settings. */
bool is_c_symbol;
} definfo;
static void
gld${EMULATION_NAME}_list_options (FILE *file)
{
fprintf (file, _(" --base_file <basefile> Generate a base file for relocatable DLLs\n"));
fprintf (file, _(" --dll Set image base to the default for DLLs\n"));
fprintf (file, _(" --file-alignment <size> Set file alignment\n"));
fprintf (file, _(" --heap <size> Set initial size of the heap\n"));
fprintf (file, _(" --image-base <address> Set start address of the executable\n"));
fprintf (file, _(" --major-image-version <number> Set version number of the executable\n"));
fprintf (file, _(" --major-os-version <number> Set minimum required OS version\n"));
fprintf (file, _(" --major-subsystem-version <number> Set minimum required OS subsystem version\n"));
fprintf (file, _(" --minor-image-version <number> Set revision number of the executable\n"));
fprintf (file, _(" --minor-os-version <number> Set minimum required OS revision\n"));
fprintf (file, _(" --minor-subsystem-version <number> Set minimum required OS subsystem revision\n"));
fprintf (file, _(" --section-alignment <size> Set section alignment\n"));
fprintf (file, _(" --stack <size> Set size of the initial stack\n"));
fprintf (file, _(" --subsystem <name>[:<version>] Set required OS subsystem [& version]\n"));
fprintf (file, _(" --support-old-code Support interworking with old code\n"));
fprintf (file, _(" --[no-]leading-underscore Set explicit symbol underscore prefix mode\n"));
fprintf (file, _(" --[no-]insert-timestamp Use a real timestamp rather than zero (default)\n"));
fprintf (file, _(" This makes binaries non-deterministic\n"));
#ifdef DLL_SUPPORT
fprintf (file, _(" --add-stdcall-alias Export symbols with and without @nn\n"));
fprintf (file, _(" --disable-stdcall-fixup Don't link _sym to _sym@nn\n"));
fprintf (file, _(" --enable-stdcall-fixup Link _sym to _sym@nn without warnings\n"));
fprintf (file, _(" --exclude-symbols sym,sym,... Exclude symbols from automatic export\n"));
fprintf (file, _(" --exclude-all-symbols Exclude all symbols from automatic export\n"));
fprintf (file, _(" --exclude-libs lib,lib,... Exclude libraries from automatic export\n"));
fprintf (file, _(" --exclude-modules-for-implib mod,mod,...\n"));
fprintf (file, _(" Exclude objects, archive members from auto\n"));
fprintf (file, _(" export, place into import library instead\n"));
fprintf (file, _(" --export-all-symbols Automatically export all globals to DLL\n"));
fprintf (file, _(" --kill-at Remove @nn from exported symbols\n"));
fprintf (file, _(" --output-def <file> Generate a .DEF file for the built DLL\n"));
fprintf (file, _(" --warn-duplicate-exports Warn about duplicate exports\n"));
fprintf (file, _(" --compat-implib Create backward compatible import libs;\n\
create __imp_<SYMBOL> as well\n"));
fprintf (file, _(" --enable-auto-image-base Automatically choose image base for DLLs\n\
unless user specifies one\n"));
fprintf (file, _(" --disable-auto-image-base Do not auto-choose image base (default)\n"));
fprintf (file, _(" --dll-search-prefix=<string> When linking dynamically to a dll without\n\
an importlib, use <string><basename>.dll\n\
in preference to lib<basename>.dll \n"));
fprintf (file, _(" --enable-auto-import Do sophisticated linking of _sym to\n\
__imp_sym for DATA references\n"));
fprintf (file, _(" --disable-auto-import Do not auto-import DATA items from DLLs\n"));
fprintf (file, _(" --enable-runtime-pseudo-reloc Work around auto-import limitations by\n\
adding pseudo-relocations resolved at\n\
runtime\n"));
fprintf (file, _(" --disable-runtime-pseudo-reloc Do not add runtime pseudo-relocations for\n\
auto-imported DATA\n"));
fprintf (file, _(" --enable-extra-pep-debug Enable verbose debug output when building\n\
or linking to DLLs (esp. auto-import)\n"));
fprintf (file, _(" --enable-long-section-names Use long COFF section names even in\n\
executable image files\n"));
fprintf (file, _(" --disable-long-section-names Never use long COFF section names, even\n\
in object files\n"));
fprintf (file, _(" --[disable-]high-entropy-va Image is compatible with 64-bit address space\n\
layout randomization (ASLR)\n"));
fprintf (file, _(" --[disable-]dynamicbase Image base address may be relocated using\n\
address space layout randomization (ASLR)\n"));
fprintf (file, _(" --enable-reloc-section Create the base relocation table\n"));
fprintf (file, _(" --disable-reloc-section Do not create the base relocation table\n"));
fprintf (file, _(" --[disable-]forceinteg Code integrity checks are enforced\n"));
fprintf (file, _(" --[disable-]nxcompat Image is compatible with data execution\n\
prevention\n"));
fprintf (file, _(" --[disable-]no-isolation Image understands isolation but do not\n\
isolate the image\n"));
fprintf (file, _(" --[disable-]no-seh Image does not use SEH; no SE handler may\n\
be called in this image\n"));
fprintf (file, _(" --[disable-]no-bind Do not bind this image\n"));
fprintf (file, _(" --[disable-]wdmdriver Driver uses the WDM model\n"));
fprintf (file, _(" --[disable-]tsaware Image is Terminal Server aware\n"));
fprintf (file, _(" --build-id[=STYLE] Generate build ID\n"));
#ifdef PDB_H
fprintf (file, _(" --pdb=[FILENAME] Generate PDB file\n"));
#endif
#endif
}
static void
set_pep_name (char *name, bfd_vma val)
{
int i;
is_underscoring ();
/* Find the name and set it. */
for (i = 0; init[i].ptr; i++)
{
if (strcmp (name, GET_INIT_SYMBOL_NAME (i)) == 0)
{
init[i].value = val;
init[i].inited = 1;
if (strcmp (name,"__image_base__") == 0)
set_pep_name (U ("__ImageBase"), val);
return;
}
}
abort ();
}
/* Check for the presence of a version number. */
sver = strchr (optarg, ':');
if (sver == NULL)
len = strlen (optarg);
else
{
len = sver - optarg;
set_pep_name ("__major_subsystem_version__",
strtoul (sver + 1, &end, 0));
if (*end == '.')
set_pep_name ("__minor_subsystem_version__",
strtoul (end + 1, &end, 0));
if (*end != '\0')
einfo (_("%P: warning: bad version number in -subsystem option\n"));
}
/* Check for numeric subsystem. */
temp_subsystem = strtoul (optarg, & end, 0);
if ((*end == ':' || *end == '\0') && (temp_subsystem < 65536))
{
/* Search list for a numeric match to use its entry point. */
for (i = 0; v[i].name; i++)
if (v[i].value == (int) temp_subsystem)
break;
/* Use this subsystem. */
pep_subsystem = (int) temp_subsystem;
}
else
{
/* Search for subsystem by name. */
for (i = 0; v[i].name; i++)
if (strncmp (optarg, v[i].name, len) == 0
&& v[i].name[len] == '\0')
break;
if (v[i].name == NULL)
{
fatal (_("%P: invalid subsystem type %s\n"), optarg);
return;
}
case OPTION_BASE_FILE:
link_info.base_file = fopen (optarg, FOPEN_WB);
if (link_info.base_file == NULL)
fatal (_("%P: cannot open base file %s\n"), optarg);
break;
/* PE options. */
case OPTION_HEAP:
set_pep_stack_heap ("__size_of_heap_reserve__", "__size_of_heap_commit__");
break;
case OPTION_STACK:
set_pep_stack_heap ("__size_of_stack_reserve__", "__size_of_stack_commit__");
break;
case OPTION_SUBSYSTEM:
set_pep_subsystem ();
break;
case OPTION_MAJOR_OS_VERSION:
set_pep_value ("__major_os_version__");
break;
case OPTION_MINOR_OS_VERSION:
set_pep_value ("__minor_os_version__");
break;
case OPTION_MAJOR_SUBSYSTEM_VERSION:
set_pep_value ("__major_subsystem_version__");
break;
case OPTION_MINOR_SUBSYSTEM_VERSION:
set_pep_value ("__minor_subsystem_version__");
break;
case OPTION_MAJOR_IMAGE_VERSION:
set_pep_value ("__major_image_version__");
break;
case OPTION_MINOR_IMAGE_VERSION:
set_pep_value ("__minor_image_version__");
break;
case OPTION_FILE_ALIGNMENT:
set_pep_value ("__file_alignment__");
break;
case OPTION_SECTION_ALIGNMENT:
set_pep_value ("__section_alignment__");
break;
case OPTION_DLL:
set_pep_name ("__dll__", 1);
break;
case OPTION_IMAGE_BASE:
set_pep_value ("__image_base__");
break;
case OPTION_SUPPORT_OLD_CODE:
support_old_code = 1;
break;
case OPTION_USE_NUL_PREFIXED_IMPORT_TABLES:
pep_use_nul_prefixed_import_tables = true;
break;
case OPTION_NO_LEADING_UNDERSCORE:
pep_leading_underscore = 0;
break;
case OPTION_LEADING_UNDERSCORE:
pep_leading_underscore = 1;
break;
case OPTION_INSERT_TIMESTAMP:
insert_timestamp = true;
break;
case OPTION_NO_INSERT_TIMESTAMP:
insert_timestamp = false;
break;
#ifdef DLL_SUPPORT
case OPTION_OUT_DEF:
pep_out_def_filename = xstrdup (optarg);
break;
case OPTION_EXPORT_ALL:
pep_dll_export_everything = 1;
break;
case OPTION_EXCLUDE_SYMBOLS:
pep_dll_add_excludes (optarg, EXCLUDESYMS);
break;
case OPTION_EXCLUDE_ALL_SYMBOLS:
pep_dll_exclude_all_symbols = 1;
break;
case OPTION_EXCLUDE_LIBS:
pep_dll_add_excludes (optarg, EXCLUDELIBS);
break;
case OPTION_EXCLUDE_MODULES_FOR_IMPLIB:
pep_dll_add_excludes (optarg, EXCLUDEFORIMPLIB);
break;
case OPTION_KILL_ATS:
pep_dll_kill_ats = 1;
break;
case OPTION_STDCALL_ALIASES:
pep_dll_stdcall_aliases = 1;
break;
case OPTION_ENABLE_STDCALL_FIXUP:
pep_enable_stdcall_fixup = 1;
break;
case OPTION_DISABLE_STDCALL_FIXUP:
pep_enable_stdcall_fixup = 0;
break;
case OPTION_WARN_DUPLICATE_EXPORTS:
pep_dll_warn_dup_exports = 1;
break;
case OPTION_IMP_COMPAT:
pep_dll_compat_implib = 1;
break;
case OPTION_ENABLE_AUTO_IMAGE_BASE:
pep_enable_auto_image_base = 1;
break;
case OPTION_DISABLE_AUTO_IMAGE_BASE:
pep_enable_auto_image_base = 0;
break;
case OPTION_DLL_SEARCH_PREFIX:
pep_dll_search_prefix = xstrdup (optarg);
break;
case OPTION_NO_DEFAULT_EXCLUDES:
pep_dll_do_default_excludes = 0;
break;
case OPTION_DLL_ENABLE_AUTO_IMPORT:
link_info.pei386_auto_import = 1;
break;
case OPTION_DLL_DISABLE_AUTO_IMPORT:
link_info.pei386_auto_import = 0;
break;
case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC:
link_info.pei386_runtime_pseudo_reloc = 2;
break;
case OPTION_DLL_DISABLE_RUNTIME_PSEUDO_RELOC:
link_info.pei386_runtime_pseudo_reloc = 0;
break;
case OPTION_DLL_ENABLE_RUNTIME_PSEUDO_RELOC_V2:
link_info.pei386_runtime_pseudo_reloc = 2;
break;
case OPTION_ENABLE_EXTRA_PE_DEBUG:
pep_dll_extra_pe_debug = 1;
break;
#endif
case OPTION_ENABLE_LONG_SECTION_NAMES:
pep_use_coff_long_section_names = 1;
break;
case OPTION_DISABLE_LONG_SECTION_NAMES:
pep_use_coff_long_section_names = 0;
break;
/* Get DLLCharacteristics bits */
case OPTION_HIGH_ENTROPY_VA:
pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
/* fall through */
case OPTION_DYNAMIC_BASE:
pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
/* fall through */
case OPTION_ENABLE_RELOC_SECTION:
pep_dll_enable_reloc_section = 1;
break;
case OPTION_DISABLE_RELOC_SECTION:
pep_dll_enable_reloc_section = 0;
/* fall through */
case OPTION_DISABLE_DYNAMIC_BASE:
pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE;
/* fall through */
case OPTION_DISABLE_HIGH_ENTROPY_VA:
pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA;
break;
case OPTION_FORCE_INTEGRITY:
pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
break;
case OPTION_DISABLE_FORCE_INTEGRITY:
pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY;
break;
case OPTION_NX_COMPAT:
pe_dll_characteristics |= IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
break;
case OPTION_DISABLE_NX_COMPAT:
pe_dll_characteristics &= ~ IMAGE_DLL_CHARACTERISTICS_NX_COMPAT;
break;
case OPTION_NO_ISOLATION:
pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_ISOLATION;
break;
case OPTION_DISABLE_NO_ISOLATION:
pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_ISOLATION;
break;
case OPTION_NO_SEH:
pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_SEH;
break;
case OPTION_DISABLE_NO_SEH:
pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_SEH;
break;
case OPTION_NO_BIND:
pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_NO_BIND;
break;
case OPTION_DISABLE_NO_BIND:
pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_NO_BIND;
break;
case OPTION_WDM_DRIVER:
pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_WDM_DRIVER;
break;
case OPTION_DISABLE_WDM_DRIVER:
pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_WDM_DRIVER;
break;
case OPTION_TERMINAL_SERVER_AWARE:
pe_dll_characteristics |= IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
break;
case OPTION_DISABLE_TERMINAL_SERVER_AWARE:
pe_dll_characteristics &= ~ IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE;
break;
case OPTION_BUILD_ID:
free ((char *) emit_build_id);
emit_build_id = NULL;
if (optarg == NULL)
optarg = DEFAULT_BUILD_ID_STYLE;
if (strcmp (optarg, "none"))
emit_build_id = xstrdup (optarg);
break;
#ifdef PDB_H
case OPTION_PDB:
pdb = 1;
if (optarg && optarg[0])
pdb_name = xstrdup (optarg);
break;
#endif
}
/* Set DLLCharacteristics bits */
set_pep_name ("__dll_characteristics__", pe_dll_characteristics);
return true;
}
#ifdef DLL_SUPPORT
static unsigned long
strhash (const char *str)
{
const unsigned char *s;
unsigned long hash;
unsigned int c;
unsigned int len;
hash = 0;
len = 0;
s = (const unsigned char *) str;
while ((c = *s++) != '\0')
{
hash += c + (c << 17);
hash ^= hash >> 2;
++len;
}
hash += len + (len << 17);
hash ^= hash >> 2;
return hash;
}
/* Use the output file to create a image base for relocatable DLLs. */
/* This is called after the linker script and the command line options
have been read. */
static void
gld${EMULATION_NAME}_after_parse (void)
{
/* PR ld/6744: Warn the user if they have used an ELF-only
option hoping it will work on PE+. */
if (link_info.export_dynamic)
einfo (_("%P: warning: --export-dynamic is not supported for PE+ "
"targets, did you mean --export-all-symbols?\n"));
if (pep_dll_extra_pe_debug)
printf ("%s\n", __func__);
for (undef = link_info.hash->undefs; undef; undef=undef->u.undef.next)
if (undef->type == bfd_link_hash_undefined)
{
char* at = strchr (undef->root.string, '@');
int lead_at = (*undef->root.string == '@');
if (lead_at)
at = strchr (undef->root.string + 1, '@');
if (at || lead_at)
{
/* The symbol is a stdcall symbol, so let's look for a
cdecl symbol with the same name and resolve to that. */
char *cname = xstrdup (undef->root.string);
if (lead_at)
*cname = '_';
at = strchr (cname, '@');
if (at)
*at = 0;
sym = bfd_link_hash_lookup (link_info.hash, cname, 0, 0, 1);
if (pep_enable_stdcall_fixup == -1)
{
einfo (_("warning: resolving %s by linking to %s\n"),
undef->root.string, cname);
if (! gave_warning_message)
{
gave_warning_message = 1;
einfo (_("Use --enable-stdcall-fixup to disable these warnings\n"));
einfo (_("Use --disable-stdcall-fixup to disable these fixups\n"));
}
}
}
}
else
{
/* The symbol is a cdecl symbol, so we look for stdcall
symbols - which means scanning the whole symbol table. */
pep_undef_found_sym = 0;
bfd_link_hash_traverse (link_info.hash, pep_undef_cdecl_match,
(char *) undef->root.string);
sym = pep_undef_found_sym;
if (sym)
{
undef->type = bfd_link_hash_defined;
undef->u.def.value = sym->u.def.value;
undef->u.def.section = sym->u.def.section;
set_decoration (undef->root.string, sym);
if (pep_enable_stdcall_fixup == -1)
{
einfo (_("warning: resolving %s by linking to %s\n"),
undef->root.string, sym->root.string);
if (! gave_warning_message)
{
gave_warning_message = 1;
einfo (_("Use --enable-stdcall-fixup to disable these warnings\n"));
einfo (_("Use --disable-stdcall-fixup to disable these fixups\n"));
}
}
}
}
}
}
/* Zero pad or truncate the generated build_id to fit in the
CodeView record. */
memset (&(cvinfo.Signature), 0, CV_INFO_SIGNATURE_LENGTH);
memcpy (&(cvinfo.Signature), build_id,
(build_id_size > CV_INFO_SIGNATURE_LENGTH
? CV_INFO_SIGNATURE_LENGTH : build_id_size));
free (build_id);
/* Write the codeview record. */
if (_bfd_XXi_write_codeview_record (abfd, idd.PointerToRawData, &cvinfo,
pdb_base_name) == 0)
return 0;
/* Record the location of the debug directory in the data directory. */
td->pe_opthdr.DataDirectory[PE_DEBUG_DATA].VirtualAddress
= asec->vma - ib + link_order->offset;
td->pe_opthdr.DataDirectory[PE_DEBUG_DATA].Size
= sizeof (struct external_IMAGE_DEBUG_DIRECTORY);
return true;
}
/* Make .buildid section, and set up coff_tdata->build_id. */
static bool
setup_build_id (bfd *ibfd)
{
asection *s;
flagword flags;
/* Section is a fixed size:
One IMAGE_DEBUG_DIRECTORY entry, of type IMAGE_DEBUG_TYPE_CODEVIEW,
pointing at a CV_INFO_PDB70 record containing the build-id, followed by
PdbFileName if relevant. */
s->size = (sizeof (struct external_IMAGE_DEBUG_DIRECTORY)
+ sizeof (CV_INFO_PDB70) + 1);
/* Find a COFF input. */
for (abfd = link_info.input_bfds;
abfd != (bfd *) NULL; abfd = abfd->link.next)
if (bfd_get_flavour (abfd) == bfd_target_coff_flavour)
break;
/* If there are no COFF input files do not try to
add a build-id section. */
if (abfd == NULL
|| !setup_build_id (abfd))
{
free ((char *) emit_build_id);
emit_build_id = NULL;
}
}
/* Pass the wacky PE command line options into the output bfd.
FIXME: This should be done via a function, rather than by
including an internal BFD header. */
if (bfd_get_flavour (link_info.output_bfd) != bfd_target_coff_flavour
|| coff_data (link_info.output_bfd) == NULL
|| !obj_pe (link_info.output_bfd))
fatal (_("%P: cannot perform PE operations on non PE output file '%pB'\n"),
link_info.output_bfd);
/* At this point we must decide whether to use long section names
in the output or not. If the user hasn't explicitly specified
on the command line, we leave it to the default for the format
(object files yes, image files no), except if there is debug
information present; GDB relies on the long section names to
find it, so enable it in that case. */
if (pep_use_coff_long_section_names < 0 && link_info.strip == strip_none)
{
if (bfd_link_relocatable (&link_info))
pep_use_coff_long_section_names = 1;
else
{
/* Iterate over all sections of all input BFDs, checking
for any that begin 'debug_' and are long names. */
LANG_FOR_EACH_INPUT_STATEMENT (is)
{
int found_debug = 0;
if (link_info.pei386_auto_import) /* -1=warn or 1=enable */
pep_find_data_imports (U ("_head_"), make_import_fixup);
/* The implementation of the feature is rather dumb and would cause the
compilation time to go through the roof if there are many undefined
symbols in the link, so it needs to be run after auto-import. */
if (pep_enable_stdcall_fixup) /* -1=warn or 1=enable */
pep_fixup_stdcalls ();
#if !defined(TARGET_IS_i386pep) && !defined(COFF_WITH_peAArch64)
if (bfd_link_pic (&link_info))
#else
if (!bfd_link_relocatable (&link_info))
#endif
pep_dll_build_sections (link_info.output_bfd, &link_info);
{
/* This next chunk of code tries to detect the case where you have
two import libraries for the same DLL (specifically,
symbolically linking libm.a and libc.a in cygwin to
libcygwin.a). In those cases, it's possible for function
thunks from the second implib to be used but without the
head/tail objects, causing an improper import table. We detect
those cases and rename the "other" import libraries to match
the one the head/tail come from, so that the linker will sort
things nicely and produce a valid import table. */
LANG_FOR_EACH_INPUT_STATEMENT (is)
{
if (is->the_bfd->my_archive)
{
int idata2 = 0, reloc_count=0, is_imp = 0;
asection *sec;
/* See if this is an import library thunk. */
for (sec = is->the_bfd->sections; sec; sec = sec->next)
{
if (strcmp (sec->name, ".idata\$2") == 0)
idata2 = 1;
if (startswith (sec->name, ".idata\$"))
is_imp = 1;
reloc_count += sec->reloc_count;
}
if (is_imp && !idata2 && reloc_count)
{
/* It is, look for the reference to head and see if it's
from our own library. */
for (sec = is->the_bfd->sections; sec; sec = sec->next)
{
int i;
long relsize;
asymbol **symbols;
arelent **relocs;
int nrelocs;
relsize = bfd_get_reloc_upper_bound (is->the_bfd, sec);
if (relsize < 1)
break;
if (!bfd_generic_link_read_symbols (is->the_bfd))
{
fatal (_("%P: %pB: could not read symbols: %E\n"),
is->the_bfd);
return;
}
symbols = bfd_get_outsymbols (is->the_bfd);
relocs = xmalloc ((size_t) relsize);
nrelocs = bfd_canonicalize_reloc (is->the_bfd, sec,
relocs, symbols);
if (nrelocs < 0)
{
free (relocs);
einfo (_("%X%P: unable to process relocs: %E\n"));
return;
}
for (i = 0; i < nrelocs; i++)
{
struct bfd_symbol *s;
struct bfd_link_hash_entry * blhe;
bfd *other_bfd;
const char *other_bfd_filename;
s = (relocs[i]->sym_ptr_ptr)[0];
if (s->flags & BSF_LOCAL)
continue;
/* Thunk section with reloc to another bfd. */
blhe = bfd_link_hash_lookup (link_info.hash,
s->name,
false, false, true);
if (blhe == NULL
|| blhe->type != bfd_link_hash_defined)
continue;
other_bfd = blhe->u.def.section->owner;
if (other_bfd->my_archive == is->the_bfd->my_archive)
continue;
if (filename_cmp (bfd_get_filename
(is->the_bfd->my_archive),
other_bfd_filename) == 0)
continue;
/* Sort this implib to match the other one. */
lang_input_statement_type *arch_is
= bfd_usrdata (is->the_bfd->my_archive);
arch_is->sort_key = other_bfd_filename;
break;
}
free (relocs);
/* Note - we do not free the symbols,
they are now cached in the BFD. */
}
}
}
}
}
{
/* Careful - this is a shell script. Watch those dollar signs! */
/* Microsoft import libraries have every member named the same,
and not in the right order for us to link them correctly. We
must detect these and rename the members so that they'll link
correctly. There are three types of objects: the head, the
thunks, and the sentinel(s). The head is easy; it's the one
with idata2. We assume that the sentinels won't have relocs,
and the thunks will. It's easier than checking the symbol
table for external references. */
LANG_FOR_EACH_INPUT_STATEMENT (is)
{
if (is->the_bfd->my_archive)
{
char *pnt;
/* Microsoft import libraries may contain archive members for
one or more DLLs, together with static object files.
The head and sentinels are regular COFF object files,
while the thunks are special ILF files that get synthesized
by bfd into COFF object files.
As Microsoft import libraries can be for a module with
almost any file name (*.dll, *.exe, etc), we can't easily
know which archive members to inspect.
Inspect all members, except ones named *.o or *.obj (which
is the case both for regular static libraries or for GNU
style import libraries). Archive members with file names other
than *.o or *.obj, that do contain .idata sections, are
considered to be Microsoft style import objects, and are
renamed accordingly.
If this heuristic is wrong and we apply this on archive members
that already have unique names, it shouldn't make any difference
as we only append a suffix on the names. */
pnt = strrchr (bfd_get_filename (is->the_bfd), '.');
/* An archive member not named .o or .obj, but not having any
.idata sections - apparently not a Microsoft import object
after all: Skip renaming it. */
if (!idata)
continue;
if (idata2) /* .idata2 is the TOC */
seq = 'a';
else if (reloc_count > 0) /* thunks */
seq = 'b';
else /* sentinel */
seq = 'c';
/* Look through the script to see where to place this section. */
if (!bfd_link_relocatable (&link_info)
&& (dollar = strchr (secname, '\$')) != NULL)
{
size_t len = dollar - secname;
char *newname = xmalloc (len + 1);
memcpy (newname, secname, len);
newname[len] = '\0';
secname = newname;
}
lang_list_init (&add_child);
os = NULL;
if (constraint == 0)
for (os = lang_output_section_find (secname);
os != NULL;
os = next_matching_output_section_statement (os, 0))
{
/* If we don't match an existing output section, tell
lang_insert_orphan to create a new output section. */
constraint = SPECIAL;
if (os->bfd_section != NULL
&& (os->bfd_section->flags == 0
|| ((s->flags ^ os->bfd_section->flags)
& (SEC_LOAD | SEC_ALLOC)) == 0))
{
/* We already have an output section statement with this
name, and its bfd section has compatible flags.
If the section already exists but does not have any flags set,
then it has been created by the linker, probably as a result of
a --section-start command line switch. */
lang_add_section (&add_child, s, NULL, NULL, os);
break;
}
/* Save unused output sections in case we can match them
against orphans later. */
if (os->bfd_section == NULL)
match_by_name = os;
}
/* If we didn't match an active output section, see if we matched an
unused one and use that. */
if (os == NULL && match_by_name)
{
lang_add_section (&match_by_name->children, s, NULL, NULL, match_by_name);
return match_by_name;
}
/* Try to put the new output section in a reasonable place based
on the section name and section flags. */
place = NULL;
if ((flags & SEC_ALLOC) == 0)
;
else if ((flags & (SEC_LOAD | SEC_HAS_CONTENTS)) == 0)
place = &hold[orphan_bss];
else if ((flags & SEC_READONLY) == 0)
place = &hold[orphan_data];
else if ((flags & SEC_CODE) == 0)
{
place = (!strncmp (secname, ".idata\$", 7) ? &hold[orphan_idata]
: &hold[orphan_rodata]);
}
else
place = &hold[orphan_text];
after = NULL;
if (place != NULL)
{
if (place->os == NULL)
place->os = lang_output_section_find (place->name);
after = place->os;
if (after == NULL)
after = lang_output_section_find_by_flags (s, flags, &place->os,
NULL);
if (after == NULL)
/* *ABS* is always the first output section statement. */
after = (void *) lang_os_list.head;
}
/* All sections in an executable must be aligned to a page boundary.
In a relocatable link, just preserve the incoming alignment; the
address is discarded by lang_insert_orphan in that case, anyway. */
address = exp_unop (ALIGN_K, exp_nameop (NAME, "__section_alignment__"));
os = lang_insert_orphan (s, secname, constraint, after, place, address,
&add_child);
if (bfd_link_relocatable (&link_info))
{
os->section_alignment = exp_intop (1U << s->alignment_power);
os->bfd_section->alignment_power = s->alignment_power;
}
}
/* If the section name has a '\$', sort it with the other '\$'
sections. */
for (pl = &os->children.head; *pl != NULL; pl = &(*pl)->header.next)
{
lang_input_section_type *ls;
const char *lname;
if ((*pl)->header.type != lang_input_section_enum)
continue;
static bool
gld${EMULATION_NAME}_open_dynamic_archive
(const char *arch ATTRIBUTE_UNUSED,
search_dirs_type *search,
lang_input_statement_type *entry)
{
static const struct
{
const char * format;
bool use_prefix;
}
libname_fmt [] =
{
/* Preferred explicit import library for dll's. */
{ "lib%s.dll.a", false },
/* Alternate explicit import library for dll's. */
{ "%s.dll.a", false },
/* "libfoo.a" could be either an import lib or a static lib.
For backwards compatibility, libfoo.a needs to precede
libfoo.dll and foo.dll in the search. */
{ "lib%s.a", false },
/* The 'native' spelling of an import lib name is "foo.lib". */
{ "%s.lib", false },
/* PR 22948 - Check for an import library. */
{ "lib%s.lib", false },
#ifdef DLL_SUPPORT
/* Try "<prefix>foo.dll" (preferred dll name, if specified). */
{ "%s%s.dll", true },
#endif
/* Try "libfoo.dll" (default preferred dll name). */
{ "lib%s.dll", false },
/* Finally try 'native' dll name "foo.dll". */
{ "%s.dll", false },
/* Note: If adding more formats to this table, make sure to check to
see if their length is longer than libname_fmt[0].format, and if
so, update the call to xmalloc() below. */
{ NULL, false }
};
static unsigned int format_max_len = 0;
const char * filename;
char * full_string;
char * base_string;
unsigned int i;
if (! entry->flags.maybe_archive || entry->flags.full_name_provided)
return false;
filename = entry->filename;
if (format_max_len == 0)
/* We need to allow space in the memory that we are going to allocate
for the characters in the format string. Since the format array is
static we only need to calculate this information once. In theory
this value could also be computed statically, but this introduces
the possibility for a discrepancy and hence a possible memory
corruption. The lengths we compute here will be too long because
they will include any formating characters (%s) in the strings, but
this will not matter. */
for (i = 0; libname_fmt[i].format; i++)
if (format_max_len < strlen (libname_fmt[i].format))
format_max_len = strlen (libname_fmt[i].format);
full_string = xmalloc (strlen (search->name)
+ strlen (filename)
+ format_max_len
#ifdef DLL_SUPPORT
+ (pep_dll_search_prefix
? strlen (pep_dll_search_prefix) : 0)
#endif
/* Allow for the terminating NUL and for the path
separator character that is inserted between
search->name and the start of the format string. */
+ 2);
if test x"$COMPILE_IN" = xyes
then
# Scripts compiled in.
# sed commands to quote an ld script as a C string.
sc="-f ${srcdir}/emultempl/stringify.sed"
fragment <<EOF
{
*isfile = 0;
if (bfd_link_relocatable (&link_info) && config.build_constructors)
return
EOF
sed $sc ldscripts/${EMULATION_NAME}.xu >> e${EMULATION_NAME}.c
echo ' ; else if (bfd_link_relocatable (&link_info)) return' >> e${EMULATION_NAME}.c
sed $sc ldscripts/${EMULATION_NAME}.xr >> e${EMULATION_NAME}.c
echo ' ; else if (!config.text_read_only) return' >> e${EMULATION_NAME}.c
sed $sc ldscripts/${EMULATION_NAME}.xbn >> e${EMULATION_NAME}.c
echo ' ; else if (!config.magic_demand_paged) return' >> e${EMULATION_NAME}.c
sed $sc ldscripts/${EMULATION_NAME}.xn >> e${EMULATION_NAME}.c
if test -n "$GENERATE_AUTO_IMPORT_SCRIPT" ; then
echo ' ; else if (link_info.pei386_auto_import == 1 && link_info.pei386_runtime_pseudo_reloc != 2) return' >> e${EMULATION_NAME}.c
sed $sc ldscripts/${EMULATION_NAME}.xa >> e${EMULATION_NAME}.c
fi
echo ' ; else return' >> e${EMULATION_NAME}.c
sed $sc ldscripts/${EMULATION_NAME}.x >> e${EMULATION_NAME}.c
echo '; }' >> e${EMULATION_NAME}.c
else
# Scripts read from the filesystem.
fragment <<EOF
{
*isfile = 1;
if (bfd_link_relocatable (&link_info) && config.build_constructors)
return "ldscripts/${EMULATION_NAME}.xu";
else if (bfd_link_relocatable (&link_info))
return "ldscripts/${EMULATION_NAME}.xr";
else if (!config.text_read_only)
return "ldscripts/${EMULATION_NAME}.xbn";
else if (!config.magic_demand_paged)
return "ldscripts/${EMULATION_NAME}.xn";
EOF
if test -n "$GENERATE_AUTO_IMPORT_SCRIPT" ; then
fragment <<EOF
else if (link_info.pei386_auto_import == 1
&& link_info.pei386_runtime_pseudo_reloc != 2)
return "ldscripts/${EMULATION_NAME}.xa";
EOF
fi
fragment <<EOF
else
return "ldscripts/${EMULATION_NAME}.x";
}
EOF
fi