[PATCH 1/3] bfd: Add a PE short import library writer [PR34527]

Zhongteng Gui dragon-archer@outlook.com
Wed Nov 25 10:26:38 GMT 2026


GNU ld can link with short import libraries, as written by MSVC lib and
llvm-dlltool, but the GNU tools cannot create them.  Add a function that
fills an archive with one short import member per export, so that ld and
dlltool can share it.

The members stay in short form on disk.  Each gets an in-memory symbol
table so that the existing archive map code indexes __imp_<symbol> and,
for code, <symbol>.  A head object provides the import descriptor named
by the short members, and a tail object provides the DLL name, the null
thunks and the null import descriptor.  The members are sorted by symbol
and given fixed names, so the same exports always give the same archive.

Only i386 and x86-64 are supported for now.  The machine is taken from a
bfd_arch_info_type, so it should be relatively easy to add aarch64 in
the future.

	PR binutils/34527

bfd/
	* coff-bfd.h (struct bfd_pe_short_export): New.
	(bfd_pe_write_short_import_library): Declare.
	* coff-bfd.c: Include coff/external.h and coff/pe.h.
	(struct pe_import_directory): New.
	(pe_short_import_member): New function.
	(pe_import_object): Likewise.
	(pe_short_export_cmp): Likewise.
	(bfd_pe_write_short_import_library): Likewise.

Signed-off-by: Zhongteng Gui <dragon-archer@outlook.com>
---
 bfd/coff-bfd.c | 273 +++++++++++++++++++++++++++++++++++++++++++++++++
 bfd/coff-bfd.h |  13 +++
 2 files changed, 286 insertions(+)

diff --git a/bfd/coff-bfd.c b/bfd/coff-bfd.c
index e57135ddd18..d060d722f6a 100644
--- a/bfd/coff-bfd.c
+++ b/bfd/coff-bfd.c
@@ -23,6 +23,9 @@
 #include "bfd.h"
 #include "libbfd.h"
 #include "coff/internal.h"
+#define L_LNNO_SIZE 2
+#include "coff/external.h"
+#include "coff/pe.h"
 #include "libcoff.h"
 
 /* Return the COFF syment for a symbol.  */
@@ -157,3 +160,273 @@ bfd_coff_pe_weak_external_has_real_fallback (bfd *abfd,
 	  && !(fallback->u.syment.n_scnum == N_ABS
 	       && fallback->u.syment.n_value == 0));
 }
+
+/* IMAGE_IMPORT_DESCRIPTOR, as placed in .idata$2.  */
+
+struct pe_import_directory
+{
+  bfd_byte lookup_table[4];
+  bfd_byte timestamp[4];
+  bfd_byte forwarder_chain[4];
+  bfd_byte name[4];
+  bfd_byte address_table[4];
+};
+
+/* Return a short import member for EXP.  Only the archive map reads the
+   symbols cached here; the member itself is written in short form.  */
+
+static bfd *
+pe_short_import_member (bfd *archive, const char *member,
+			unsigned int machine, const char *dll,
+			const struct bfd_pe_short_export *exp)
+{
+  const char *symbol = exp->symbol;
+  const char *name = exp->name;
+  unsigned int name_type = IMPORT_ORDINAL;
+
+  if (name != NULL)
+    {
+      /* Strip the prefix as pe_ILF_build_a_bfd does.  */
+      const char *p = symbol;
+      if ((*p == '_' && bfd_get_symbol_leading_char (archive) != 0)
+	  || *p == '@' || *p == '?')
+	p++;
+      size_t len = strcspn (p, "@");
+
+      if (strcmp (symbol, name) == 0)
+	name_type = IMPORT_NAME;
+      else if (strcmp (p, name) == 0)
+	name_type = IMPORT_NAME_NOPREFIX;
+      else if (strncmp (p, name, len) == 0 && name[len] == '\0')
+	name_type = IMPORT_NAME_UNDECORATE;
+      else
+	name_type = IMPORT_NAME_EXPORTAS;
+    }
+
+  size_t symbol_size = strlen (symbol) + 1;
+  size_t dll_size = strlen (dll) + 1;
+  size_t name_size = (name_type == IMPORT_NAME_EXPORTAS
+		      ? strlen (name) + 1 : 0);
+  struct
+  {
+    bfd_byte sig1[2], sig2[2], version[2], machine[2];
+    bfd_byte timestamp[4], size_of_data[4];
+    bfd_byte ordinal_or_hint[2], type[2];
+  } header = { 0 };
+
+  bfd_putl16 (0xffff, header.sig2);
+  bfd_putl16 (machine, header.machine);
+  bfd_putl32 (symbol_size + dll_size + name_size, header.size_of_data);
+  bfd_putl16 (exp->hint, header.ordinal_or_hint);
+  bfd_putl16 ((name_type << 2) | (exp->data ? IMPORT_DATA : IMPORT_CODE),
+	      header.type);
+
+  bfd *abfd = bfd_create (member, archive);
+  if (abfd == NULL)
+    return NULL;
+
+  coff_symbol_type *syms = bfd_zalloc (abfd, 2 * sizeof (*syms));
+  char *imp = bfd_alloc (abfd, sizeof "__imp_" - 1 + symbol_size);
+  if (syms == NULL
+      || imp == NULL
+      || !bfd_make_writable (abfd)
+      || bfd_write (&header, sizeof (header), abfd) != sizeof (header)
+      || bfd_write (symbol, symbol_size, abfd) != symbol_size
+      || bfd_write (dll, dll_size, abfd) != dll_size
+      || bfd_write (name, name_size, abfd) != name_size)
+    {
+      bfd_close_all_done (abfd);
+      return NULL;
+    }
+
+  sprintf (imp, "__imp_%s", symbol);
+  for (int i = 0; i < 2; i++)
+    {
+      syms[i].symbol.the_bfd = abfd;
+      syms[i].symbol.name = imp + (i == 0 ? 0 : sizeof "__imp_" - 1);
+      syms[i].symbol.flags = BSF_GLOBAL;
+      syms[i].symbol.section = bfd_abs_section_ptr;
+    }
+  obj_symbols (abfd) = syms;
+  abfd->symcount = exp->data ? 1 : 2;
+  abfd->flags |= HAS_SYMS;
+  abfd->direction = read_direction;
+  return abfd;
+}
+
+/* If HEAD, return the object defining DESCRIPTOR, the import descriptor
+   for DLL, which refers to INAME.  Otherwise return the object defining
+   INAME as the DLL name, with the null thunks and null descriptor.  */
+
+static bfd *
+pe_import_object (bfd *archive, const bfd_arch_info_type *arch, bool head,
+		  const char *dll, const char *descriptor, const char *iname,
+		  bool nul_prefix)
+{
+  unsigned int width = arch->bits_per_address / 8;
+  bfd_size_type thunk = head && !nul_prefix ? 0 : width;
+  struct pe_import_directory dir = { 0 };
+  bfd_byte zero[sizeof (dir)] = { 0 };
+  const char *names[] = { head ? ".idata$2" : ".idata$7", ".idata$4",
+			  ".idata$5", ".idata$3" };
+  bfd_size_type sizes[] = { head ? sizeof (dir) : strlen (dll) + 1,
+			    thunk, thunk, sizeof (dir) };
+  const void *data[] = { head ? (const void *) &dir : dll, zero, zero, zero };
+  unsigned int nsec = head ? 3 : 4;
+  unsigned int nsym = head ? 5 : 4;
+  asection *sec[4];
+  asymbol *syms[5];
+  arelent relocs[3];
+  arelent *relocp[3] = { &relocs[0], &relocs[1], &relocs[2] };
+  unsigned int i;
+
+  bfd *abfd = bfd_create (head ? "d00000000.o" : "z00000000.o", archive);
+  if (abfd == NULL)
+    return NULL;
+  if (!bfd_make_writable (abfd)
+      || !bfd_set_arch_mach (abfd, arch->arch, arch->mach))
+    goto fail;
+
+  for (i = 0; i < nsec; i++)
+    {
+      sec[i] = bfd_make_section_old_way (abfd, names[i]);
+      if (sec[i] == NULL
+	  || !bfd_set_section_flags (sec[i], (SEC_ALLOC | SEC_LOAD | SEC_KEEP
+					      | SEC_HAS_CONTENTS))
+	  || !bfd_set_section_alignment (sec[i], (i == 1 || i == 2
+						  ? bfd_log2 (width) : 2))
+	  || !bfd_set_section_size (sec[i], sizes[i]))
+	goto fail;
+      sec[i]->output_section = sec[i];
+    }
+
+  const char *sym_names[] = { names[0], names[1], names[2],
+			      head ? descriptor : iname, iname };
+  for (i = 0; i < nsym; i++)
+    {
+      syms[i] = bfd_make_empty_symbol (abfd);
+      if (syms[i] == NULL)
+	goto fail;
+      syms[i]->name = sym_names[i];
+      syms[i]->section = i < 4 ? sec[i % 3] : bfd_und_section_ptr;
+      syms[i]->flags = i < 3 ? BSF_LOCAL : BSF_GLOBAL;
+    }
+
+  if (head)
+    {
+      reloc_howto_type *howto = bfd_reloc_type_lookup (abfd, BFD_RELOC_RVA);
+      if (howto == NULL)
+	goto fail;
+      /* The addends skip the optional leading null thunks.  */
+      if (nul_prefix)
+	{
+	  bfd_putl32 (width, dir.lookup_table);
+	  bfd_putl32 (width, dir.address_table);
+	}
+      relocs[0] = (arelent) { &syms[1],
+			      offsetof (struct pe_import_directory,
+					lookup_table), 0, howto };
+      relocs[1] = (arelent) { &syms[4],
+			      offsetof (struct pe_import_directory, name),
+			      0, howto };
+      relocs[2] = (arelent) { &syms[2],
+			      offsetof (struct pe_import_directory,
+					address_table), 0, howto };
+      sec[0]->orelocation = relocp;
+      sec[0]->reloc_count = 3;
+      sec[0]->flags |= SEC_RELOC;
+    }
+
+  if (!bfd_set_symtab (abfd, syms, nsym))
+    goto fail;
+  for (i = 0; i < nsec; i++)
+    if (!bfd_set_section_contents (abfd, sec[i], data[i], 0, sizes[i]))
+      goto fail;
+  if (bfd_make_readable (abfd))
+    return abfd;
+
+ fail:
+  bfd_close_all_done (abfd);
+  return NULL;
+}
+
+static int
+pe_short_export_cmp (const void *a, const void *b)
+{
+  const struct bfd_pe_short_export *x = a;
+  const struct bfd_pe_short_export *y = b;
+
+  return strcmp (x->symbol, y->symbol);
+}
+
+/* Make ARCHIVE a short import library for the COUNT EXPORTS of DLL,
+   followed by the members chained from EXTRA.  NUL_PREFIX starts the
+   lookup and address tables with a null thunk.  The caller closes ARCHIVE
+   to write it.  GNU ld sorts the import sections by member name, which
+   places the d00000000.o head and the z00000000.o tail around the short
+   members.  */
+
+bool
+bfd_pe_write_short_import_library (bfd *archive,
+				   const bfd_arch_info_type *arch,
+				   const char *dll,
+				   struct bfd_pe_short_export *exports,
+				   size_t count, bool nul_prefix, bfd *extra)
+{
+  unsigned int machine;
+
+  switch (arch != NULL ? arch->arch : bfd_arch_unknown)
+    {
+    case bfd_arch_i386:
+      machine = (arch->mach & bfd_mach_x86_64
+		 ? IMAGE_FILE_MACHINE_AMD64 : IMAGE_FILE_MACHINE_I386);
+      break;
+    default:
+      bfd_set_error (bfd_error_sorry);
+      return false;
+    }
+
+  /* The descriptor is named after the DLL without its extension.  */
+  const char *dot = strrchr (dll, '.');
+  int len = dot != NULL ? (int) (dot - dll) : (int) strlen (dll);
+  char *descriptor = bfd_alloc (archive, sizeof "__IMPORT_DESCRIPTOR_" + len);
+  char *iname = bfd_alloc (archive, sizeof "___iname" + strlen (dll));
+  if (descriptor == NULL || iname == NULL)
+    return false;
+  sprintf (descriptor, "__IMPORT_DESCRIPTOR_%.*s", len, dll);
+  sprintf (iname, "__%s_iname", dll);
+
+  bfd *tail = pe_import_object (archive, arch, false, dll, descriptor, iname,
+				nul_prefix);
+  if (tail == NULL)
+    return false;
+  bfd *head = pe_import_object (archive, arch, true, dll, descriptor, iname,
+				nul_prefix);
+  if (head == NULL)
+    {
+      bfd_close_all_done (tail);
+      return false;
+    }
+  tail->archive_next = head;
+
+  /* Sort so that ld and dlltool write identical archives.  */
+  qsort (exports, count, sizeof (*exports), pe_short_export_cmp);
+  bool ret = true;
+  bfd **next = &head->archive_next;
+  for (size_t i = 0; i < count && ret; i++)
+    {
+      char member[sizeof "d00000000.o"];
+
+      sprintf (member, "d%08x.o", (unsigned int) i + 1);
+      *next = pe_short_import_member (archive, member, machine, dll,
+				      &exports[i]);
+      if (*next == NULL)
+	ret = false;
+      else
+	next = &(*next)->archive_next;
+    }
+  if (ret)
+    *next = extra;
+
+  return bfd_set_archive_head (archive, tail) && ret;
+}
diff --git a/bfd/coff-bfd.h b/bfd/coff-bfd.h
index 6626c491ebb..883baada7be 100644
--- a/bfd/coff-bfd.h
+++ b/bfd/coff-bfd.h
@@ -75,6 +75,19 @@ struct coff_section_tdata
 struct internal_syment;
 union internal_auxent;
 
+/* An export described by a PE short import library member.  */
+struct bfd_pe_short_export
+{
+  const char *symbol;	/* Public COFF symbol.  */
+  const char *name;	/* DLL export name, or NULL to import by ordinal.  */
+  unsigned int hint;	/* Ordinal if NAME is NULL, else the hint.  */
+  bool data;
+};
+
+extern bool bfd_pe_write_short_import_library
+  (bfd *, const bfd_arch_info_type *, const char *,
+   struct bfd_pe_short_export *, size_t, bool, bfd *);
+
 extern bool bfd_coff_get_syment
   (bfd *, struct bfd_symbol *, struct internal_syment *);
 
-- 
2.56.1.windows.1



More information about the Binutils mailing list