From f72f52c9d19124e4f87b0023578719061a6ff079 Mon Sep 17 00:00:00 2001
From: Christoph Reiter <reiter.christoph@gmail.com>
Date: Sun, 27 Aug 2023 15:00:32 +0200
Subject: [PATCH 101/N] Port GetPythonImport() to mingw

This looks for DLL names in the import table but while with MSVC the DLL
is named python311.dll in our case it is named libpython3.11.dll.
Adjust the strings and lengths accordingly.
---
 Python/dynload_win.c | 24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)

diff --git a/Python/dynload_win.c b/Python/dynload_win.c
index db79687..36d1c7a 100644
--- a/Python/dynload_win.c
+++ b/Python/dynload_win.c
@@ -56,6 +56,16 @@ const char *_PyImport_DynLoadFiletab[] = {
 #define DWORD_AT(mem) (*(DWORD *)(mem))
 #define WORD_AT(mem)  (*(WORD *)(mem))
 
+#ifdef __MINGW32__
+#define DLL_PREFIX "libpython"
+#define DLL_PREFIX_LEN 9
+#define DLL_NAME_FORMAT "libpython%d.%d"
+#else
+#define DLL_PREFIX "python"
+#define DLL_PREFIX_LEN 6
+#define DLL_NAME_FORMAT "python%d%d"
+#endif
+
 static char *GetPythonImport (HINSTANCE hModule)
 {
     unsigned char *dllbase, *import_data, *import_name;
@@ -122,15 +132,15 @@ static char *GetPythonImport (HINSTANCE hModule)
                                          import_off);
         while (DWORD_AT(import_data)) {
             import_name = dllbase + DWORD_AT(import_data+12);
-            if (strlen(import_name) >= 6 &&
-                !strncmp(import_name,"python",6)) {
+            if (strlen(import_name) >= DLL_PREFIX_LEN &&
+                !strncmp(import_name, DLL_PREFIX, DLL_PREFIX_LEN)) {
                 char *pch;
 
                 /* Don't claim that python3.dll is a Python DLL. */
 #ifdef _DEBUG
-                if (strcmp(import_name, "python3_d.dll") == 0) {
+                if (strcmp(import_name, DLL_PREFIX "3_d.dll") == 0) {
 #else
-                if (strcmp(import_name, "python3.dll") == 0) {
+                if (strcmp(import_name, DLL_PREFIX "3.dll") == 0) {
 #endif
                     import_data += 20;
                     continue;
@@ -138,7 +148,7 @@ static char *GetPythonImport (HINSTANCE hModule)
 
                 /* Ensure python prefix is followed only
                    by numbers to the end of the basename */
-                pch = import_name + 6;
+                pch = import_name + DLL_PREFIX_LEN;
 #ifdef _DEBUG
                 while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') {
 #else
@@ -329,9 +339,9 @@ dl_funcptr _PyImport_FindSharedFuncptrWindows(const char *prefix,
 
             PyOS_snprintf(buffer, sizeof(buffer),
 #ifdef _DEBUG
-                          "python%d%d_d.dll",
+                          DLL_NAME_FORMAT "_d.dll",
 #else
-                          "python%d%d.dll",
+                          DLL_NAME_FORMAT ".dll",
 #endif
                           PY_MAJOR_VERSION,PY_MINOR_VERSION);
             import_python = GetPythonImport(hDLL);
