crt: Pass --temp-prefix to dlltool, if supported

When GNU dlltool generates import libraries, it picks a semi-random
prefix string for its file names based on the pid of the process.
Normally, the prefix doesn't matter much, but when we merge multiple
import libraries into one, like for libucrt.a, the prefixes need
to be unique (otherwise their import tables get entangled).

In practice it has been noticed that these aren't always unique
(see https://github.com/msys2/MINGW-packages/issues/9363).
Instead pass an option to give it use a unique prefix for each
library (based on the target dll name).

LLVM dlltool uses a different format of import library, where
there's no corresponding semi random prefix. LLVM dlltool doesn't
support the --temp-prefix option either (yet). Therefore, try to
detect whether the option is supported.

Based on a Debian patch by Stephen Kitt.

Signed-off-by: Martin Storsjö <martin@martin.st>
diff --git a/mingw-w64-crt/Makefile.am b/mingw-w64-crt/Makefile.am
index e104804..2d33e1a 100644
--- a/mingw-w64-crt/Makefile.am
+++ b/mingw-w64-crt/Makefile.am
@@ -46,6 +46,9 @@
   DTDEF32=$(DLLTOOL) $(DLLTOOLFLAGS32) $(AM_DLLTOOLFLAGS) --input-def
   DTDEF64=$(DLLTOOL) $(DLLTOOLFLAGS64) $(AM_DLLTOOLFLAGS) --input-def
 endif
+if DLLTOOL_HAS_TEMP_PREFIX
+  AM_DLLTOOLFLAGS += --temp-prefix $$(basename $@ .a)
+endif
 if DELAY_IMPORT_LIBS
   AM_DLLTOOLFLAGS += --output-delaylib $@.delayimp.a
 endif
diff --git a/mingw-w64-crt/configure.ac b/mingw-w64-crt/configure.ac
index b63e305..ad50953 100644
--- a/mingw-w64-crt/configure.ac
+++ b/mingw-w64-crt/configure.ac
@@ -47,6 +47,37 @@
 dnl ---
 AM_PROG_CC_C_O
 
+AC_MSG_CHECKING([whether dlltool supports --temp-prefix])
+cat > test.def <<EOF
+LIBRARY test.dll
+EXPORTS
+myfunc
+EOF
+
+AS_VAR_SET([test_dlltool_flags],[])
+AC_DEFUN([TEST_DLLTOOL], [
+  test_dlltool_flags_save="$test_dlltool_flags"
+  test_dlltool_flags="$test_dlltool_flags $1"
+  AS_ECHO([["$DLLTOOL $test_dlltool_flags -d test.def -l libtest.a"]]) >&AS_MESSAGE_LOG_FD
+  AS_IF($DLLTOOL $test_dlltool_flags -d test.def -l libtest.a >&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD, [
+    $2
+  ], [
+    test_dlltool_flags="$test_dlltool_flags_save"
+  ])
+])
+
+# First check if $DLLTOOL supports the -m option. LLVM dlltool might not
+# have a default arch (in older versions), so make sure we specify one.
+TEST_DLLTOOL([--as-flags=--64 -m i386:x86-64])
+# Now check if --temp-prefix is supported. GNU dlltool supports it,
+# LLVM dlltool doesn't, yet at least (but doesn't need it either).
+AS_VAR_SET([dlltool_has_temp_prefix],[no])
+TEST_DLLTOOL([--temp-prefix myprefix], [dlltool_has_temp_prefix=yes])
+
+rm -f test.def libtest.a
+AC_MSG_RESULT([$dlltool_has_temp_prefix])
+AM_CONDITIONAL([DLLTOOL_HAS_TEMP_PREFIX],[test $dlltool_has_temp_prefix = yes])
+
 AC_MSG_CHECKING([whether to build a w32api package for Cygwin])
 AC_ARG_ENABLE([w32api],
   [AS_HELP_STRING([--enable-w32api],