1010#include "osdefs.h"
1111#include <windows.h>
1212#include "importdl.h"
13+ #include "malloc.h" // for alloca
14+
15+ extern const char * PyWin_DLLVersionString ; // a string loaded from the DLL at startup.
1316
1417/* Return whether this is Win32s, i.e., Win32 API on Win 3.1(1).
1518 This function is exported! */
@@ -29,13 +32,32 @@ BOOL PyWin_IsWin32s()
2932
3033FILE * PyWin_FindRegisteredModule ( const char * moduleName , struct filedescr * * ppFileDesc , char * pathBuf , int pathLen )
3134{
32- char moduleKey [128 ];
35+ char * moduleKey ;
36+ char * pos ;
37+ const char keyPrefix [] = "Software\\Python\\PythonCore\\" ;
38+ const char keySuffix [] = "\\Modules\\" ;
3339 struct filedescr * fdp = NULL ;
3440 FILE * fp ;
3541 int modNameSize = pathLen ;
42+ int versionLen , moduleLen ;
3643 HKEY keyBase = PyWin_IsWin32s () ? HKEY_CLASSES_ROOT : HKEY_LOCAL_MACHINE ;
37- strcpy (moduleKey , "Software\\Python\\PythonCore\\" MS_DLL_ID "\\Modules\\" );
38- strcat (moduleKey , moduleName );
44+
45+ // conceptually, this code is setting up:
46+ // sprintf(buf, "Software\\Python\\PythonCore\\%s\\Modules\\%s", PyWin_DLLVersionString, moduleName);
47+ // the sprintf would be clearer, but slower and less "length-safe"
48+ versionLen = strlen (PyWin_DLLVersionString );
49+ moduleLen = strlen (moduleName );
50+ // alloca == no free required, but memory only local to fn, also no heap fragmentation!
51+ moduleKey = alloca (sizeof (keyPrefix )- 1 + versionLen + sizeof (keySuffix ) + moduleLen ); // chars only, plus 1 NULL.
52+ pos = moduleKey ;
53+ memcpy (pos , keyPrefix , sizeof (keyPrefix )- 1 );
54+ pos += sizeof (keyPrefix )- 1 ;
55+ memcpy (pos , PyWin_DLLVersionString , versionLen );
56+ pos += versionLen ;
57+ memcpy (pos , keySuffix , sizeof (keySuffix ));
58+ pos += sizeof (keySuffix )- 1 ;
59+ memcpy (pos , moduleName , moduleLen + 1 ); // NULL comes with this one!
60+
3961 if (RegQueryValue (keyBase , moduleKey , pathBuf , & modNameSize )!= ERROR_SUCCESS )
4062 return NULL ;
4163 // use the file extension to locate the type entry.
0 commit comments