blob: 61c5664da479b9f9f18db68832fd97f7e90bfdbf [file] [log] [blame]
Guido van Rossum22a1d361999-12-20 21:18:49 +00001
2/* Support for dynamic loading of extension modules */
3
Christian Heimesfaf2f632008-01-06 16:59:19 +00004#include "Python.h"
5
Thomas Wouters0e3f5912006-08-11 14:57:12 +00006#ifdef HAVE_DIRECT_H
Guido van Rossum22a1d361999-12-20 21:18:49 +00007#include <direct.h>
Thomas Wouters0e3f5912006-08-11 14:57:12 +00008#endif
Mark Hammond1f7838b2000-10-05 10:54:45 +00009#include <ctype.h>
Guido van Rossum22a1d361999-12-20 21:18:49 +000010
Guido van Rossum22a1d361999-12-20 21:18:49 +000011#include "importdl.h"
Guido van Rossume7ba4952007-06-06 23:52:48 +000012#include <windows.h>
Guido van Rossum22a1d361999-12-20 21:18:49 +000013
Mark Hammond9844a1f2009-01-27 23:46:57 +000014// "activation context" magic - see dl_nt.c...
15extern ULONG_PTR _Py_ActivateActCtx();
16void _Py_DeactivateActCtx(ULONG_PTR cookie);
17
Guido van Rossum22a1d361999-12-20 21:18:49 +000018const struct filedescr _PyImport_DynLoadFiletab[] = {
19#ifdef _DEBUG
20 {"_d.pyd", "rb", C_EXTENSION},
Guido van Rossum22a1d361999-12-20 21:18:49 +000021#else
22 {".pyd", "rb", C_EXTENSION},
Guido van Rossum22a1d361999-12-20 21:18:49 +000023#endif
24 {0, 0}
25};
26
27
Mark Hammond1f7838b2000-10-05 10:54:45 +000028/* Case insensitive string compare, to avoid any dependencies on particular
29 C RTL implementations */
30
31static int strcasecmp (char *string1, char *string2)
32{
33 int first, second;
34
35 do {
36 first = tolower(*string1);
37 second = tolower(*string2);
38 string1++;
39 string2++;
40 } while (first && first == second);
41
42 return (first - second);
43}
44
45
46/* Function to return the name of the "python" DLL that the supplied module
47 directly imports. Looks through the list of imported modules and
48 returns the first entry that starts with "python" (case sensitive) and
49 is followed by nothing but numbers until the separator (period).
50
51 Returns a pointer to the import name, or NULL if no matching name was
52 located.
53
54 This function parses through the PE header for the module as loaded in
55 memory by the system loader. The PE header is accessed as documented by
56 Microsoft in the MSDN PE and COFF specification (2/99), and handles
57 both PE32 and PE32+. It only worries about the direct import table and
58 not the delay load import table since it's unlikely an extension is
59 going to be delay loading Python (after all, it's already loaded).
60
61 If any magic values are not found (e.g., the PE header or optional
62 header magic), then this function simply returns NULL. */
63
64#define DWORD_AT(mem) (*(DWORD *)(mem))
65#define WORD_AT(mem) (*(WORD *)(mem))
66
67static char *GetPythonImport (HINSTANCE hModule)
68{
69 unsigned char *dllbase, *import_data, *import_name;
70 DWORD pe_offset, opt_offset;
71 WORD opt_magic;
72 int num_dict_off, import_off;
73
74 /* Safety check input */
75 if (hModule == NULL) {
76 return NULL;
77 }
78
79 /* Module instance is also the base load address. First portion of
80 memory is the MS-DOS loader, which holds the offset to the PE
81 header (from the load base) at 0x3C */
82 dllbase = (unsigned char *)hModule;
83 pe_offset = DWORD_AT(dllbase + 0x3C);
84
85 /* The PE signature must be "PE\0\0" */
86 if (memcmp(dllbase+pe_offset,"PE\0\0",4)) {
87 return NULL;
88 }
89
90 /* Following the PE signature is the standard COFF header (20
91 bytes) and then the optional header. The optional header starts
92 with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+
93 uses 64-bits for some fields). It might also be 0x107 for a ROM
94 image, but we don't process that here.
95
96 The optional header ends with a data dictionary that directly
97 points to certain types of data, among them the import entries
98 (in the second table entry). Based on the header type, we
99 determine offsets for the data dictionary count and the entry
100 within the dictionary pointing to the imports. */
101
102 opt_offset = pe_offset + 4 + 20;
103 opt_magic = WORD_AT(dllbase+opt_offset);
104 if (opt_magic == 0x10B) {
105 /* PE32 */
106 num_dict_off = 92;
107 import_off = 104;
108 } else if (opt_magic == 0x20B) {
109 /* PE32+ */
110 num_dict_off = 108;
111 import_off = 120;
112 } else {
113 /* Unsupported */
114 return NULL;
115 }
116
117 /* Now if an import table exists, offset to it and walk the list of
118 imports. The import table is an array (ending when an entry has
119 empty values) of structures (20 bytes each), which contains (at
120 offset 12) a relative address (to the module base) at which a
121 string constant holding the import name is located. */
122
123 if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) {
Thomas Heller1df04612004-07-02 08:53:57 +0000124 /* We have at least 2 tables - the import table is the second
125 one. But still it may be that the table size is zero */
126 if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD)))
127 return NULL;
Mark Hammond1f7838b2000-10-05 10:54:45 +0000128 import_data = dllbase + DWORD_AT(dllbase +
129 opt_offset +
130 import_off);
131 while (DWORD_AT(import_data)) {
132 import_name = dllbase + DWORD_AT(import_data+12);
133 if (strlen(import_name) >= 6 &&
134 !strncmp(import_name,"python",6)) {
135 char *pch;
136
137 /* Ensure python prefix is followed only
138 by numbers to the end of the basename */
139 pch = import_name + 6;
Thomas Heller1df04612004-07-02 08:53:57 +0000140#ifdef _DEBUG
141 while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') {
142#else
Mark Hammond1f7838b2000-10-05 10:54:45 +0000143 while (*pch && *pch != '.') {
Thomas Heller1df04612004-07-02 08:53:57 +0000144#endif
Mark Hammond1f7838b2000-10-05 10:54:45 +0000145 if (*pch >= '0' && *pch <= '9') {
146 pch++;
147 } else {
148 pch = NULL;
149 break;
150 }
151 }
152
153 if (pch) {
154 /* Found it - return the name */
155 return import_name;
156 }
157 }
158 import_data += 20;
159 }
160 }
161
162 return NULL;
163}
Mark Hammond1f7838b2000-10-05 10:54:45 +0000164
165
Guido van Rossum96a8fb71999-12-22 14:09:35 +0000166dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
Guido van Rossum22a1d361999-12-20 21:18:49 +0000167 const char *pathname, FILE *fp)
168{
169 dl_funcptr p;
Mark Hammond1f7838b2000-10-05 10:54:45 +0000170 char funcname[258], *import_python;
Guido van Rossum96a8fb71999-12-22 14:09:35 +0000171
Martin v. Löwis6cb01092008-06-11 06:22:46 +0000172 PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname);
Guido van Rossum22a1d361999-12-20 21:18:49 +0000173
Guido van Rossum22a1d361999-12-20 21:18:49 +0000174 {
Mark Hammondfb1f68e2001-05-09 00:50:59 +0000175 HINSTANCE hDLL = NULL;
Guido van Rossum22a1d361999-12-20 21:18:49 +0000176 char pathbuf[260];
Mark Hammondfb1f68e2001-05-09 00:50:59 +0000177 LPTSTR dummy;
Christian Heimesbbffeb62008-01-24 09:42:52 +0000178 unsigned int old_mode;
Mark Hammond9844a1f2009-01-27 23:46:57 +0000179 ULONG_PTR cookie = 0;
Mark Hammondfb1f68e2001-05-09 00:50:59 +0000180 /* We use LoadLibraryEx so Windows looks for dependent DLLs
181 in directory of pathname first. However, Windows95
182 can sometimes not work correctly unless the absolute
183 path is used. If GetFullPathName() fails, the LoadLibrary
184 will certainly fail too, so use its error code */
Christian Heimesbbffeb62008-01-24 09:42:52 +0000185
186 /* Don't display a message box when Python can't load a DLL */
187 old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
188
Mark Hammondfb1f68e2001-05-09 00:50:59 +0000189 if (GetFullPathName(pathname,
190 sizeof(pathbuf),
191 pathbuf,
Mark Hammond9844a1f2009-01-27 23:46:57 +0000192 &dummy)) {
193 ULONG_PTR cookie = _Py_ActivateActCtx();
Mark Hammondfb1f68e2001-05-09 00:50:59 +0000194 /* XXX This call doesn't exist in Windows CE */
195 hDLL = LoadLibraryEx(pathname, NULL,
196 LOAD_WITH_ALTERED_SEARCH_PATH);
Mark Hammond9844a1f2009-01-27 23:46:57 +0000197 _Py_DeactivateActCtx(cookie);
198 }
Christian Heimesbbffeb62008-01-24 09:42:52 +0000199
200 /* restore old error mode settings */
201 SetErrorMode(old_mode);
202
Guido van Rossum22a1d361999-12-20 21:18:49 +0000203 if (hDLL==NULL){
Amaury Forgeot d'Arcd6179e12008-01-03 23:42:13 +0000204 PyObject *message;
Guido van Rossum22a1d361999-12-20 21:18:49 +0000205 unsigned int errorCode;
206
207 /* Get an error string from Win32 error code */
Amaury Forgeot d'Arcd6179e12008-01-03 23:42:13 +0000208 wchar_t theInfo[256]; /* Pointer to error text
Guido van Rossum22a1d361999-12-20 21:18:49 +0000209 from system */
210 int theLength; /* Length of error text */
211
212 errorCode = GetLastError();
213
Amaury Forgeot d'Arcd6179e12008-01-03 23:42:13 +0000214 theLength = FormatMessageW(
215 FORMAT_MESSAGE_FROM_SYSTEM |
216 FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */
Guido van Rossum22a1d361999-12-20 21:18:49 +0000217 NULL, /* message source */
218 errorCode, /* the message (error) ID */
Amaury Forgeot d'Arcd6179e12008-01-03 23:42:13 +0000219 MAKELANGID(LANG_NEUTRAL,
220 SUBLANG_DEFAULT),
221 /* Default language */
222 theInfo, /* the buffer */
Guido van Rossum22a1d361999-12-20 21:18:49 +0000223 sizeof(theInfo), /* the buffer size */
224 NULL); /* no additional format args. */
225
226 /* Problem: could not get the error message.
227 This should not happen if called correctly. */
228 if (theLength == 0) {
Amaury Forgeot d'Arcd6179e12008-01-03 23:42:13 +0000229 message = PyUnicode_FromFormat(
230 "DLL load failed with error code %d",
231 errorCode);
Guido van Rossum22a1d361999-12-20 21:18:49 +0000232 } else {
Guido van Rossum22a1d361999-12-20 21:18:49 +0000233 /* For some reason a \r\n
234 is appended to the text */
235 if (theLength >= 2 &&
236 theInfo[theLength-2] == '\r' &&
237 theInfo[theLength-1] == '\n') {
238 theLength -= 2;
239 theInfo[theLength] = '\0';
240 }
Amaury Forgeot d'Arcd6179e12008-01-03 23:42:13 +0000241 message = PyUnicode_FromString(
242 "DLL load failed: ");
243
244 PyUnicode_AppendAndDel(&message,
245 PyUnicode_FromUnicode(
246 theInfo,
247 theLength));
Guido van Rossum22a1d361999-12-20 21:18:49 +0000248 }
Amaury Forgeot d'Arcd6179e12008-01-03 23:42:13 +0000249 PyErr_SetObject(PyExc_ImportError, message);
250 Py_XDECREF(message);
Fred Drakee20131e2002-08-26 21:20:30 +0000251 return NULL;
Mark Hammond1f7838b2000-10-05 10:54:45 +0000252 } else {
253 char buffer[256];
254
Thomas Heller1df04612004-07-02 08:53:57 +0000255#ifdef _DEBUG
256 PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll",
257#else
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000258 PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll",
Thomas Heller1df04612004-07-02 08:53:57 +0000259#endif
Fred Drakee20131e2002-08-26 21:20:30 +0000260 PY_MAJOR_VERSION,PY_MINOR_VERSION);
Mark Hammond1f7838b2000-10-05 10:54:45 +0000261 import_python = GetPythonImport(hDLL);
262
263 if (import_python &&
264 strcasecmp(buffer,import_python)) {
Jeremy Hylton518ab1c2001-11-28 20:42:20 +0000265 PyOS_snprintf(buffer, sizeof(buffer),
266 "Module use of %.150s conflicts "
267 "with this version of Python.",
268 import_python);
Mark Hammond1f7838b2000-10-05 10:54:45 +0000269 PyErr_SetString(PyExc_ImportError,buffer);
270 FreeLibrary(hDLL);
271 return NULL;
272 }
Guido van Rossum22a1d361999-12-20 21:18:49 +0000273 }
274 p = GetProcAddress(hDLL, funcname);
275 }
Guido van Rossum22a1d361999-12-20 21:18:49 +0000276
277 return p;
278}