blob: 0b0d81068dc539028c96d5af9d6da91d46940a4a [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Kristján Valur Jónsson67387fb2007-04-25 00:17:39 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Neal Norwitzadb69fc2005-12-17 20:54:49 +00008#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000011#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000014#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000015#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000016#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017
Guido van Rossum55a83382000-09-20 20:31:38 +000018#ifdef HAVE_FCNTL_H
19#include <fcntl.h>
20#endif
Anthony Baxterac6bd462006-04-13 02:06:09 +000021#ifdef __cplusplus
22extern "C" {
23#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000024
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000025extern time_t PyOS_GetLastModificationTime(char *, FILE *);
26 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000027
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000028/* Magic word to reject .pyc files generated by other Python versions.
29 It should change for each incompatible change to the bytecode.
30
31 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000032 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000033 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000034
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000035 The magic numbers must be spaced apart atleast 2 values, as the
36 -U interpeter flag will cause MAGIC+1 being used. They have been
37 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000038
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000039 There were a variety of old schemes for setting the magic number.
40 The current working scheme is to increment the previous value by
41 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000042
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000043 Known values:
44 Python 1.5: 20121
45 Python 1.5.1: 20121
46 Python 1.5.2: 20121
Skip Montanaro4ec3c262006-03-25 14:12:03 +000047 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000048 Python 2.0: 50823
49 Python 2.0.1: 50823
50 Python 2.1: 60202
51 Python 2.1.1: 60202
52 Python 2.1.2: 60202
53 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000054 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000055 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000056 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000057 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000058 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000059 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000060 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000061 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000062 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000063 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Neal Norwitz0d62a062006-07-30 06:53:31 +000064 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
65 Python 2.5b3: 62111 (fix wrong code: x += yield)
Neal Norwitz9a70f952006-08-04 05:12:19 +000066 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
67 storing constants that should have been removed)
Neal Norwitzdac090d2006-09-05 03:53:08 +000068 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Raymond Hettingereffde122007-12-18 18:26:18 +000069 Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000070.
Tim Peters36515e22001-11-18 04:06:29 +000071*/
Raymond Hettingereffde122007-12-18 18:26:18 +000072#define MAGIC (62151 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000073
Guido van Rossum96774c12000-05-01 20:19:08 +000074/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000075 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000076 compiler works which are enabled by command line switches. */
77static long pyc_magic = MAGIC;
78
Guido van Rossum25ce5661997-08-02 03:10:38 +000079/* See _PyImport_FixupExtension() below */
80static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000081
Guido van Rossum771c6c81997-10-31 18:37:24 +000082/* This table is defined in config.c: */
83extern struct _inittab _PyImport_Inittab[];
84
85struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000086
Guido van Rossumed1170e1999-12-20 21:23:41 +000087/* these tables define the module suffixes that Python recognizes */
88struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +000089
90#ifdef RISCOS
91static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000092 {"/py", "U", PY_SOURCE},
Guido van Rossum48a680c2001-03-02 06:34:14 +000093 {"/pyc", "rb", PY_COMPILED},
94 {0, 0}
95};
96#else
Guido van Rossumed1170e1999-12-20 21:23:41 +000097static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000098 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000099#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +0000100 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000101#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000102 {".pyc", "rb", PY_COMPILED},
103 {0, 0}
104};
Guido van Rossum48a680c2001-03-02 06:34:14 +0000105#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000106
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000107
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000108/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000109
110void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000111_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000112{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000113 const struct filedescr *scan;
114 struct filedescr *filetab;
115 int countD = 0;
116 int countS = 0;
117
118 /* prepare _PyImport_Filetab: copy entries from
119 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
120 */
Georg Brandladd36e52007-08-23 18:08:06 +0000121#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000122 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
123 ++countD;
Georg Brandladd36e52007-08-23 18:08:06 +0000124#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000125 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
126 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000127 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Neal Norwitze1fdb322006-07-21 05:32:28 +0000128 if (filetab == NULL)
Neal Norwitz33722ae2006-07-21 07:59:02 +0000129 Py_FatalError("Can't initialize import file table.");
Georg Brandladd36e52007-08-23 18:08:06 +0000130#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000131 memcpy(filetab, _PyImport_DynLoadFiletab,
132 countD * sizeof(struct filedescr));
Georg Brandladd36e52007-08-23 18:08:06 +0000133#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000134 memcpy(filetab + countD, _PyImport_StandardFiletab,
135 countS * sizeof(struct filedescr));
136 filetab[countD + countS].suffix = NULL;
137
138 _PyImport_Filetab = filetab;
139
Guido van Rossum0824f631997-03-11 18:37:35 +0000140 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000141 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
142 for (; filetab->suffix != NULL; filetab++) {
Guido van Rossum48a680c2001-03-02 06:34:14 +0000143#ifndef RISCOS
Guido van Rossumed1170e1999-12-20 21:23:41 +0000144 if (strcmp(filetab->suffix, ".pyc") == 0)
145 filetab->suffix = ".pyo";
Guido van Rossum48a680c2001-03-02 06:34:14 +0000146#else
147 if (strcmp(filetab->suffix, "/pyc") == 0)
148 filetab->suffix = "/pyo";
149#endif
Guido van Rossum0824f631997-03-11 18:37:35 +0000150 }
151 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000152
153 if (Py_UnicodeFlag) {
154 /* Fix the pyc_magic so that byte compiled code created
155 using the all-Unicode method doesn't interfere with
156 code created in normal operation mode. */
157 pyc_magic = MAGIC + 1;
158 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
160
Guido van Rossum25ce5661997-08-02 03:10:38 +0000161void
Just van Rossum52e14d62002-12-30 22:08:05 +0000162_PyImportHooks_Init(void)
163{
164 PyObject *v, *path_hooks = NULL, *zimpimport;
165 int err = 0;
166
167 /* adding sys.path_hooks and sys.path_importer_cache, setting up
168 zipimport */
Nick Coghlan327a39b2007-11-18 11:56:28 +0000169 if (PyType_Ready(&PyNullImporter_Type) < 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000170 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000171
172 if (Py_VerboseFlag)
173 PySys_WriteStderr("# installing zipimport hook\n");
174
175 v = PyList_New(0);
176 if (v == NULL)
177 goto error;
178 err = PySys_SetObject("meta_path", v);
179 Py_DECREF(v);
180 if (err)
181 goto error;
182 v = PyDict_New();
183 if (v == NULL)
184 goto error;
185 err = PySys_SetObject("path_importer_cache", v);
186 Py_DECREF(v);
187 if (err)
188 goto error;
189 path_hooks = PyList_New(0);
190 if (path_hooks == NULL)
191 goto error;
192 err = PySys_SetObject("path_hooks", path_hooks);
193 if (err) {
194 error:
195 PyErr_Print();
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000196 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
197 "path_importer_cache, or NullImporter failed"
198 );
Just van Rossum52e14d62002-12-30 22:08:05 +0000199 }
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000200
Just van Rossum52e14d62002-12-30 22:08:05 +0000201 zimpimport = PyImport_ImportModule("zipimport");
202 if (zimpimport == NULL) {
203 PyErr_Clear(); /* No zip import module -- okay */
204 if (Py_VerboseFlag)
205 PySys_WriteStderr("# can't import zipimport\n");
206 }
207 else {
208 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
209 "zipimporter");
210 Py_DECREF(zimpimport);
211 if (zipimporter == NULL) {
212 PyErr_Clear(); /* No zipimporter object -- okay */
213 if (Py_VerboseFlag)
214 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000215 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000216 }
217 else {
218 /* sys.path_hooks.append(zipimporter) */
219 err = PyList_Append(path_hooks, zipimporter);
220 Py_DECREF(zipimporter);
221 if (err)
222 goto error;
223 if (Py_VerboseFlag)
224 PySys_WriteStderr(
225 "# installed zipimport hook\n");
226 }
227 }
228 Py_DECREF(path_hooks);
229}
230
231void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000232_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000233{
234 Py_XDECREF(extensions);
235 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000236 PyMem_DEL(_PyImport_Filetab);
237 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000238}
239
240
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000241/* Locking primitives to prevent parallel imports of the same module
242 in different threads to return with a partially loaded module.
243 These calls are serialized by the global interpreter lock. */
244
245#ifdef WITH_THREAD
246
Guido van Rossum49b56061998-10-01 20:42:43 +0000247#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000248
Guido van Rossum65d5b571998-12-21 19:32:43 +0000249static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000250static long import_lock_thread = -1;
251static int import_lock_level = 0;
252
253static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000254lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000255{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000256 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000257 if (me == -1)
258 return; /* Too bad */
Neal Norwitze1fdb322006-07-21 05:32:28 +0000259 if (import_lock == NULL) {
Guido van Rossum65d5b571998-12-21 19:32:43 +0000260 import_lock = PyThread_allocate_lock();
Neal Norwitze1fdb322006-07-21 05:32:28 +0000261 if (import_lock == NULL)
262 return; /* Nothing much we can do. */
263 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000264 if (import_lock_thread == me) {
265 import_lock_level++;
266 return;
267 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000268 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
269 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000270 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000271 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000272 PyEval_RestoreThread(tstate);
273 }
274 import_lock_thread = me;
275 import_lock_level = 1;
276}
277
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000278static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000279unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000280{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000281 long me = PyThread_get_thread_ident();
Neal Norwitze1fdb322006-07-21 05:32:28 +0000282 if (me == -1 || import_lock == NULL)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000283 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000284 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000285 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000286 import_lock_level--;
287 if (import_lock_level == 0) {
288 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000289 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000290 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000291 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000292}
293
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000294/* This function is called from PyOS_AfterFork to ensure that newly
295 created child processes do not share locks with the parent. */
296
297void
298_PyImport_ReInitLock(void)
299{
300#ifdef _AIX
301 if (import_lock != NULL)
302 import_lock = PyThread_allocate_lock();
303#endif
304}
305
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000306#else
307
308#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000309#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000310
311#endif
312
Tim Peters69232342001-08-30 05:16:13 +0000313static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000314imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000315{
Tim Peters69232342001-08-30 05:16:13 +0000316#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000317 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000318#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000319 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000320#endif
321}
322
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000323static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000324imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000325{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000326#ifdef WITH_THREAD
327 lock_import();
328#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000329 Py_INCREF(Py_None);
330 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000331}
332
333static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000334imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000335{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000336#ifdef WITH_THREAD
337 if (unlock_import() < 0) {
338 PyErr_SetString(PyExc_RuntimeError,
339 "not holding the import lock");
340 return NULL;
341 }
342#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000343 Py_INCREF(Py_None);
344 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000345}
346
Collin Winter276887b2007-03-12 16:11:39 +0000347static void
Neal Norwitz75c7c802007-03-13 05:31:38 +0000348imp_modules_reloading_clear(void)
Collin Winter276887b2007-03-12 16:11:39 +0000349{
350 PyInterpreterState *interp = PyThreadState_Get()->interp;
Neal Norwitz75c7c802007-03-13 05:31:38 +0000351 if (interp->modules_reloading != NULL)
352 PyDict_Clear(interp->modules_reloading);
Collin Winter276887b2007-03-12 16:11:39 +0000353}
354
Guido van Rossum25ce5661997-08-02 03:10:38 +0000355/* Helper for sys */
356
357PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000358PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000359{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000360 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000361 if (interp->modules == NULL)
362 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
363 return interp->modules;
364}
365
Guido van Rossum3f5da241990-12-20 15:06:42 +0000366
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000367/* List of names to clear in sys */
368static char* sys_deletes[] = {
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000369 "path", "argv", "ps1", "ps2", "exitfunc",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000370 "exc_type", "exc_value", "exc_traceback",
371 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000372 "path_hooks", "path_importer_cache", "meta_path",
Christian Heimes0d924432008-01-30 17:21:22 +0000373 /* misc stuff */
374 "flags", "float_info",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000375 NULL
376};
377
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000378static char* sys_files[] = {
379 "stdin", "__stdin__",
380 "stdout", "__stdout__",
381 "stderr", "__stderr__",
382 NULL
383};
384
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000385
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000386/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000387
Guido van Rossum3f5da241990-12-20 15:06:42 +0000388void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000389PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000390{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000391 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000392 char *name;
393 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000394 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000395 PyObject *modules = interp->modules;
396
397 if (modules == NULL)
398 return; /* Already done */
399
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000400 /* Delete some special variables first. These are common
401 places where user values hide and people complain when their
402 destructors fail. Since the modules containing them are
403 deleted *last* of all, they would come too late in the normal
404 destruction order. Sigh. */
405
406 value = PyDict_GetItemString(modules, "__builtin__");
407 if (value != NULL && PyModule_Check(value)) {
408 dict = PyModule_GetDict(value);
409 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000410 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000411 PyDict_SetItemString(dict, "_", Py_None);
412 }
413 value = PyDict_GetItemString(modules, "sys");
414 if (value != NULL && PyModule_Check(value)) {
415 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000416 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000417 dict = PyModule_GetDict(value);
418 for (p = sys_deletes; *p != NULL; p++) {
419 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000420 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000421 PyDict_SetItemString(dict, *p, Py_None);
422 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000423 for (p = sys_files; *p != NULL; p+=2) {
424 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000425 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000426 v = PyDict_GetItemString(dict, *(p+1));
427 if (v == NULL)
428 v = Py_None;
429 PyDict_SetItemString(dict, *p, v);
430 }
431 }
432
433 /* First, delete __main__ */
434 value = PyDict_GetItemString(modules, "__main__");
435 if (value != NULL && PyModule_Check(value)) {
436 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000437 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000438 _PyModule_Clear(value);
439 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000440 }
441
Guido van Rossum758eec01998-01-19 21:58:26 +0000442 /* The special treatment of __builtin__ here is because even
443 when it's not referenced as a module, its dictionary is
444 referenced by almost every module's __builtins__. Since
445 deleting a module clears its dictionary (even if there are
446 references left to it), we need to delete the __builtin__
447 module last. Likewise, we don't delete sys until the very
448 end because it is implicitly referenced (e.g. by print).
449
450 Also note that we 'delete' modules by replacing their entry
451 in the modules dict with None, rather than really deleting
452 them; this avoids a rehash of the modules dictionary and
453 also marks them as "non existent" so they won't be
454 re-imported. */
455
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000456 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000457 one (skipping __builtin__ and sys) and delete them */
458 do {
459 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000460 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000461 while (PyDict_Next(modules, &pos, &key, &value)) {
462 if (value->ob_refcnt != 1)
463 continue;
Guido van Rossum566373e1998-10-01 15:24:50 +0000464 if (PyString_Check(key) && PyModule_Check(value)) {
465 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000466 if (strcmp(name, "__builtin__") == 0)
467 continue;
468 if (strcmp(name, "sys") == 0)
469 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000470 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000471 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000472 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000473 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000474 PyDict_SetItem(modules, key, Py_None);
475 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000476 }
477 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000478 } while (ndone > 0);
479
Guido van Rossum758eec01998-01-19 21:58:26 +0000480 /* Next, delete all modules (still skipping __builtin__ and sys) */
481 pos = 0;
482 while (PyDict_Next(modules, &pos, &key, &value)) {
Guido van Rossum566373e1998-10-01 15:24:50 +0000483 if (PyString_Check(key) && PyModule_Check(value)) {
484 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000485 if (strcmp(name, "__builtin__") == 0)
486 continue;
487 if (strcmp(name, "sys") == 0)
488 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000489 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000490 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000491 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000492 PyDict_SetItem(modules, key, Py_None);
493 }
494 }
495
496 /* Next, delete sys and __builtin__ (in that order) */
497 value = PyDict_GetItemString(modules, "sys");
498 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000499 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000500 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000501 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000502 PyDict_SetItemString(modules, "sys", Py_None);
503 }
504 value = PyDict_GetItemString(modules, "__builtin__");
505 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000506 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000507 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000508 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000509 PyDict_SetItemString(modules, "__builtin__", Py_None);
510 }
511
512 /* Finally, clear and delete the modules directory */
513 PyDict_Clear(modules);
514 interp->modules = NULL;
515 Py_DECREF(modules);
Collin Winter276887b2007-03-12 16:11:39 +0000516 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000517}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000518
519
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000520/* Helper for pythonrun.c -- return magic number */
521
522long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000523PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000524{
Guido van Rossum96774c12000-05-01 20:19:08 +0000525 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000526}
527
528
Guido van Rossum25ce5661997-08-02 03:10:38 +0000529/* Magic for extension modules (built-in as well as dynamically
530 loaded). To prevent initializing an extension module more than
531 once, we keep a static dictionary 'extensions' keyed by module name
532 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000533 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000534 dictionary is stored by calling _PyImport_FixupExtension()
535 immediately after the module initialization function succeeds. A
536 copy can be retrieved from there by calling
537 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000538
Guido van Rossum79f25d91997-04-29 20:08:16 +0000539PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000540_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000541{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000542 PyObject *modules, *mod, *dict, *copy;
543 if (extensions == NULL) {
544 extensions = PyDict_New();
545 if (extensions == NULL)
546 return NULL;
547 }
548 modules = PyImport_GetModuleDict();
549 mod = PyDict_GetItemString(modules, name);
550 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000551 PyErr_Format(PyExc_SystemError,
552 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000553 return NULL;
554 }
555 dict = PyModule_GetDict(mod);
556 if (dict == NULL)
557 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000558 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559 if (copy == NULL)
560 return NULL;
561 PyDict_SetItemString(extensions, filename, copy);
562 Py_DECREF(copy);
563 return copy;
564}
565
566PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000567_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000568{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000569 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000570 if (extensions == NULL)
571 return NULL;
572 dict = PyDict_GetItemString(extensions, filename);
573 if (dict == NULL)
574 return NULL;
575 mod = PyImport_AddModule(name);
576 if (mod == NULL)
577 return NULL;
578 mdict = PyModule_GetDict(mod);
579 if (mdict == NULL)
580 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000581 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000582 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000583 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000584 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000585 name, filename);
586 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587}
588
589
590/* Get the module object corresponding to a module name.
591 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000592 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000593 Because the former action is most common, THIS DOES NOT RETURN A
594 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000595
Guido van Rossum79f25d91997-04-29 20:08:16 +0000596PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000597PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000598{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000599 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000600 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000601
Guido van Rossum25ce5661997-08-02 03:10:38 +0000602 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000603 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000604 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000605 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000606 if (m == NULL)
607 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000609 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000610 return NULL;
611 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000612 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000613
614 return m;
615}
616
Tim Peters1cd70172004-08-02 03:52:12 +0000617/* Remove name from sys.modules, if it's there. */
618static void
619_RemoveModule(const char *name)
620{
621 PyObject *modules = PyImport_GetModuleDict();
622 if (PyDict_GetItemString(modules, name) == NULL)
623 return;
624 if (PyDict_DelItemString(modules, name) < 0)
625 Py_FatalError("import: deleting existing key in"
626 "sys.modules failed");
627}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000628
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000629/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000630 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
631 * removed from sys.modules, to avoid leaving damaged module objects
632 * in sys.modules. The caller may wish to restore the original
633 * module object (if any) in this case; PyImport_ReloadModule is an
634 * example.
635 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000636PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000637PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000638{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000639 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
640}
641
642PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000643PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000644{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000645 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000646 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000647
Guido van Rossum79f25d91997-04-29 20:08:16 +0000648 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000649 if (m == NULL)
650 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000651 /* If the module is being reloaded, we get the old module back
652 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000653 d = PyModule_GetDict(m);
654 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
655 if (PyDict_SetItemString(d, "__builtins__",
656 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000657 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000658 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000659 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000660 v = NULL;
661 if (pathname != NULL) {
662 v = PyString_FromString(pathname);
663 if (v == NULL)
664 PyErr_Clear();
665 }
666 if (v == NULL) {
667 v = ((PyCodeObject *)co)->co_filename;
668 Py_INCREF(v);
669 }
670 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000671 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000672 Py_DECREF(v);
673
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000674 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000675 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000676 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000677 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000678
Guido van Rossum25ce5661997-08-02 03:10:38 +0000679 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000680 PyErr_Format(PyExc_ImportError,
681 "Loaded module %.200s not found in sys.modules",
682 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000683 return NULL;
684 }
685
Guido van Rossum79f25d91997-04-29 20:08:16 +0000686 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000687
688 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000689
690 error:
691 _RemoveModule(name);
692 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000693}
694
695
696/* Given a pathname for a Python source file, fill a buffer with the
697 pathname for the corresponding compiled file. Return the pathname
698 for the compiled file, or NULL if there's no space in the buffer.
699 Doesn't set an exception. */
700
701static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000702make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000703{
Tim Petersc1731372001-08-04 08:12:36 +0000704 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000705 if (len+2 > buflen)
706 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000707
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000708#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000709 /* Treat .pyw as if it were .py. The case of ".pyw" must match
710 that used in _PyImport_StandardFiletab. */
711 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
712 --len; /* pretend 'w' isn't there */
713#endif
714 memcpy(buf, pathname, len);
715 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
716 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000717
718 return buf;
719}
720
721
722/* Given a pathname for a Python source file, its time of last
723 modification, and a pathname for a compiled file, check whether the
724 compiled file represents the same version of the source. If so,
725 return a FILE pointer for the compiled file, positioned just after
726 the header; if not, return NULL.
727 Doesn't set an exception. */
728
729static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000730check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000731{
732 FILE *fp;
733 long magic;
734 long pyc_mtime;
735
736 fp = fopen(cpathname, "rb");
737 if (fp == NULL)
738 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000739 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000740 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000741 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000742 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000743 fclose(fp);
744 return NULL;
745 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000746 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000747 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000748 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000749 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000750 fclose(fp);
751 return NULL;
752 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000753 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000754 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000755 return fp;
756}
757
758
759/* Read a code object from a file and check it for validity */
760
Guido van Rossum79f25d91997-04-29 20:08:16 +0000761static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000762read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000763{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000764 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000765
Tim Petersd9b9ac82001-01-28 00:27:39 +0000766 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000767 if (co == NULL)
768 return NULL;
769 if (!PyCode_Check(co)) {
770 PyErr_Format(PyExc_ImportError,
771 "Non-code object in %.200s", cpathname);
772 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000773 return NULL;
774 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000775 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000776}
777
778
779/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000780 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000781
Guido van Rossum79f25d91997-04-29 20:08:16 +0000782static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000783load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000784{
785 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000786 PyCodeObject *co;
787 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000788
Guido van Rossum79f25d91997-04-29 20:08:16 +0000789 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000790 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000791 PyErr_Format(PyExc_ImportError,
792 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000793 return NULL;
794 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000795 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000796 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000797 if (co == NULL)
798 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000799 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000800 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000801 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000802 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000803 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000804
805 return m;
806}
807
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000808/* Parse a source file and return the corresponding code object */
809
Guido van Rossum79f25d91997-04-29 20:08:16 +0000810static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000811parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000812{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000813 PyCodeObject *co = NULL;
814 mod_ty mod;
Neal Norwitz2a399b02006-09-11 04:28:16 +0000815 PyArena *arena = PyArena_New();
816 if (arena == NULL)
817 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000818
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000819 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, 0,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000820 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000821 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000822 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000823 }
Neal Norwitz2a399b02006-09-11 04:28:16 +0000824 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000825 return co;
826}
827
828
Guido van Rossum55a83382000-09-20 20:31:38 +0000829/* Helper to open a bytecode file for writing in exclusive mode */
830
831static FILE *
832open_exclusive(char *filename)
833{
834#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
835 /* Use O_EXCL to avoid a race condition when another process tries to
836 write the same file. When that happens, our open() call fails,
837 which is just fine (since it's only a cache).
838 XXX If the file exists and is writable but the directory is not
839 writable, the file will never be written. Oh well.
840 */
841 int fd;
842 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000843 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
844#ifdef O_BINARY
845 |O_BINARY /* necessary for Windows */
846#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000847#ifdef __VMS
Martin v. Löwis18e16552006-02-15 17:27:45 +0000848 , 0666, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000849#else
Martin v. Löwis18e16552006-02-15 17:27:45 +0000850 , 0666
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000851#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000852 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000853 if (fd < 0)
854 return NULL;
855 return fdopen(fd, "wb");
856#else
857 /* Best we can do -- on Windows this can't happen anyway */
858 return fopen(filename, "wb");
859#endif
860}
861
862
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000863/* Write a compiled module to a file, placing the time of last
864 modification of its source into the header.
865 Errors are ignored, if a write error occurs an attempt is made to
866 remove the file. */
867
868static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000869write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000870{
871 FILE *fp;
872
Guido van Rossum55a83382000-09-20 20:31:38 +0000873 fp = open_exclusive(cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000874 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000875 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000876 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000877 "# can't create %s\n", cpathname);
878 return;
879 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000880 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000881 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000882 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
883 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000884 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000885 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000886 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000887 /* Don't keep partial file */
888 fclose(fp);
889 (void) unlink(cpathname);
890 return;
891 }
892 /* Now write the true mtime */
893 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000894 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000895 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000896 fflush(fp);
897 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000898 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000899 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000900}
901
902
903/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000904 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
905 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000906
Guido van Rossum79f25d91997-04-29 20:08:16 +0000907static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000908load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000909{
Fred Drake4c82b232000-06-30 16:18:57 +0000910 time_t mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000911 FILE *fpc;
912 char buf[MAXPATHLEN+1];
913 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000914 PyCodeObject *co;
915 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000916
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000917 mtime = PyOS_GetLastModificationTime(pathname, fp);
Neal Norwitz708e51a2005-10-03 04:48:15 +0000918 if (mtime == (time_t)(-1)) {
919 PyErr_Format(PyExc_RuntimeError,
920 "unable to get modification time from '%s'",
921 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000922 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000923 }
Fred Drake4c82b232000-06-30 16:18:57 +0000924#if SIZEOF_TIME_T > 4
925 /* Python's .pyc timestamp handling presumes that the timestamp fits
926 in 4 bytes. This will be fine until sometime in the year 2038,
927 when a 4-byte signed time_t will overflow.
928 */
929 if (mtime >> 32) {
930 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000931 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000932 return NULL;
933 }
934#endif
Tim Peters36515e22001-11-18 04:06:29 +0000935 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000936 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000937 if (cpathname != NULL &&
938 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000939 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000940 fclose(fpc);
941 if (co == NULL)
942 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000943 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000944 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000945 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000946 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000947 }
948 else {
949 co = parse_source_module(pathname, fp);
950 if (co == NULL)
951 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000952 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000953 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000954 name, pathname);
Georg Brandl2da0fce2008-01-07 17:09:35 +0000955 if (cpathname) {
956 PyObject *ro = PySys_GetObject("dont_write_bytecode");
957 if (ro == NULL || !PyObject_IsTrue(ro))
958 write_compiled_module(co, cpathname, mtime);
959 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000960 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000961 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000962 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000963
964 return m;
965}
966
967
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000968/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +0000969static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
970static struct filedescr *find_module(char *, char *, PyObject *,
971 char *, size_t, FILE **, PyObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000972static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000973
974/* Load a package and return its module object WITH INCREMENTED
975 REFERENCE COUNT */
976
977static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000978load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000979{
Tim Peters1cd70172004-08-02 03:52:12 +0000980 PyObject *m, *d;
981 PyObject *file = NULL;
982 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000983 int err;
984 char buf[MAXPATHLEN+1];
985 FILE *fp = NULL;
986 struct filedescr *fdp;
987
988 m = PyImport_AddModule(name);
989 if (m == NULL)
990 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000991 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000992 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000993 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000994 d = PyModule_GetDict(m);
995 file = PyString_FromString(pathname);
996 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000997 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000998 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +0000999 if (path == NULL)
1000 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001001 err = PyDict_SetItemString(d, "__file__", file);
1002 if (err == 0)
1003 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +00001004 if (err != 0)
1005 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001006 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00001007 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001008 if (fdp == NULL) {
1009 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1010 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +00001011 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001012 }
1013 else
1014 m = NULL;
1015 goto cleanup;
1016 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001017 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001018 if (fp != NULL)
1019 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00001020 goto cleanup;
1021
1022 error:
1023 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001024 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001025 Py_XDECREF(path);
1026 Py_XDECREF(file);
1027 return m;
1028}
1029
1030
1031/* Helper to test for built-in module */
1032
1033static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001034is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001035{
1036 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001037 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1038 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1039 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001040 return -1;
1041 else
1042 return 1;
1043 }
1044 }
1045 return 0;
1046}
1047
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001048
Just van Rossum52e14d62002-12-30 22:08:05 +00001049/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1050 possibly by fetching it from the path_importer_cache dict. If it
Brett Cannon94b69f62006-09-28 22:10:14 +00001051 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001052 that can handle the path item. Return None if no hook could;
1053 this tells our caller it should fall back to the builtin
1054 import mechanism. Cache the result in path_importer_cache.
1055 Returns a borrowed reference. */
1056
1057static PyObject *
1058get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1059 PyObject *p)
1060{
1061 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001062 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001063
1064 /* These conditions are the caller's responsibility: */
1065 assert(PyList_Check(path_hooks));
1066 assert(PyDict_Check(path_importer_cache));
1067
1068 nhooks = PyList_Size(path_hooks);
1069 if (nhooks < 0)
1070 return NULL; /* Shouldn't happen */
1071
1072 importer = PyDict_GetItem(path_importer_cache, p);
1073 if (importer != NULL)
1074 return importer;
1075
1076 /* set path_importer_cache[p] to None to avoid recursion */
1077 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1078 return NULL;
1079
1080 for (j = 0; j < nhooks; j++) {
1081 PyObject *hook = PyList_GetItem(path_hooks, j);
1082 if (hook == NULL)
1083 return NULL;
Georg Brandl684fd0c2006-05-25 19:15:31 +00001084 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001085 if (importer != NULL)
1086 break;
1087
1088 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1089 return NULL;
1090 }
1091 PyErr_Clear();
1092 }
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001093 if (importer == NULL) {
1094 importer = PyObject_CallFunctionObjArgs(
Nick Coghlan327a39b2007-11-18 11:56:28 +00001095 (PyObject *)&PyNullImporter_Type, p, NULL
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001096 );
1097 if (importer == NULL) {
1098 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1099 PyErr_Clear();
1100 return Py_None;
1101 }
1102 }
1103 }
1104 if (importer != NULL) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001105 int err = PyDict_SetItem(path_importer_cache, p, importer);
1106 Py_DECREF(importer);
1107 if (err != 0)
1108 return NULL;
1109 }
1110 return importer;
1111}
1112
Nick Coghlan327a39b2007-11-18 11:56:28 +00001113PyAPI_FUNC(PyObject *)
1114PyImport_GetImporter(PyObject *path) {
1115 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1116
1117 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1118 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1119 importer = get_path_importer(path_importer_cache,
1120 path_hooks, path);
1121 }
1122 }
1123 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1124 return importer;
1125}
1126
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001127/* Search the path (default sys.path) for a module. Return the
1128 corresponding filedescr struct, and (via return arguments) the
1129 pathname and an open file. Return NULL if the module is not found. */
1130
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001131#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001132extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001133 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001134#endif
1135
Martin v. Löwis18e16552006-02-15 17:27:45 +00001136static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001137static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001138static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001139
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001140static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001141find_module(char *fullname, char *subname, PyObject *path, char *buf,
1142 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001143{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001144 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001145 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001146 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001147 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001148 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001149 PyObject *path_hooks, *path_importer_cache;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001150#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001151 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001152#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001153 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1154 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1155 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001156 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001157#if defined(PYOS_OS2)
1158 size_t saved_len;
1159 size_t saved_namelen;
1160 char *saved_buf = NULL;
1161#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001162 if (p_loader != NULL)
1163 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001164
Just van Rossum52e14d62002-12-30 22:08:05 +00001165 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001166 PyErr_SetString(PyExc_OverflowError,
1167 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001168 return NULL;
1169 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001170 strcpy(name, subname);
1171
1172 /* sys.meta_path import hook */
1173 if (p_loader != NULL) {
1174 PyObject *meta_path;
1175
1176 meta_path = PySys_GetObject("meta_path");
1177 if (meta_path == NULL || !PyList_Check(meta_path)) {
1178 PyErr_SetString(PyExc_ImportError,
1179 "sys.meta_path must be a list of "
1180 "import hooks");
1181 return NULL;
1182 }
1183 Py_INCREF(meta_path); /* zap guard */
1184 npath = PyList_Size(meta_path);
1185 for (i = 0; i < npath; i++) {
1186 PyObject *loader;
1187 PyObject *hook = PyList_GetItem(meta_path, i);
1188 loader = PyObject_CallMethod(hook, "find_module",
1189 "sO", fullname,
1190 path != NULL ?
1191 path : Py_None);
1192 if (loader == NULL) {
1193 Py_DECREF(meta_path);
1194 return NULL; /* true error */
1195 }
1196 if (loader != Py_None) {
1197 /* a loader was found */
1198 *p_loader = loader;
1199 Py_DECREF(meta_path);
1200 return &importhookdescr;
1201 }
1202 Py_DECREF(loader);
1203 }
1204 Py_DECREF(meta_path);
1205 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001206
1207 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001208 /* The only type of submodule allowed inside a "frozen"
1209 package are other frozen modules or packages. */
Guido van Rossum0506a431998-08-11 15:07:39 +00001210 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1211 PyErr_SetString(PyExc_ImportError,
1212 "full frozen module name too long");
1213 return NULL;
1214 }
1215 strcpy(buf, PyString_AsString(path));
1216 strcat(buf, ".");
1217 strcat(buf, name);
1218 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001219 if (find_frozen(name) != NULL) {
1220 strcpy(buf, name);
1221 return &fd_frozen;
1222 }
1223 PyErr_Format(PyExc_ImportError,
1224 "No frozen submodule named %.200s", name);
1225 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001226 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001227 if (path == NULL) {
1228 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001229 strcpy(buf, name);
1230 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001231 }
Greg Ward201baee2001-10-04 14:52:06 +00001232 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001233 strcpy(buf, name);
1234 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001235 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001236
Guido van Rossumac279101996-08-22 23:10:58 +00001237#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001238 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1239 if (fp != NULL) {
1240 *p_fp = fp;
1241 return fdp;
1242 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001243#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001244 path = PySys_GetObject("path");
1245 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001246 if (path == NULL || !PyList_Check(path)) {
1247 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001248 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001249 return NULL;
1250 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001251
1252 path_hooks = PySys_GetObject("path_hooks");
1253 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1254 PyErr_SetString(PyExc_ImportError,
1255 "sys.path_hooks must be a list of "
1256 "import hooks");
1257 return NULL;
1258 }
1259 path_importer_cache = PySys_GetObject("path_importer_cache");
1260 if (path_importer_cache == NULL ||
1261 !PyDict_Check(path_importer_cache)) {
1262 PyErr_SetString(PyExc_ImportError,
1263 "sys.path_importer_cache must be a dict");
1264 return NULL;
1265 }
1266
Guido van Rossum79f25d91997-04-29 20:08:16 +00001267 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001268 namelen = strlen(name);
1269 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +00001270 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001271 PyObject *v = PyList_GetItem(path, i);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00001272 if (!v)
1273 return NULL;
Walter Dörwald3430d702002-06-17 10:43:59 +00001274#ifdef Py_USING_UNICODE
1275 if (PyUnicode_Check(v)) {
1276 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1277 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1278 if (copy == NULL)
1279 return NULL;
1280 v = copy;
1281 }
1282 else
1283#endif
Guido van Rossum79f25d91997-04-29 20:08:16 +00001284 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001285 continue;
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00001286 len = PyString_GET_SIZE(v);
Walter Dörwald3430d702002-06-17 10:43:59 +00001287 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1288 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001289 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001290 }
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00001291 strcpy(buf, PyString_AS_STRING(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001292 if (strlen(buf) != len) {
1293 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001294 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001295 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001296
1297 /* sys.path_hooks import hook */
1298 if (p_loader != NULL) {
1299 PyObject *importer;
1300
1301 importer = get_path_importer(path_importer_cache,
1302 path_hooks, v);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001303 if (importer == NULL) {
1304 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001305 return NULL;
Neal Norwitza4df11d2006-07-06 04:28:59 +00001306 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001307 /* Note: importer is a borrowed reference */
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001308 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001309 PyObject *loader;
1310 loader = PyObject_CallMethod(importer,
1311 "find_module",
1312 "s", fullname);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001313 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001314 if (loader == NULL)
1315 return NULL; /* error */
1316 if (loader != Py_None) {
1317 /* a loader was found */
1318 *p_loader = loader;
1319 return &importhookdescr;
1320 }
1321 Py_DECREF(loader);
Georg Brandlf4ef1162006-05-26 18:03:31 +00001322 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001323 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001324 }
Georg Brandlf4ef1162006-05-26 18:03:31 +00001325 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001326
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001327 if (len > 0 && buf[len-1] != SEP
1328#ifdef ALTSEP
1329 && buf[len-1] != ALTSEP
1330#endif
1331 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001332 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001333 strcpy(buf+len, name);
1334 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001335
1336 /* Check for package import (buf holds a directory name,
1337 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001338#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001339 if (stat(buf, &statbuf) == 0 && /* it exists */
1340 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001341 case_ok(buf, len, namelen, name)) { /* case matches */
1342 if (find_init_module(buf)) { /* and has __init__.py */
1343 Py_XDECREF(copy);
1344 return &fd_package;
1345 }
1346 else {
1347 char warnstr[MAXPATHLEN+80];
1348 sprintf(warnstr, "Not importing directory "
1349 "'%.*s': missing __init__.py",
1350 MAXPATHLEN, buf);
1351 if (PyErr_Warn(PyExc_ImportWarning,
1352 warnstr)) {
1353 Py_XDECREF(copy);
1354 return NULL;
1355 }
1356 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001357 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001358#else
1359 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001360#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001361 if (isdir(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001362 case_ok(buf, len, namelen, name)) {
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001363 if (find_init_module(buf)) {
1364 Py_XDECREF(copy);
1365 return &fd_package;
1366 }
1367 else {
1368 char warnstr[MAXPATHLEN+80];
1369 sprintf(warnstr, "Not importing directory "
1370 "'%.*s': missing __init__.py",
1371 MAXPATHLEN, buf);
1372 if (PyErr_Warn(PyExc_ImportWarning,
1373 warnstr)) {
1374 Py_XDECREF(copy);
1375 return NULL;
1376 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001377 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001378#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001379#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001380#if defined(PYOS_OS2)
1381 /* take a snapshot of the module spec for restoration
1382 * after the 8 character DLL hackery
1383 */
1384 saved_buf = strdup(buf);
1385 saved_len = len;
1386 saved_namelen = namelen;
1387#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001388 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Georg Brandladd36e52007-08-23 18:08:06 +00001389#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001390 /* OS/2 limits DLLs to 8 character names (w/o
1391 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001392 * so if the name is longer than that and its a
1393 * dynamically loaded module we're going to try,
1394 * truncate the name before trying
1395 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001396 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001397 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001398 const struct filedescr *scan;
1399 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001400 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001401 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001402 break;
1403 else
1404 scan++;
1405 }
1406 if (scan->suffix != NULL) {
1407 /* yes, so truncate the name */
1408 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001409 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001410 buf[len] = '\0';
1411 }
1412 }
1413#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001414 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001415 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001416 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001417 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001418 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001419 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001420 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001421 if (fp != NULL) {
1422 if (case_ok(buf, len, namelen, name))
1423 break;
1424 else { /* continue search */
1425 fclose(fp);
1426 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001427 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001428 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001429#if defined(PYOS_OS2)
1430 /* restore the saved snapshot */
1431 strcpy(buf, saved_buf);
1432 len = saved_len;
1433 namelen = saved_namelen;
1434#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001435 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001436#if defined(PYOS_OS2)
1437 /* don't need/want the module name snapshot anymore */
1438 if (saved_buf)
1439 {
1440 free(saved_buf);
1441 saved_buf = NULL;
1442 }
1443#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001444 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001445 if (fp != NULL)
1446 break;
1447 }
1448 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001449 PyErr_Format(PyExc_ImportError,
1450 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001451 return NULL;
1452 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001453 *p_fp = fp;
1454 return fdp;
1455}
1456
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001457/* Helpers for main.c
1458 * Find the source file corresponding to a named module
1459 */
1460struct filedescr *
1461_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1462 size_t buflen, FILE **p_fp, PyObject **p_loader)
1463{
1464 return find_module((char *) name, (char *) name, path,
1465 buf, buflen, p_fp, p_loader);
1466}
1467
1468PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1469{
1470 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1471}
1472
Martin v. Löwis18e16552006-02-15 17:27:45 +00001473/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001474 * The arguments here are tricky, best shown by example:
1475 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1476 * ^ ^ ^ ^
1477 * |--------------------- buf ---------------------|
1478 * |------------------- len ------------------|
1479 * |------ name -------|
1480 * |----- namelen -----|
1481 * buf is the full path, but len only counts up to (& exclusive of) the
1482 * extension. name is the module name, also exclusive of extension.
1483 *
1484 * We've already done a successful stat() or fopen() on buf, so know that
1485 * there's some match, possibly case-insensitive.
1486 *
Tim Peters50d8d372001-02-28 05:34:27 +00001487 * case_ok() is to return 1 if there's a case-sensitive match for
1488 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1489 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001490 *
Tim Peters50d8d372001-02-28 05:34:27 +00001491 * case_ok() is used to implement case-sensitive import semantics even
1492 * on platforms with case-insensitive filesystems. It's trivial to implement
1493 * for case-sensitive filesystems. It's pretty much a cross-platform
1494 * nightmare for systems with case-insensitive filesystems.
1495 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001496
Tim Peters50d8d372001-02-28 05:34:27 +00001497/* First we may need a pile of platform-specific header files; the sequence
1498 * of #if's here should match the sequence in the body of case_ok().
1499 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001500#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001501#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001502
Tim Peters50d8d372001-02-28 05:34:27 +00001503#elif defined(DJGPP)
1504#include <dir.h>
1505
Jason Tishler7961aa62005-05-20 00:56:54 +00001506#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001507#include <sys/types.h>
1508#include <dirent.h>
1509
Andrew MacIntyred9400542002-02-26 11:41:34 +00001510#elif defined(PYOS_OS2)
1511#define INCL_DOS
1512#define INCL_DOSERRORS
1513#define INCL_NOPMAPI
1514#include <os2.h>
1515
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001516#elif defined(RISCOS)
1517#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001518#endif
1519
Guido van Rossum0980bd91998-02-13 17:18:36 +00001520static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001521case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001522{
Tim Peters50d8d372001-02-28 05:34:27 +00001523/* Pick a platform-specific implementation; the sequence of #if's here should
1524 * match the sequence just above.
1525 */
1526
Jason Tishler7961aa62005-05-20 00:56:54 +00001527/* MS_WINDOWS */
1528#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001529 WIN32_FIND_DATA data;
1530 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001531
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001532 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001533 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001534
Guido van Rossum0980bd91998-02-13 17:18:36 +00001535 h = FindFirstFile(buf, &data);
1536 if (h == INVALID_HANDLE_VALUE) {
1537 PyErr_Format(PyExc_NameError,
1538 "Can't find file for module %.100s\n(filename %.300s)",
1539 name, buf);
1540 return 0;
1541 }
1542 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001543 return strncmp(data.cFileName, name, namelen) == 0;
1544
1545/* DJGPP */
1546#elif defined(DJGPP)
1547 struct ffblk ffblk;
1548 int done;
1549
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001550 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001551 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001552
1553 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1554 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001555 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001556 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001557 name, buf);
1558 return 0;
1559 }
Tim Peters50d8d372001-02-28 05:34:27 +00001560 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001561
Jason Tishler7961aa62005-05-20 00:56:54 +00001562/* new-fangled macintosh (macosx) or Cygwin */
1563#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001564 DIR *dirp;
1565 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001566 char dirname[MAXPATHLEN + 1];
1567 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001568
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001569 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001570 return 1;
1571
Tim Petersd1e87a82001-03-01 18:12:00 +00001572 /* Copy the dir component into dirname; substitute "." if empty */
1573 if (dirlen <= 0) {
1574 dirname[0] = '.';
1575 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001576 }
1577 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001578 assert(dirlen <= MAXPATHLEN);
1579 memcpy(dirname, buf, dirlen);
1580 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001581 }
1582 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001583 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001584 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001585 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001586 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001587 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001588#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001589 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001590#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001591 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001592#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001593 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001594 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001595 (void)closedir(dirp);
1596 return 1; /* Found */
1597 }
1598 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001599 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001600 }
Tim Peters430f5d42001-03-01 01:30:56 +00001601 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001602
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001603/* RISC OS */
1604#elif defined(RISCOS)
1605 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1606 char buf2[MAXPATHLEN+2];
1607 char *nameWithExt = buf+len-namelen;
1608 int canonlen;
1609 os_error *e;
1610
1611 if (Py_GETENV("PYTHONCASEOK") != NULL)
1612 return 1;
1613
1614 /* workaround:
1615 append wildcard, otherwise case of filename wouldn't be touched */
1616 strcpy(buf2, buf);
1617 strcat(buf2, "*");
1618
1619 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1620 canonlen = MAXPATHLEN+1-canonlen;
1621 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1622 return 0;
1623 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1624 return 1; /* match */
1625
1626 return 0;
1627
Andrew MacIntyred9400542002-02-26 11:41:34 +00001628/* OS/2 */
1629#elif defined(PYOS_OS2)
1630 HDIR hdir = 1;
1631 ULONG srchcnt = 1;
1632 FILEFINDBUF3 ffbuf;
1633 APIRET rc;
1634
Georg Brandlaed6c662008-01-07 17:25:53 +00001635 if (Py_GETENV("PYTHONCASEOK") != NULL)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001636 return 1;
1637
1638 rc = DosFindFirst(buf,
1639 &hdir,
1640 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1641 &ffbuf, sizeof(ffbuf),
1642 &srchcnt,
1643 FIL_STANDARD);
1644 if (rc != NO_ERROR)
1645 return 0;
1646 return strncmp(ffbuf.achName, name, namelen) == 0;
1647
Tim Peters50d8d372001-02-28 05:34:27 +00001648/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1649#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001650 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001651
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001652#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001653}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001654
Guido van Rossum0980bd91998-02-13 17:18:36 +00001655
Guido van Rossum197346f1997-10-31 18:38:52 +00001656#ifdef HAVE_STAT
1657/* Helper to look for __init__.py or __init__.py[co] in potential package */
1658static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001659find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001660{
Tim Peters0f9431f2001-07-05 03:47:53 +00001661 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001662 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001663 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001664 struct stat statbuf;
1665
Tim Peters0f9431f2001-07-05 03:47:53 +00001666/* For calling case_ok(buf, len, namelen, name):
1667 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1668 * ^ ^ ^ ^
1669 * |--------------------- buf ---------------------|
1670 * |------------------- len ------------------|
1671 * |------ name -------|
1672 * |----- namelen -----|
1673 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001674 if (save_len + 13 >= MAXPATHLEN)
1675 return 0;
1676 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001677 pname = buf + i;
1678 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001679 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001680 if (case_ok(buf,
1681 save_len + 9, /* len("/__init__") */
1682 8, /* len("__init__") */
1683 pname)) {
1684 buf[save_len] = '\0';
1685 return 1;
1686 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001687 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001688 i += strlen(pname);
1689 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001690 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001691 if (case_ok(buf,
1692 save_len + 9, /* len("/__init__") */
1693 8, /* len("__init__") */
1694 pname)) {
1695 buf[save_len] = '\0';
1696 return 1;
1697 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001698 }
1699 buf[save_len] = '\0';
1700 return 0;
1701}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001702
1703#else
1704
1705#ifdef RISCOS
1706static int
1707find_init_module(buf)
1708 char *buf;
1709{
1710 int save_len = strlen(buf);
1711 int i = save_len;
1712
1713 if (save_len + 13 >= MAXPATHLEN)
1714 return 0;
1715 buf[i++] = SEP;
1716 strcpy(buf+i, "__init__/py");
1717 if (isfile(buf)) {
1718 buf[save_len] = '\0';
1719 return 1;
1720 }
1721
1722 if (Py_OptimizeFlag)
1723 strcpy(buf+i, "o");
1724 else
1725 strcpy(buf+i, "c");
1726 if (isfile(buf)) {
1727 buf[save_len] = '\0';
1728 return 1;
1729 }
1730 buf[save_len] = '\0';
1731 return 0;
1732}
1733#endif /*RISCOS*/
1734
Guido van Rossum197346f1997-10-31 18:38:52 +00001735#endif /* HAVE_STAT */
1736
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001737
Tim Petersdbd9ba62000-07-09 03:09:57 +00001738static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001739
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001740/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001741 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001742
Guido van Rossum79f25d91997-04-29 20:08:16 +00001743static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001744load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001745{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001746 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001747 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001748 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001749
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001750 /* First check that there's an open file (if we need one) */
1751 switch (type) {
1752 case PY_SOURCE:
1753 case PY_COMPILED:
1754 if (fp == NULL) {
1755 PyErr_Format(PyExc_ValueError,
1756 "file object required for import (type code %d)",
1757 type);
1758 return NULL;
1759 }
1760 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001761
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001762 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001763
1764 case PY_SOURCE:
1765 m = load_source_module(name, buf, fp);
1766 break;
1767
1768 case PY_COMPILED:
1769 m = load_compiled_module(name, buf, fp);
1770 break;
1771
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001772#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001773 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001774 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001775 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001776#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001777
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001778 case PKG_DIRECTORY:
1779 m = load_package(name, buf);
1780 break;
1781
1782 case C_BUILTIN:
1783 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001784 if (buf != NULL && buf[0] != '\0')
1785 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001786 if (type == C_BUILTIN)
1787 err = init_builtin(name);
1788 else
1789 err = PyImport_ImportFrozenModule(name);
1790 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001791 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001792 if (err == 0) {
1793 PyErr_Format(PyExc_ImportError,
1794 "Purported %s module %.200s not found",
1795 type == C_BUILTIN ?
1796 "builtin" : "frozen",
1797 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001798 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001799 }
1800 modules = PyImport_GetModuleDict();
1801 m = PyDict_GetItemString(modules, name);
1802 if (m == NULL) {
1803 PyErr_Format(
1804 PyExc_ImportError,
1805 "%s module %.200s not properly initialized",
1806 type == C_BUILTIN ?
1807 "builtin" : "frozen",
1808 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001809 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001810 }
1811 Py_INCREF(m);
1812 break;
1813
Just van Rossum52e14d62002-12-30 22:08:05 +00001814 case IMP_HOOK: {
1815 if (loader == NULL) {
1816 PyErr_SetString(PyExc_ImportError,
1817 "import hook without loader");
1818 return NULL;
1819 }
1820 m = PyObject_CallMethod(loader, "load_module", "s", name);
1821 break;
1822 }
1823
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001824 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001825 PyErr_Format(PyExc_ImportError,
1826 "Don't know how to import %.200s (type code %d)",
1827 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001828 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001829
1830 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001831
1832 return m;
1833}
1834
1835
1836/* Initialize a built-in module.
Brett Cannon5a9aa4f2006-10-03 21:58:55 +00001837 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001838 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001839
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001840static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001841init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001842{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001843 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001844
Greg Ward201baee2001-10-04 14:52:06 +00001845 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001846 return 1;
1847
Guido van Rossum771c6c81997-10-31 18:37:24 +00001848 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001849 if (strcmp(name, p->name) == 0) {
1850 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001851 PyErr_Format(PyExc_ImportError,
1852 "Cannot re-init internal module %.200s",
1853 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001854 return -1;
1855 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001856 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001857 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001858 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001859 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001860 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001861 if (_PyImport_FixupExtension(name, name) == NULL)
1862 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001863 return 1;
1864 }
1865 }
1866 return 0;
1867}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001868
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001869
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001870/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001871
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001872static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001873find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001874{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001875 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001876
Guido van Rossum79f25d91997-04-29 20:08:16 +00001877 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001878 if (p->name == NULL)
1879 return NULL;
1880 if (strcmp(p->name, name) == 0)
1881 break;
1882 }
1883 return p;
1884}
1885
Guido van Rossum79f25d91997-04-29 20:08:16 +00001886static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001887get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001888{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001889 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001890 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001891
1892 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001893 PyErr_Format(PyExc_ImportError,
1894 "No such frozen object named %.200s",
1895 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001896 return NULL;
1897 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001898 if (p->code == NULL) {
1899 PyErr_Format(PyExc_ImportError,
1900 "Excluded frozen object named %.200s",
1901 name);
1902 return NULL;
1903 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001904 size = p->size;
1905 if (size < 0)
1906 size = -size;
1907 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001908}
1909
1910/* Initialize a frozen module.
1911 Return 1 for succes, 0 if the module is not found, and -1 with
1912 an exception set if the initialization failed.
1913 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001914
1915int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001916PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001917{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001918 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001919 PyObject *co;
1920 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001921 int ispackage;
1922 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001923
1924 if (p == NULL)
1925 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001926 if (p->code == NULL) {
1927 PyErr_Format(PyExc_ImportError,
1928 "Excluded frozen object named %.200s",
1929 name);
1930 return -1;
1931 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001932 size = p->size;
1933 ispackage = (size < 0);
1934 if (ispackage)
1935 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001936 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001937 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001938 name, ispackage ? " package" : "");
1939 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001940 if (co == NULL)
1941 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001942 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001943 PyErr_Format(PyExc_TypeError,
1944 "frozen object %.200s is not a code object",
1945 name);
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001946 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001947 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001948 if (ispackage) {
1949 /* Set __path__ to the package name */
1950 PyObject *d, *s;
1951 int err;
1952 m = PyImport_AddModule(name);
1953 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001954 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001955 d = PyModule_GetDict(m);
1956 s = PyString_InternFromString(name);
1957 if (s == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001958 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001959 err = PyDict_SetItemString(d, "__path__", s);
1960 Py_DECREF(s);
1961 if (err != 0)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001962 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001963 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001964 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001965 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001966 goto err_return;
1967 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001968 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001969 return 1;
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001970err_return:
1971 Py_DECREF(co);
1972 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001973}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001974
1975
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001976/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001977 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001978
Guido van Rossum79f25d91997-04-29 20:08:16 +00001979PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001980PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001981{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001982 PyObject *pname;
1983 PyObject *result;
1984
1985 pname = PyString_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001986 if (pname == NULL)
1987 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001988 result = PyImport_Import(pname);
1989 Py_DECREF(pname);
1990 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001991}
1992
Christian Heimes000a0742008-01-03 22:16:32 +00001993/* Import a module without blocking
1994 *
1995 * At first it tries to fetch the module from sys.modules. If the module was
1996 * never loaded before it loads it with PyImport_ImportModule() unless another
1997 * thread holds the import lock. In the latter case the function raises an
1998 * ImportError instead of blocking.
1999 *
2000 * Returns the module object with incremented ref count.
2001 */
2002PyObject *
2003PyImport_ImportModuleNoBlock(const char *name)
2004{
2005 PyObject *result;
2006 PyObject *modules;
2007 long me;
2008
2009 /* Try to get the module from sys.modules[name] */
2010 modules = PyImport_GetModuleDict();
2011 if (modules == NULL)
2012 return NULL;
2013
2014 result = PyDict_GetItemString(modules, name);
2015 if (result != NULL) {
2016 Py_INCREF(result);
2017 return result;
2018 }
2019 else {
2020 PyErr_Clear();
2021 }
2022
2023 /* check the import lock
2024 * me might be -1 but I ignore the error here, the lock function
2025 * takes care of the problem */
2026 me = PyThread_get_thread_ident();
2027 if (import_lock_thread == -1 || import_lock_thread == me) {
2028 /* no thread or me is holding the lock */
2029 return PyImport_ImportModule(name);
2030 }
2031 else {
2032 PyErr_Format(PyExc_ImportError,
2033 "Failed to import %.200s because the import lock"
2034 "is held by another thread.",
2035 name);
2036 return NULL;
2037 }
2038}
2039
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002040/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002041static PyObject *get_parent(PyObject *globals, char *buf,
2042 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002043static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002044 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002045static int mark_miss(char *name);
2046static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002047 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002048static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002049
2050/* The Magnum Opus of dotted-name import :-) */
2051
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002052static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002053import_module_level(char *name, PyObject *globals, PyObject *locals,
2054 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002055{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002056 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00002057 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002058 PyObject *parent, *head, *next, *tail;
2059
Christian Heimes3403f152008-01-09 19:56:33 +00002060 if (strchr(name, '/') != NULL
2061#ifdef MS_WINDOWS
2062 || strchr(name, '\\') != NULL
2063#endif
2064 ) {
2065 PyErr_SetString(PyExc_ImportError,
2066 "Import by filename is not supported.");
2067 return NULL;
2068 }
2069
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002070 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002071 if (parent == NULL)
2072 return NULL;
2073
2074 head = load_next(parent, Py_None, &name, buf, &buflen);
2075 if (head == NULL)
2076 return NULL;
2077
2078 tail = head;
2079 Py_INCREF(tail);
2080 while (name) {
2081 next = load_next(tail, tail, &name, buf, &buflen);
2082 Py_DECREF(tail);
2083 if (next == NULL) {
2084 Py_DECREF(head);
2085 return NULL;
2086 }
2087 tail = next;
2088 }
Thomas Wouters8ddab272006-04-04 16:17:02 +00002089 if (tail == Py_None) {
2090 /* If tail is Py_None, both get_parent and load_next found
2091 an empty module name: someone called __import__("") or
2092 doctored faulty bytecode */
Thomas Wouters4bdaa272006-04-05 13:39:37 +00002093 Py_DECREF(tail);
2094 Py_DECREF(head);
Thomas Wouters8ddab272006-04-04 16:17:02 +00002095 PyErr_SetString(PyExc_ValueError,
2096 "Empty module name");
2097 return NULL;
2098 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002099
2100 if (fromlist != NULL) {
2101 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2102 fromlist = NULL;
2103 }
2104
2105 if (fromlist == NULL) {
2106 Py_DECREF(tail);
2107 return head;
2108 }
2109
2110 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002111 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002112 Py_DECREF(tail);
2113 return NULL;
2114 }
2115
2116 return tail;
2117}
2118
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002119PyObject *
2120PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2121 PyObject *fromlist, int level)
2122{
2123 PyObject *result;
2124 lock_import();
2125 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002126 if (unlock_import() < 0) {
2127 Py_XDECREF(result);
2128 PyErr_SetString(PyExc_RuntimeError,
2129 "not holding the import lock");
2130 return NULL;
2131 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002132 return result;
2133}
2134
Fred Drake87590902004-05-28 20:21:36 +00002135/* Return the package that an import is being performed in. If globals comes
2136 from the module foo.bar.bat (not itself a package), this returns the
2137 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Georg Brandl5f6861d2006-05-28 21:57:35 +00002138 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002139
2140 The *name* of the returned package is returned in buf, with the length of
2141 the name in *p_buflen.
2142
2143 If globals doesn't come from a package or a module in a package, or a
2144 corresponding entry is not found in sys.modules, Py_None is returned.
2145*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002146static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002147get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002148{
2149 static PyObject *namestr = NULL;
2150 static PyObject *pathstr = NULL;
Nick Coghlanef01d822007-12-03 12:55:17 +00002151 static PyObject *pkgstr = NULL;
2152 PyObject *pkgname, *modname, *modpath, *modules, *parent;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002153
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002154 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002155 return Py_None;
2156
2157 if (namestr == NULL) {
2158 namestr = PyString_InternFromString("__name__");
2159 if (namestr == NULL)
2160 return NULL;
2161 }
2162 if (pathstr == NULL) {
2163 pathstr = PyString_InternFromString("__path__");
2164 if (pathstr == NULL)
2165 return NULL;
2166 }
Nick Coghlanef01d822007-12-03 12:55:17 +00002167 if (pkgstr == NULL) {
2168 pkgstr = PyString_InternFromString("__package__");
2169 if (pkgstr == NULL)
2170 return NULL;
2171 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002172
2173 *buf = '\0';
2174 *p_buflen = 0;
Nick Coghlanef01d822007-12-03 12:55:17 +00002175 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002176
Nick Coghlanef01d822007-12-03 12:55:17 +00002177 if ((pkgname != NULL) && (pkgname != Py_None)) {
2178 /* __package__ is set, so use it */
2179 Py_ssize_t len;
2180 if (!PyString_Check(pkgname)) {
2181 PyErr_SetString(PyExc_ValueError,
2182 "__package__ set to non-string");
2183 return NULL;
2184 }
2185 len = PyString_GET_SIZE(pkgname);
2186 if (len == 0) {
2187 if (level > 0) {
2188 PyErr_SetString(PyExc_ValueError,
2189 "Attempted relative import in non-package");
2190 return NULL;
2191 }
2192 return Py_None;
2193 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002194 if (len > MAXPATHLEN) {
2195 PyErr_SetString(PyExc_ValueError,
Nick Coghlanef01d822007-12-03 12:55:17 +00002196 "Package name too long");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002197 return NULL;
2198 }
Nick Coghlanef01d822007-12-03 12:55:17 +00002199 strcpy(buf, PyString_AS_STRING(pkgname));
2200 } else {
2201 /* __package__ not set, so figure it out and set it */
2202 modname = PyDict_GetItem(globals, namestr);
2203 if (modname == NULL || !PyString_Check(modname))
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002204 return Py_None;
Nick Coghlanef01d822007-12-03 12:55:17 +00002205
2206 modpath = PyDict_GetItem(globals, pathstr);
2207 if (modpath != NULL) {
2208 /* __path__ is set, so modname is already the package name */
2209 Py_ssize_t len = PyString_GET_SIZE(modname);
2210 int error;
2211 if (len > MAXPATHLEN) {
2212 PyErr_SetString(PyExc_ValueError,
2213 "Module name too long");
2214 return NULL;
2215 }
2216 strcpy(buf, PyString_AS_STRING(modname));
2217 error = PyDict_SetItem(globals, pkgstr, modname);
2218 if (error) {
2219 PyErr_SetString(PyExc_ValueError,
2220 "Could not set __package__");
2221 return NULL;
2222 }
2223 } else {
2224 /* Normal module, so work out the package name if any */
2225 char *start = PyString_AS_STRING(modname);
2226 char *lastdot = strrchr(start, '.');
2227 size_t len;
2228 int error;
2229 if (lastdot == NULL && level > 0) {
2230 PyErr_SetString(PyExc_ValueError,
2231 "Attempted relative import in non-package");
2232 return NULL;
2233 }
2234 if (lastdot == NULL) {
2235 error = PyDict_SetItem(globals, pkgstr, Py_None);
2236 if (error) {
2237 PyErr_SetString(PyExc_ValueError,
2238 "Could not set __package__");
2239 return NULL;
2240 }
2241 return Py_None;
2242 }
2243 len = lastdot - start;
2244 if (len >= MAXPATHLEN) {
2245 PyErr_SetString(PyExc_ValueError,
2246 "Module name too long");
2247 return NULL;
2248 }
2249 strncpy(buf, start, len);
2250 buf[len] = '\0';
2251 pkgname = PyString_FromString(buf);
2252 if (pkgname == NULL) {
2253 return NULL;
2254 }
2255 error = PyDict_SetItem(globals, pkgstr, pkgname);
2256 Py_DECREF(pkgname);
2257 if (error) {
2258 PyErr_SetString(PyExc_ValueError,
2259 "Could not set __package__");
2260 return NULL;
2261 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002262 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002263 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002264 while (--level > 0) {
2265 char *dot = strrchr(buf, '.');
2266 if (dot == NULL) {
2267 PyErr_SetString(PyExc_ValueError,
Georg Brandl98775df2006-09-06 06:09:31 +00002268 "Attempted relative import beyond "
2269 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002270 return NULL;
2271 }
2272 *dot = '\0';
2273 }
2274 *p_buflen = strlen(buf);
2275
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002276 modules = PyImport_GetModuleDict();
2277 parent = PyDict_GetItemString(modules, buf);
2278 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002279 PyErr_Format(PyExc_SystemError,
2280 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002281 return parent;
2282 /* We expect, but can't guarantee, if parent != None, that:
2283 - parent.__name__ == buf
2284 - parent.__dict__ is globals
2285 If this is violated... Who cares? */
2286}
2287
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002288/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002289static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002290load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002291 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002292{
2293 char *name = *p_name;
2294 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002295 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002296 char *p;
2297 PyObject *result;
2298
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002299 if (strlen(name) == 0) {
Thomas Wouters8ddab272006-04-04 16:17:02 +00002300 /* completely empty module name should only happen in
2301 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002302 Py_INCREF(mod);
2303 *p_name = NULL;
2304 return mod;
2305 }
2306
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002307 if (dot == NULL) {
2308 *p_name = NULL;
2309 len = strlen(name);
2310 }
2311 else {
2312 *p_name = dot+1;
2313 len = dot-name;
2314 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002315 if (len == 0) {
2316 PyErr_SetString(PyExc_ValueError,
2317 "Empty module name");
2318 return NULL;
2319 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002320
2321 p = buf + *p_buflen;
2322 if (p != buf)
2323 *p++ = '.';
2324 if (p+len-buf >= MAXPATHLEN) {
2325 PyErr_SetString(PyExc_ValueError,
2326 "Module name too long");
2327 return NULL;
2328 }
2329 strncpy(p, name, len);
2330 p[len] = '\0';
2331 *p_buflen = p+len-buf;
2332
2333 result = import_submodule(mod, p, buf);
2334 if (result == Py_None && altmod != mod) {
2335 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002336 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002337 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002338 if (result != NULL && result != Py_None) {
2339 if (mark_miss(buf) != 0) {
2340 Py_DECREF(result);
2341 return NULL;
2342 }
2343 strncpy(buf, name, len);
2344 buf[len] = '\0';
2345 *p_buflen = len;
2346 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002347 }
2348 if (result == NULL)
2349 return NULL;
2350
2351 if (result == Py_None) {
2352 Py_DECREF(result);
2353 PyErr_Format(PyExc_ImportError,
2354 "No module named %.200s", name);
2355 return NULL;
2356 }
2357
2358 return result;
2359}
2360
2361static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002362mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002363{
2364 PyObject *modules = PyImport_GetModuleDict();
2365 return PyDict_SetItemString(modules, name, Py_None);
2366}
2367
2368static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002369ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002370 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002371{
2372 int i;
2373
2374 if (!PyObject_HasAttrString(mod, "__path__"))
2375 return 1;
2376
2377 for (i = 0; ; i++) {
2378 PyObject *item = PySequence_GetItem(fromlist, i);
2379 int hasit;
2380 if (item == NULL) {
2381 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2382 PyErr_Clear();
2383 return 1;
2384 }
2385 return 0;
2386 }
2387 if (!PyString_Check(item)) {
2388 PyErr_SetString(PyExc_TypeError,
2389 "Item in ``from list'' not a string");
2390 Py_DECREF(item);
2391 return 0;
2392 }
2393 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002394 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002395 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002396 /* See if the package defines __all__ */
2397 if (recursive)
2398 continue; /* Avoid endless recursion */
2399 all = PyObject_GetAttrString(mod, "__all__");
2400 if (all == NULL)
2401 PyErr_Clear();
2402 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002403 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002404 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002405 if (!ret)
2406 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002407 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002408 continue;
2409 }
2410 hasit = PyObject_HasAttr(mod, item);
2411 if (!hasit) {
2412 char *subname = PyString_AS_STRING(item);
2413 PyObject *submod;
2414 char *p;
2415 if (buflen + strlen(subname) >= MAXPATHLEN) {
2416 PyErr_SetString(PyExc_ValueError,
2417 "Module name too long");
2418 Py_DECREF(item);
2419 return 0;
2420 }
2421 p = buf + buflen;
2422 *p++ = '.';
2423 strcpy(p, subname);
2424 submod = import_submodule(mod, subname, buf);
2425 Py_XDECREF(submod);
2426 if (submod == NULL) {
2427 Py_DECREF(item);
2428 return 0;
2429 }
2430 }
2431 Py_DECREF(item);
2432 }
2433
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002434 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002435}
2436
Neil Schemenauer00b09662003-06-16 21:03:07 +00002437static int
2438add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2439 PyObject *modules)
2440{
2441 if (mod == Py_None)
2442 return 1;
2443 /* Irrespective of the success of this load, make a
2444 reference to it in the parent package module. A copy gets
2445 saved in the modules dictionary under the full name, so get a
2446 reference from there, if need be. (The exception is when the
2447 load failed with a SyntaxError -- then there's no trace in
2448 sys.modules. In that case, of course, do nothing extra.) */
2449 if (submod == NULL) {
2450 submod = PyDict_GetItemString(modules, fullname);
2451 if (submod == NULL)
2452 return 1;
2453 }
2454 if (PyModule_Check(mod)) {
2455 /* We can't use setattr here since it can give a
2456 * spurious warning if the submodule name shadows a
2457 * builtin name */
2458 PyObject *dict = PyModule_GetDict(mod);
2459 if (!dict)
2460 return 0;
2461 if (PyDict_SetItemString(dict, subname, submod) < 0)
2462 return 0;
2463 }
2464 else {
2465 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2466 return 0;
2467 }
2468 return 1;
2469}
2470
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002471static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002472import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002473{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002474 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002475 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002476
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002477 /* Require:
2478 if mod == None: subname == fullname
2479 else: mod.__name__ + "." + subname == fullname
2480 */
2481
Tim Peters50d8d372001-02-28 05:34:27 +00002482 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002483 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002484 }
2485 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002486 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002487 char buf[MAXPATHLEN+1];
2488 struct filedescr *fdp;
2489 FILE *fp = NULL;
2490
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002491 if (mod == Py_None)
2492 path = NULL;
2493 else {
2494 path = PyObject_GetAttrString(mod, "__path__");
2495 if (path == NULL) {
2496 PyErr_Clear();
2497 Py_INCREF(Py_None);
2498 return Py_None;
2499 }
2500 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002501
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002502 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002503 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2504 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002505 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002506 if (fdp == NULL) {
2507 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2508 return NULL;
2509 PyErr_Clear();
2510 Py_INCREF(Py_None);
2511 return Py_None;
2512 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002513 m = load_module(fullname, fp, buf, fdp->type, loader);
2514 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002515 if (fp)
2516 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002517 if (!add_submodule(mod, m, fullname, subname, modules)) {
2518 Py_XDECREF(m);
2519 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002520 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002521 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002522
2523 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002524}
2525
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002526
2527/* Re-import a module of any kind and return its module object, WITH
2528 INCREMENTED REFERENCE COUNT */
2529
Guido van Rossum79f25d91997-04-29 20:08:16 +00002530PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002531PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002532{
Collin Winter47c52a82007-03-13 23:02:15 +00002533 PyInterpreterState *interp = PyThreadState_Get()->interp;
2534 PyObject *modules_reloading = interp->modules_reloading;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002535 PyObject *modules = PyImport_GetModuleDict();
Collin Winter276887b2007-03-12 16:11:39 +00002536 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002537 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002538 char buf[MAXPATHLEN+1];
2539 struct filedescr *fdp;
2540 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002541 PyObject *newm;
Collin Winter47c52a82007-03-13 23:02:15 +00002542
2543 if (modules_reloading == NULL) {
2544 Py_FatalError("PyImport_ReloadModule: "
Neal Norwitz2fca81c2007-05-30 04:53:41 +00002545 "no modules_reloading dictionary!");
Collin Winter47c52a82007-03-13 23:02:15 +00002546 return NULL;
2547 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002548
Guido van Rossum79f25d91997-04-29 20:08:16 +00002549 if (m == NULL || !PyModule_Check(m)) {
2550 PyErr_SetString(PyExc_TypeError,
2551 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002552 return NULL;
2553 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002554 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002555 if (name == NULL)
2556 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002557 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002558 PyErr_Format(PyExc_ImportError,
2559 "reload(): module %.200s not in sys.modules",
2560 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002561 return NULL;
2562 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002563 existing_m = PyDict_GetItemString(modules_reloading, name);
2564 if (existing_m != NULL) {
2565 /* Due to a recursive reload, this module is already
2566 being reloaded. */
2567 Py_INCREF(existing_m);
2568 return existing_m;
Collin Winter276887b2007-03-12 16:11:39 +00002569 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002570 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2571 return NULL;
Collin Winter276887b2007-03-12 16:11:39 +00002572
Guido van Rossum222ef561997-09-06 19:41:09 +00002573 subname = strrchr(name, '.');
2574 if (subname == NULL)
2575 subname = name;
2576 else {
2577 PyObject *parentname, *parent;
2578 parentname = PyString_FromStringAndSize(name, (subname-name));
Collin Winter276887b2007-03-12 16:11:39 +00002579 if (parentname == NULL) {
2580 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002581 return NULL;
Neal Norwitz75c7c802007-03-13 05:31:38 +00002582 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002583 parent = PyDict_GetItem(modules, parentname);
2584 if (parent == NULL) {
2585 PyErr_Format(PyExc_ImportError,
2586 "reload(): parent %.200s not in sys.modules",
Georg Brandl0c55f292005-09-14 06:56:20 +00002587 PyString_AS_STRING(parentname));
2588 Py_DECREF(parentname);
Neal Norwitz2fca81c2007-05-30 04:53:41 +00002589 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002590 return NULL;
2591 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002592 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002593 subname++;
2594 path = PyObject_GetAttrString(parent, "__path__");
2595 if (path == NULL)
2596 PyErr_Clear();
2597 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002598 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002599 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002600 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002601
2602 if (fdp == NULL) {
2603 Py_XDECREF(loader);
Collin Winter276887b2007-03-12 16:11:39 +00002604 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002605 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002606 }
2607
2608 newm = load_module(name, fp, buf, fdp->type, loader);
2609 Py_XDECREF(loader);
2610
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002611 if (fp)
2612 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002613 if (newm == NULL) {
2614 /* load_module probably removed name from modules because of
2615 * the error. Put back the original module object. We're
2616 * going to return NULL in this case regardless of whether
2617 * replacing name succeeds, so the return value is ignored.
2618 */
2619 PyDict_SetItemString(modules, name, m);
2620 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002621 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002622 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002623}
2624
2625
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002626/* Higher-level import emulator which emulates the "import" statement
2627 more accurately -- it invokes the __import__() function from the
2628 builtins of the current globals. This means that the import is
2629 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002630 environment, e.g. by "rexec".
2631 A dummy list ["__doc__"] is passed as the 4th argument so that
2632 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2633 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002634
2635PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002636PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002637{
2638 static PyObject *silly_list = NULL;
2639 static PyObject *builtins_str = NULL;
2640 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002641 PyObject *globals = NULL;
2642 PyObject *import = NULL;
2643 PyObject *builtins = NULL;
2644 PyObject *r = NULL;
2645
2646 /* Initialize constant string objects */
2647 if (silly_list == NULL) {
2648 import_str = PyString_InternFromString("__import__");
2649 if (import_str == NULL)
2650 return NULL;
2651 builtins_str = PyString_InternFromString("__builtins__");
2652 if (builtins_str == NULL)
2653 return NULL;
2654 silly_list = Py_BuildValue("[s]", "__doc__");
2655 if (silly_list == NULL)
2656 return NULL;
2657 }
2658
2659 /* Get the builtins from current globals */
2660 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002661 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002662 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002663 builtins = PyObject_GetItem(globals, builtins_str);
2664 if (builtins == NULL)
2665 goto err;
2666 }
2667 else {
2668 /* No globals -- use standard builtins, and fake globals */
2669 PyErr_Clear();
2670
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002671 builtins = PyImport_ImportModuleLevel("__builtin__",
2672 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002673 if (builtins == NULL)
2674 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002675 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2676 if (globals == NULL)
2677 goto err;
2678 }
2679
2680 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002681 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002682 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002683 if (import == NULL)
2684 PyErr_SetObject(PyExc_KeyError, import_str);
2685 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002686 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002687 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002688 if (import == NULL)
2689 goto err;
2690
Christian Heimes000a0742008-01-03 22:16:32 +00002691 /* Call the __import__ function with the proper argument list
2692 * Always use absolute import here. */
2693 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2694 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002695
2696 err:
2697 Py_XDECREF(globals);
2698 Py_XDECREF(builtins);
2699 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002700
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002701 return r;
2702}
2703
2704
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002705/* Module 'imp' provides Python access to the primitives used for
2706 importing modules.
2707*/
2708
Guido van Rossum79f25d91997-04-29 20:08:16 +00002709static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002710imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002711{
2712 char buf[4];
2713
Guido van Rossum96774c12000-05-01 20:19:08 +00002714 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2715 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2716 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2717 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002718
Guido van Rossum79f25d91997-04-29 20:08:16 +00002719 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002720}
2721
Guido van Rossum79f25d91997-04-29 20:08:16 +00002722static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002723imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002724{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002725 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002726 struct filedescr *fdp;
2727
Guido van Rossum79f25d91997-04-29 20:08:16 +00002728 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002729 if (list == NULL)
2730 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002731 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2732 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002733 fdp->suffix, fdp->mode, fdp->type);
2734 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002735 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002736 return NULL;
2737 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002738 if (PyList_Append(list, item) < 0) {
2739 Py_DECREF(list);
2740 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002741 return NULL;
2742 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002743 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002744 }
2745 return list;
2746}
2747
Guido van Rossum79f25d91997-04-29 20:08:16 +00002748static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002749call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002750{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002751 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002752 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002753 struct filedescr *fdp;
2754 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002755 FILE *fp = NULL;
2756
2757 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002758 if (path == Py_None)
2759 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002760 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002761 if (fdp == NULL)
2762 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002763 if (fp != NULL) {
2764 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2765 if (fob == NULL) {
2766 fclose(fp);
2767 return NULL;
2768 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002769 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002770 else {
2771 fob = Py_None;
2772 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002773 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002774 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002775 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002776 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002777 return ret;
2778}
2779
Guido van Rossum79f25d91997-04-29 20:08:16 +00002780static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002781imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002782{
2783 char *name;
2784 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002785 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002786 return NULL;
2787 return call_find_module(name, path);
2788}
2789
2790static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002791imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002792{
2793 char *name;
2794 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002795 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002796 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002797 return NULL;
2798 ret = init_builtin(name);
2799 if (ret < 0)
2800 return NULL;
2801 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002802 Py_INCREF(Py_None);
2803 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002804 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002805 m = PyImport_AddModule(name);
2806 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002807 return m;
2808}
2809
Guido van Rossum79f25d91997-04-29 20:08:16 +00002810static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002811imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002812{
2813 char *name;
2814 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002815 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002816 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002817 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002818 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002819 if (ret < 0)
2820 return NULL;
2821 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002822 Py_INCREF(Py_None);
2823 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002824 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002825 m = PyImport_AddModule(name);
2826 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002827 return m;
2828}
2829
Guido van Rossum79f25d91997-04-29 20:08:16 +00002830static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002831imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002832{
2833 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002834
Guido van Rossum43713e52000-02-29 13:59:29 +00002835 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002836 return NULL;
2837 return get_frozen_object(name);
2838}
2839
Guido van Rossum79f25d91997-04-29 20:08:16 +00002840static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002841imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002842{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002843 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002844 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002845 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002846 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002847}
2848
Guido van Rossum79f25d91997-04-29 20:08:16 +00002849static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002850imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002851{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002852 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002853 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002854 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002855 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002856 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002857 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002858}
2859
2860static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002861get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002862{
2863 FILE *fp;
2864 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002865 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002866 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002867 fp = fopen(pathname, mode);
2868 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002869 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002870 }
2871 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002872 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002873 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002874 PyErr_SetString(PyExc_ValueError,
2875 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002876 }
2877 return fp;
2878}
2879
Guido van Rossum79f25d91997-04-29 20:08:16 +00002880static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002881imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002882{
2883 char *name;
2884 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002885 PyObject *fob = NULL;
2886 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002887 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002888 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002889 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002890 return NULL;
2891 fp = get_file(pathname, fob, "rb");
2892 if (fp == NULL)
2893 return NULL;
2894 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002895 if (fob == NULL)
2896 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002897 return m;
2898}
2899
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002900#ifdef HAVE_DYNAMIC_LOADING
2901
Guido van Rossum79f25d91997-04-29 20:08:16 +00002902static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002903imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002904{
2905 char *name;
2906 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002907 PyObject *fob = NULL;
2908 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002909 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002910 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002911 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002912 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002913 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002914 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002915 if (fp == NULL)
2916 return NULL;
2917 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002918 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002919 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002920}
2921
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002922#endif /* HAVE_DYNAMIC_LOADING */
2923
Guido van Rossum79f25d91997-04-29 20:08:16 +00002924static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002925imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002926{
2927 char *name;
2928 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002929 PyObject *fob = NULL;
2930 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002931 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002932 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002933 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002934 return NULL;
2935 fp = get_file(pathname, fob, "r");
2936 if (fp == NULL)
2937 return NULL;
2938 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002939 if (fob == NULL)
2940 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002941 return m;
2942}
2943
Guido van Rossum79f25d91997-04-29 20:08:16 +00002944static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002945imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002946{
2947 char *name;
2948 PyObject *fob;
2949 char *pathname;
2950 char *suffix; /* Unused */
2951 char *mode;
2952 int type;
2953 FILE *fp;
2954
Guido van Rossum43713e52000-02-29 13:59:29 +00002955 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002956 &name, &fob, &pathname,
2957 &suffix, &mode, &type))
2958 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002959 if (*mode) {
2960 /* Mode must start with 'r' or 'U' and must not contain '+'.
2961 Implicit in this test is the assumption that the mode
2962 may contain other modifiers like 'b' or 't'. */
2963
2964 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002965 PyErr_Format(PyExc_ValueError,
2966 "invalid file open mode %.200s", mode);
2967 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002968 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002969 }
2970 if (fob == Py_None)
2971 fp = NULL;
2972 else {
2973 if (!PyFile_Check(fob)) {
2974 PyErr_SetString(PyExc_ValueError,
2975 "load_module arg#2 should be a file or None");
2976 return NULL;
2977 }
2978 fp = get_file(pathname, fob, mode);
2979 if (fp == NULL)
2980 return NULL;
2981 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002982 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002983}
2984
2985static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002986imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002987{
2988 char *name;
2989 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002990 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002991 return NULL;
2992 return load_package(name, pathname);
2993}
2994
2995static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002996imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002997{
2998 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002999 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003000 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003001 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003002}
3003
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003004/* Doc strings */
3005
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003006PyDoc_STRVAR(doc_imp,
3007"This module provides the components needed to build your own\n\
3008__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003009
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003010PyDoc_STRVAR(doc_find_module,
3011"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003012Search for a module. If path is omitted or None, search for a\n\
3013built-in, frozen or special module and continue search in sys.path.\n\
3014The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003015package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003016
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003017PyDoc_STRVAR(doc_load_module,
3018"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003019Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003020The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003021
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003022PyDoc_STRVAR(doc_get_magic,
3023"get_magic() -> string\n\
3024Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003025
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003026PyDoc_STRVAR(doc_get_suffixes,
3027"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003028Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003029that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003030
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003031PyDoc_STRVAR(doc_new_module,
3032"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003033Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003034The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003035
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003036PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003037"lock_held() -> boolean\n\
3038Return True if the import lock is currently held, else False.\n\
3039On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003040
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003041PyDoc_STRVAR(doc_acquire_lock,
3042"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003043Acquires the interpreter's import lock for the current thread.\n\
3044This lock should be used by import hooks to ensure thread-safety\n\
3045when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003046On platforms without threads, this function does nothing.");
3047
3048PyDoc_STRVAR(doc_release_lock,
3049"release_lock() -> None\n\
3050Release the interpreter's import lock.\n\
3051On platforms without threads, this function does nothing.");
3052
Guido van Rossum79f25d91997-04-29 20:08:16 +00003053static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003054 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3055 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3056 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3057 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3058 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3059 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3060 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3061 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003062 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00003063 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3064 {"init_builtin", imp_init_builtin, METH_VARARGS},
3065 {"init_frozen", imp_init_frozen, METH_VARARGS},
3066 {"is_builtin", imp_is_builtin, METH_VARARGS},
3067 {"is_frozen", imp_is_frozen, METH_VARARGS},
3068 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003069#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00003070 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003071#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00003072 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00003073 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003074 {NULL, NULL} /* sentinel */
3075};
3076
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003077static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003078setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003079{
3080 PyObject *v;
3081 int err;
3082
3083 v = PyInt_FromLong((long)value);
3084 err = PyDict_SetItemString(d, name, v);
3085 Py_XDECREF(v);
3086 return err;
3087}
3088
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003089typedef struct {
3090 PyObject_HEAD
3091} NullImporter;
3092
3093static int
3094NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3095{
3096 char *path;
Christian Heimescea681b2007-11-07 17:50:54 +00003097 Py_ssize_t pathlen;
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003098
3099 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3100 return -1;
3101
3102 if (!PyArg_ParseTuple(args, "s:NullImporter",
3103 &path))
3104 return -1;
3105
Christian Heimescea681b2007-11-07 17:50:54 +00003106 pathlen = strlen(path);
3107 if (pathlen == 0) {
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003108 PyErr_SetString(PyExc_ImportError, "empty pathname");
3109 return -1;
3110 } else {
3111#ifndef RISCOS
3112 struct stat statbuf;
3113 int rv;
3114
3115 rv = stat(path, &statbuf);
Christian Heimes004c1c12007-11-07 18:30:22 +00003116#ifdef MS_WINDOWS
3117 /* MS Windows stat() chokes on paths like C:\path\. Try to
3118 * recover *one* time by stripping off a trailing slash or
3119 * backslash. http://bugs.python.org/issue1293
3120 */
Christian Heimescea681b2007-11-07 17:50:54 +00003121 if (rv != 0 && pathlen <= MAXPATHLEN &&
3122 (path[pathlen-1] == '/' || path[pathlen-1] == '\\')) {
3123 char mangled[MAXPATHLEN+1];
3124
3125 strcpy(mangled, path);
3126 mangled[pathlen-1] = '\0';
3127 rv = stat(mangled, &statbuf);
3128 }
Christian Heimescea681b2007-11-07 17:50:54 +00003129#endif
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003130 if (rv == 0) {
3131 /* it exists */
3132 if (S_ISDIR(statbuf.st_mode)) {
3133 /* it's a directory */
3134 PyErr_SetString(PyExc_ImportError,
3135 "existing directory");
3136 return -1;
3137 }
3138 }
3139#else
3140 if (object_exists(path)) {
3141 /* it exists */
3142 if (isdir(path)) {
3143 /* it's a directory */
3144 PyErr_SetString(PyExc_ImportError,
3145 "existing directory");
3146 return -1;
3147 }
3148 }
3149#endif
3150 }
3151 return 0;
3152}
3153
3154static PyObject *
3155NullImporter_find_module(NullImporter *self, PyObject *args)
3156{
3157 Py_RETURN_NONE;
3158}
3159
3160static PyMethodDef NullImporter_methods[] = {
3161 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3162 "Always return None"
3163 },
3164 {NULL} /* Sentinel */
3165};
3166
3167
Nick Coghlan327a39b2007-11-18 11:56:28 +00003168PyTypeObject PyNullImporter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003169 PyVarObject_HEAD_INIT(NULL, 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003170 "imp.NullImporter", /*tp_name*/
3171 sizeof(NullImporter), /*tp_basicsize*/
3172 0, /*tp_itemsize*/
3173 0, /*tp_dealloc*/
3174 0, /*tp_print*/
3175 0, /*tp_getattr*/
3176 0, /*tp_setattr*/
3177 0, /*tp_compare*/
3178 0, /*tp_repr*/
3179 0, /*tp_as_number*/
3180 0, /*tp_as_sequence*/
3181 0, /*tp_as_mapping*/
3182 0, /*tp_hash */
3183 0, /*tp_call*/
3184 0, /*tp_str*/
3185 0, /*tp_getattro*/
3186 0, /*tp_setattro*/
3187 0, /*tp_as_buffer*/
3188 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3189 "Null importer object", /* tp_doc */
3190 0, /* tp_traverse */
3191 0, /* tp_clear */
3192 0, /* tp_richcompare */
3193 0, /* tp_weaklistoffset */
3194 0, /* tp_iter */
3195 0, /* tp_iternext */
3196 NullImporter_methods, /* tp_methods */
3197 0, /* tp_members */
3198 0, /* tp_getset */
3199 0, /* tp_base */
3200 0, /* tp_dict */
3201 0, /* tp_descr_get */
3202 0, /* tp_descr_set */
3203 0, /* tp_dictoffset */
3204 (initproc)NullImporter_init, /* tp_init */
3205 0, /* tp_alloc */
3206 PyType_GenericNew /* tp_new */
3207};
3208
3209
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003210PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003211initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003212{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003213 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003214
Nick Coghlan327a39b2007-11-18 11:56:28 +00003215 if (PyType_Ready(&PyNullImporter_Type) < 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003216 goto failure;
3217
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003218 m = Py_InitModule4("imp", imp_methods, doc_imp,
3219 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00003220 if (m == NULL)
3221 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003222 d = PyModule_GetDict(m);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00003223 if (d == NULL)
3224 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003225
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003226 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3227 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3228 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3229 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3230 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3231 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3232 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3233 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003234 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003235 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003236
Nick Coghlan327a39b2007-11-18 11:56:28 +00003237 Py_INCREF(&PyNullImporter_Type);
3238 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003239 failure:
3240 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003241}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003242
3243
Guido van Rossumb18618d2000-05-03 23:44:39 +00003244/* API for embedding applications that want to add their own entries
3245 to the table of built-in modules. This should normally be called
3246 *before* Py_Initialize(). When the table resize fails, -1 is
3247 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003248
3249 After a similar function by Just van Rossum. */
3250
3251int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003252PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003253{
3254 static struct _inittab *our_copy = NULL;
3255 struct _inittab *p;
3256 int i, n;
3257
3258 /* Count the number of entries in both tables */
3259 for (n = 0; newtab[n].name != NULL; n++)
3260 ;
3261 if (n == 0)
3262 return 0; /* Nothing to do */
3263 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3264 ;
3265
3266 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003267 p = our_copy;
3268 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003269 if (p == NULL)
3270 return -1;
3271
3272 /* Copy the tables into the new memory */
3273 if (our_copy != PyImport_Inittab)
3274 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3275 PyImport_Inittab = our_copy = p;
3276 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3277
3278 return 0;
3279}
3280
3281/* Shorthand to add a single entry given a name and a function */
3282
3283int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003284PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003285{
3286 struct _inittab newtab[2];
3287
3288 memset(newtab, '\0', sizeof newtab);
3289
3290 newtab[0].name = name;
3291 newtab[0].initfunc = initfunc;
3292
3293 return PyImport_ExtendInittab(newtab);
3294}
Anthony Baxterac6bd462006-04-13 02:06:09 +00003295
3296#ifdef __cplusplus
3297}
3298#endif