import_nt.c 2.36 KB
Newer Older
1 2
/********************************************************************

3
 import_nt.c 
4 5 6 7 8

  Win32 specific import code.

*/

9
#include "Python.h"
10 11 12
#include "osdefs.h"
#include <windows.h>
#include "importdl.h"
13
#include "malloc.h" /* for alloca */
14

15 16
/* a string loaded from the DLL at startup */
extern const char *PyWin_DLLVersionString;
17

18 19 20 21
FILE *PyWin_FindRegisteredModule(const char *moduleName,
				 struct filedescr **ppFileDesc,
				 char *pathBuf,
				 int pathLen)
22
{
23 24 25
	char *moduleKey;
	const char keyPrefix[] = "Software\\Python\\PythonCore\\";
	const char keySuffix[] = "\\Modules\\";
Guido van Rossum's avatar
Guido van Rossum committed
26
#ifdef _DEBUG
27 28 29
	/* In debugging builds, we _must_ have the debug version
	 * registered.
	 */
Guido van Rossum's avatar
Guido van Rossum committed
30 31 32 33
	const char debugString[] = "\\Debug";
#else
	const char debugString[] = "";
#endif
34 35
	struct filedescr *fdp = NULL;
	FILE *fp;
36
	HKEY keyBase = HKEY_CURRENT_USER;
Guido van Rossum's avatar
Guido van Rossum committed
37
	int modNameSize;
38
	long regStat;
39

40 41 42 43 44 45 46 47 48 49 50
	/* Calculate the size for the sprintf buffer.
	 * Get the size of the chars only, plus 1 NULL.
	 */
	size_t bufSize = sizeof(keyPrefix)-1 +
	                 strlen(PyWin_DLLVersionString) +
	                 sizeof(keySuffix) +
	                 strlen(moduleName) +
	                 sizeof(debugString) - 1;
	/* alloca == no free required, but memory only local to fn,
	 * also no heap fragmentation!
	 */
Guido van Rossum's avatar
Guido van Rossum committed
51
	moduleKey = alloca(bufSize); 
52 53 54
	PyOS_snprintf(moduleKey, bufSize,
		      "Software\\Python\\PythonCore\\%s\\Modules\\%s%s",
		      PyWin_DLLVersionString, moduleName, debugString);
55

56
	modNameSize = pathLen;
57
	regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize);
58 59 60 61 62 63 64 65 66 67 68
	if (regStat != ERROR_SUCCESS) {
		/* No user setting - lookup in machine settings */
		keyBase = HKEY_LOCAL_MACHINE;
		/* be anal - failure may have reset size param */
		modNameSize = pathLen;
		regStat = RegQueryValue(keyBase, moduleKey, 
		                        pathBuf, &modNameSize);

		if (regStat != ERROR_SUCCESS)
			return NULL;
	}
69
	/* use the file extension to locate the type entry. */
70
	for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
71
		size_t extLen = strlen(fdp->suffix);
72 73 74 75 76
		assert(modNameSize >= 0); /* else cast to size_t is wrong */
		if ((size_t)modNameSize > extLen &&
		    strnicmp(pathBuf + ((size_t)modNameSize-extLen-1),
		             fdp->suffix,
		             extLen) == 0)
77 78
			break;
	}
79
	if (fdp->suffix == NULL)
80 81 82 83 84 85
		return NULL;
	fp = fopen(pathBuf, fdp->mode);
	if (fp != NULL)
		*ppFileDesc = fdp;
	return fp;
}