Fix three PyChecker-detected gotchas.
[python/dscho.git] / PC / import_nt.c
blob573106fd3ff2f390dcaa56fab41b7b37a0d38831
1 /********************************************************************
3 import_nt.c
5 Win32 specific import code.
7 */
9 #include "Python.h"
10 #include "osdefs.h"
11 #include <assert.h>
12 #include <windows.h>
13 #include "importdl.h"
14 #include "malloc.h" /* for alloca */
16 /* a string loaded from the DLL at startup */
17 extern const char *PyWin_DLLVersionString;
19 FILE *PyWin_FindRegisteredModule(const char *moduleName,
20 struct filedescr **ppFileDesc,
21 char *pathBuf,
22 int pathLen)
24 char *moduleKey;
25 const char keyPrefix[] = "Software\\Python\\PythonCore\\";
26 const char keySuffix[] = "\\Modules\\";
27 #ifdef _DEBUG
28 /* In debugging builds, we _must_ have the debug version
29 * registered.
31 const char debugString[] = "\\Debug";
32 #else
33 const char debugString[] = "";
34 #endif
35 struct filedescr *fdp = NULL;
36 FILE *fp;
37 HKEY keyBase = HKEY_CURRENT_USER;
38 int modNameSize;
39 long regStat;
41 /* Calculate the size for the sprintf buffer.
42 * Get the size of the chars only, plus 1 NULL.
44 size_t bufSize = sizeof(keyPrefix)-1 +
45 strlen(PyWin_DLLVersionString) +
46 sizeof(keySuffix) +
47 strlen(moduleName) +
48 sizeof(debugString) - 1;
49 /* alloca == no free required, but memory only local to fn,
50 * also no heap fragmentation!
52 moduleKey = alloca(bufSize);
53 sprintf(moduleKey,
54 "Software\\Python\\PythonCore\\%s\\Modules\\%s%s",
55 PyWin_DLLVersionString, moduleName, debugString);
57 modNameSize = pathLen;
58 regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize);
59 if (regStat != ERROR_SUCCESS) {
60 /* No user setting - lookup in machine settings */
61 keyBase = HKEY_LOCAL_MACHINE;
62 /* be anal - failure may have reset size param */
63 modNameSize = pathLen;
64 regStat = RegQueryValue(keyBase, moduleKey,
65 pathBuf, &modNameSize);
67 if (regStat != ERROR_SUCCESS)
68 return NULL;
70 /* use the file extension to locate the type entry. */
71 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
72 size_t extLen = strlen(fdp->suffix);
73 assert(modNameSize >= 0); /* else cast to size_t is wrong */
74 if ((size_t)modNameSize > extLen &&
75 strnicmp(pathBuf + ((size_t)modNameSize-extLen-1),
76 fdp->suffix,
77 extLen) == 0)
78 break;
80 if (fdp->suffix == NULL)
81 return NULL;
82 fp = fopen(pathBuf, fdp->mode);
83 if (fp != NULL)
84 *ppFileDesc = fdp;
85 return fp;