blob: 8e06cffa829f00cbd8687b0590a6a3f16d6de257 [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 *
Christian Heimes40346852008-02-23 17:52:07 +0000832open_exclusive(char *filename, mode_t mode)
Guido van Rossum55a83382000-09-20 20:31:38 +0000833{
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
Christian Heimes40346852008-02-23 17:52:07 +0000848 , mode, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000849#else
Christian Heimes40346852008-02-23 17:52:07 +0000850 , mode
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
Christian Heimes40346852008-02-23 17:52:07 +0000869write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000870{
871 FILE *fp;
Christian Heimes40346852008-02-23 17:52:07 +0000872 time_t mtime = srcstat->st_mtime;
873 mode_t mode = srcstat->st_mode;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000874
Christian Heimes40346852008-02-23 17:52:07 +0000875 fp = open_exclusive(cpathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000876 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000877 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000878 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000879 "# can't create %s\n", cpathname);
880 return;
881 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000882 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000883 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000884 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
885 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000886 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000887 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000888 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000889 /* Don't keep partial file */
890 fclose(fp);
891 (void) unlink(cpathname);
892 return;
893 }
894 /* Now write the true mtime */
895 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000896 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000897 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000898 fflush(fp);
899 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000900 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000901 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000902}
903
904
905/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000906 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
907 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000908
Guido van Rossum79f25d91997-04-29 20:08:16 +0000909static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000910load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000911{
Christian Heimes40346852008-02-23 17:52:07 +0000912 struct stat st;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000913 FILE *fpc;
914 char buf[MAXPATHLEN+1];
915 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000916 PyCodeObject *co;
917 PyObject *m;
Christian Heimes40346852008-02-23 17:52:07 +0000918
919 if (fstat(fileno(fp), &st) != 0) {
Neal Norwitz708e51a2005-10-03 04:48:15 +0000920 PyErr_Format(PyExc_RuntimeError,
Christian Heimes40346852008-02-23 17:52:07 +0000921 "unable to get file status from '%s'",
Neal Norwitz708e51a2005-10-03 04:48:15 +0000922 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000923 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000924 }
Fred Drake4c82b232000-06-30 16:18:57 +0000925#if SIZEOF_TIME_T > 4
926 /* Python's .pyc timestamp handling presumes that the timestamp fits
927 in 4 bytes. This will be fine until sometime in the year 2038,
928 when a 4-byte signed time_t will overflow.
929 */
Christian Heimes40346852008-02-23 17:52:07 +0000930 if (st.st_mtime >> 32) {
Fred Drake4c82b232000-06-30 16:18:57 +0000931 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000932 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000933 return NULL;
934 }
935#endif
Tim Peters36515e22001-11-18 04:06:29 +0000936 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000937 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000938 if (cpathname != NULL &&
Christian Heimes40346852008-02-23 17:52:07 +0000939 (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000940 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000941 fclose(fpc);
942 if (co == NULL)
943 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000944 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000945 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000946 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000947 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000948 }
949 else {
950 co = parse_source_module(pathname, fp);
951 if (co == NULL)
952 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000953 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000954 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000955 name, pathname);
Georg Brandl2da0fce2008-01-07 17:09:35 +0000956 if (cpathname) {
957 PyObject *ro = PySys_GetObject("dont_write_bytecode");
958 if (ro == NULL || !PyObject_IsTrue(ro))
Christian Heimes40346852008-02-23 17:52:07 +0000959 write_compiled_module(co, cpathname, &st);
Georg Brandl2da0fce2008-01-07 17:09:35 +0000960 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000961 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000962 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000963 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000964
965 return m;
966}
967
968
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000969/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +0000970static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
971static struct filedescr *find_module(char *, char *, PyObject *,
972 char *, size_t, FILE **, PyObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000973static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000974
975/* Load a package and return its module object WITH INCREMENTED
976 REFERENCE COUNT */
977
978static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000979load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000980{
Tim Peters1cd70172004-08-02 03:52:12 +0000981 PyObject *m, *d;
982 PyObject *file = NULL;
983 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000984 int err;
985 char buf[MAXPATHLEN+1];
986 FILE *fp = NULL;
987 struct filedescr *fdp;
988
989 m = PyImport_AddModule(name);
990 if (m == NULL)
991 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000992 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000993 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000994 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000995 d = PyModule_GetDict(m);
996 file = PyString_FromString(pathname);
997 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000998 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000999 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +00001000 if (path == NULL)
1001 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001002 err = PyDict_SetItemString(d, "__file__", file);
1003 if (err == 0)
1004 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +00001005 if (err != 0)
1006 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001007 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00001008 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001009 if (fdp == NULL) {
1010 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1011 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +00001012 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001013 }
1014 else
1015 m = NULL;
1016 goto cleanup;
1017 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001018 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001019 if (fp != NULL)
1020 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00001021 goto cleanup;
1022
1023 error:
1024 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001025 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001026 Py_XDECREF(path);
1027 Py_XDECREF(file);
1028 return m;
1029}
1030
1031
1032/* Helper to test for built-in module */
1033
1034static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001035is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001036{
1037 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001038 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1039 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1040 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001041 return -1;
1042 else
1043 return 1;
1044 }
1045 }
1046 return 0;
1047}
1048
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001049
Just van Rossum52e14d62002-12-30 22:08:05 +00001050/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1051 possibly by fetching it from the path_importer_cache dict. If it
Brett Cannon94b69f62006-09-28 22:10:14 +00001052 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001053 that can handle the path item. Return None if no hook could;
1054 this tells our caller it should fall back to the builtin
1055 import mechanism. Cache the result in path_importer_cache.
1056 Returns a borrowed reference. */
1057
1058static PyObject *
1059get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1060 PyObject *p)
1061{
1062 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001063 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001064
1065 /* These conditions are the caller's responsibility: */
1066 assert(PyList_Check(path_hooks));
1067 assert(PyDict_Check(path_importer_cache));
1068
1069 nhooks = PyList_Size(path_hooks);
1070 if (nhooks < 0)
1071 return NULL; /* Shouldn't happen */
1072
1073 importer = PyDict_GetItem(path_importer_cache, p);
1074 if (importer != NULL)
1075 return importer;
1076
1077 /* set path_importer_cache[p] to None to avoid recursion */
1078 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1079 return NULL;
1080
1081 for (j = 0; j < nhooks; j++) {
1082 PyObject *hook = PyList_GetItem(path_hooks, j);
1083 if (hook == NULL)
1084 return NULL;
Georg Brandl684fd0c2006-05-25 19:15:31 +00001085 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001086 if (importer != NULL)
1087 break;
1088
1089 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1090 return NULL;
1091 }
1092 PyErr_Clear();
1093 }
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001094 if (importer == NULL) {
1095 importer = PyObject_CallFunctionObjArgs(
Nick Coghlan327a39b2007-11-18 11:56:28 +00001096 (PyObject *)&PyNullImporter_Type, p, NULL
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001097 );
1098 if (importer == NULL) {
1099 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1100 PyErr_Clear();
1101 return Py_None;
1102 }
1103 }
1104 }
1105 if (importer != NULL) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001106 int err = PyDict_SetItem(path_importer_cache, p, importer);
1107 Py_DECREF(importer);
1108 if (err != 0)
1109 return NULL;
1110 }
1111 return importer;
1112}
1113
Nick Coghlan327a39b2007-11-18 11:56:28 +00001114PyAPI_FUNC(PyObject *)
1115PyImport_GetImporter(PyObject *path) {
1116 PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
1117
1118 if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
1119 if ((path_hooks = PySys_GetObject("path_hooks"))) {
1120 importer = get_path_importer(path_importer_cache,
1121 path_hooks, path);
1122 }
1123 }
1124 Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
1125 return importer;
1126}
1127
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001128/* Search the path (default sys.path) for a module. Return the
1129 corresponding filedescr struct, and (via return arguments) the
1130 pathname and an open file. Return NULL if the module is not found. */
1131
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001132#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001133extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001134 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001135#endif
1136
Martin v. Löwis18e16552006-02-15 17:27:45 +00001137static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001138static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001139static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001140
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001141static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001142find_module(char *fullname, char *subname, PyObject *path, char *buf,
1143 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001144{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001145 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001146 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001147 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001148 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001149 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001150 PyObject *path_hooks, *path_importer_cache;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001151#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001152 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001153#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001154 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1155 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1156 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001157 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001158#if defined(PYOS_OS2)
1159 size_t saved_len;
1160 size_t saved_namelen;
1161 char *saved_buf = NULL;
1162#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001163 if (p_loader != NULL)
1164 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001165
Just van Rossum52e14d62002-12-30 22:08:05 +00001166 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001167 PyErr_SetString(PyExc_OverflowError,
1168 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001169 return NULL;
1170 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001171 strcpy(name, subname);
1172
1173 /* sys.meta_path import hook */
1174 if (p_loader != NULL) {
1175 PyObject *meta_path;
1176
1177 meta_path = PySys_GetObject("meta_path");
1178 if (meta_path == NULL || !PyList_Check(meta_path)) {
1179 PyErr_SetString(PyExc_ImportError,
1180 "sys.meta_path must be a list of "
1181 "import hooks");
1182 return NULL;
1183 }
1184 Py_INCREF(meta_path); /* zap guard */
1185 npath = PyList_Size(meta_path);
1186 for (i = 0; i < npath; i++) {
1187 PyObject *loader;
1188 PyObject *hook = PyList_GetItem(meta_path, i);
1189 loader = PyObject_CallMethod(hook, "find_module",
1190 "sO", fullname,
1191 path != NULL ?
1192 path : Py_None);
1193 if (loader == NULL) {
1194 Py_DECREF(meta_path);
1195 return NULL; /* true error */
1196 }
1197 if (loader != Py_None) {
1198 /* a loader was found */
1199 *p_loader = loader;
1200 Py_DECREF(meta_path);
1201 return &importhookdescr;
1202 }
1203 Py_DECREF(loader);
1204 }
1205 Py_DECREF(meta_path);
1206 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001207
1208 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001209 /* The only type of submodule allowed inside a "frozen"
1210 package are other frozen modules or packages. */
Guido van Rossum0506a431998-08-11 15:07:39 +00001211 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1212 PyErr_SetString(PyExc_ImportError,
1213 "full frozen module name too long");
1214 return NULL;
1215 }
1216 strcpy(buf, PyString_AsString(path));
1217 strcat(buf, ".");
1218 strcat(buf, name);
1219 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001220 if (find_frozen(name) != NULL) {
1221 strcpy(buf, name);
1222 return &fd_frozen;
1223 }
1224 PyErr_Format(PyExc_ImportError,
1225 "No frozen submodule named %.200s", name);
1226 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001227 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001228 if (path == NULL) {
1229 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001230 strcpy(buf, name);
1231 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001232 }
Greg Ward201baee2001-10-04 14:52:06 +00001233 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001234 strcpy(buf, name);
1235 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001236 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001237
Guido van Rossumac279101996-08-22 23:10:58 +00001238#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001239 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1240 if (fp != NULL) {
1241 *p_fp = fp;
1242 return fdp;
1243 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001244#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001245 path = PySys_GetObject("path");
1246 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001247 if (path == NULL || !PyList_Check(path)) {
1248 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001249 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001250 return NULL;
1251 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001252
1253 path_hooks = PySys_GetObject("path_hooks");
1254 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1255 PyErr_SetString(PyExc_ImportError,
1256 "sys.path_hooks must be a list of "
1257 "import hooks");
1258 return NULL;
1259 }
1260 path_importer_cache = PySys_GetObject("path_importer_cache");
1261 if (path_importer_cache == NULL ||
1262 !PyDict_Check(path_importer_cache)) {
1263 PyErr_SetString(PyExc_ImportError,
1264 "sys.path_importer_cache must be a dict");
1265 return NULL;
1266 }
1267
Guido van Rossum79f25d91997-04-29 20:08:16 +00001268 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001269 namelen = strlen(name);
1270 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +00001271 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001272 PyObject *v = PyList_GetItem(path, i);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00001273 if (!v)
1274 return NULL;
Walter Dörwald3430d702002-06-17 10:43:59 +00001275#ifdef Py_USING_UNICODE
1276 if (PyUnicode_Check(v)) {
1277 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1278 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1279 if (copy == NULL)
1280 return NULL;
1281 v = copy;
1282 }
1283 else
1284#endif
Guido van Rossum79f25d91997-04-29 20:08:16 +00001285 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001286 continue;
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00001287 len = PyString_GET_SIZE(v);
Walter Dörwald3430d702002-06-17 10:43:59 +00001288 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1289 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001290 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001291 }
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00001292 strcpy(buf, PyString_AS_STRING(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001293 if (strlen(buf) != len) {
1294 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001295 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001296 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001297
1298 /* sys.path_hooks import hook */
1299 if (p_loader != NULL) {
1300 PyObject *importer;
1301
1302 importer = get_path_importer(path_importer_cache,
1303 path_hooks, v);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001304 if (importer == NULL) {
1305 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001306 return NULL;
Neal Norwitza4df11d2006-07-06 04:28:59 +00001307 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001308 /* Note: importer is a borrowed reference */
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001309 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001310 PyObject *loader;
1311 loader = PyObject_CallMethod(importer,
1312 "find_module",
1313 "s", fullname);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001314 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001315 if (loader == NULL)
1316 return NULL; /* error */
1317 if (loader != Py_None) {
1318 /* a loader was found */
1319 *p_loader = loader;
1320 return &importhookdescr;
1321 }
1322 Py_DECREF(loader);
Georg Brandlf4ef1162006-05-26 18:03:31 +00001323 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001324 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001325 }
Georg Brandlf4ef1162006-05-26 18:03:31 +00001326 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001327
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001328 if (len > 0 && buf[len-1] != SEP
1329#ifdef ALTSEP
1330 && buf[len-1] != ALTSEP
1331#endif
1332 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001333 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001334 strcpy(buf+len, name);
1335 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001336
1337 /* Check for package import (buf holds a directory name,
1338 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001339#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001340 if (stat(buf, &statbuf) == 0 && /* it exists */
1341 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001342 case_ok(buf, len, namelen, name)) { /* case matches */
1343 if (find_init_module(buf)) { /* and has __init__.py */
1344 Py_XDECREF(copy);
1345 return &fd_package;
1346 }
1347 else {
1348 char warnstr[MAXPATHLEN+80];
1349 sprintf(warnstr, "Not importing directory "
1350 "'%.*s': missing __init__.py",
1351 MAXPATHLEN, buf);
1352 if (PyErr_Warn(PyExc_ImportWarning,
1353 warnstr)) {
1354 Py_XDECREF(copy);
1355 return NULL;
1356 }
1357 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001358 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001359#else
1360 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001361#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001362 if (isdir(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001363 case_ok(buf, len, namelen, name)) {
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001364 if (find_init_module(buf)) {
1365 Py_XDECREF(copy);
1366 return &fd_package;
1367 }
1368 else {
1369 char warnstr[MAXPATHLEN+80];
1370 sprintf(warnstr, "Not importing directory "
1371 "'%.*s': missing __init__.py",
1372 MAXPATHLEN, buf);
1373 if (PyErr_Warn(PyExc_ImportWarning,
1374 warnstr)) {
1375 Py_XDECREF(copy);
1376 return NULL;
1377 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001378 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001379#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001380#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001381#if defined(PYOS_OS2)
1382 /* take a snapshot of the module spec for restoration
1383 * after the 8 character DLL hackery
1384 */
1385 saved_buf = strdup(buf);
1386 saved_len = len;
1387 saved_namelen = namelen;
1388#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001389 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Georg Brandladd36e52007-08-23 18:08:06 +00001390#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001391 /* OS/2 limits DLLs to 8 character names (w/o
1392 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001393 * so if the name is longer than that and its a
1394 * dynamically loaded module we're going to try,
1395 * truncate the name before trying
1396 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001397 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001398 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001399 const struct filedescr *scan;
1400 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001401 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001402 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001403 break;
1404 else
1405 scan++;
1406 }
1407 if (scan->suffix != NULL) {
1408 /* yes, so truncate the name */
1409 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001410 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001411 buf[len] = '\0';
1412 }
1413 }
1414#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001415 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001416 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001417 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001418 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001419 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001420 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001421 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001422 if (fp != NULL) {
1423 if (case_ok(buf, len, namelen, name))
1424 break;
1425 else { /* continue search */
1426 fclose(fp);
1427 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001428 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001429 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001430#if defined(PYOS_OS2)
1431 /* restore the saved snapshot */
1432 strcpy(buf, saved_buf);
1433 len = saved_len;
1434 namelen = saved_namelen;
1435#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001436 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001437#if defined(PYOS_OS2)
1438 /* don't need/want the module name snapshot anymore */
1439 if (saved_buf)
1440 {
1441 free(saved_buf);
1442 saved_buf = NULL;
1443 }
1444#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001445 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001446 if (fp != NULL)
1447 break;
1448 }
1449 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001450 PyErr_Format(PyExc_ImportError,
1451 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001452 return NULL;
1453 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001454 *p_fp = fp;
1455 return fdp;
1456}
1457
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001458/* Helpers for main.c
1459 * Find the source file corresponding to a named module
1460 */
1461struct filedescr *
1462_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1463 size_t buflen, FILE **p_fp, PyObject **p_loader)
1464{
1465 return find_module((char *) name, (char *) name, path,
1466 buf, buflen, p_fp, p_loader);
1467}
1468
1469PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1470{
1471 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1472}
1473
Martin v. Löwis18e16552006-02-15 17:27:45 +00001474/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001475 * The arguments here are tricky, best shown by example:
1476 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1477 * ^ ^ ^ ^
1478 * |--------------------- buf ---------------------|
1479 * |------------------- len ------------------|
1480 * |------ name -------|
1481 * |----- namelen -----|
1482 * buf is the full path, but len only counts up to (& exclusive of) the
1483 * extension. name is the module name, also exclusive of extension.
1484 *
1485 * We've already done a successful stat() or fopen() on buf, so know that
1486 * there's some match, possibly case-insensitive.
1487 *
Tim Peters50d8d372001-02-28 05:34:27 +00001488 * case_ok() is to return 1 if there's a case-sensitive match for
1489 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1490 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001491 *
Tim Peters50d8d372001-02-28 05:34:27 +00001492 * case_ok() is used to implement case-sensitive import semantics even
1493 * on platforms with case-insensitive filesystems. It's trivial to implement
1494 * for case-sensitive filesystems. It's pretty much a cross-platform
1495 * nightmare for systems with case-insensitive filesystems.
1496 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001497
Tim Peters50d8d372001-02-28 05:34:27 +00001498/* First we may need a pile of platform-specific header files; the sequence
1499 * of #if's here should match the sequence in the body of case_ok().
1500 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001501#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001502#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001503
Tim Peters50d8d372001-02-28 05:34:27 +00001504#elif defined(DJGPP)
1505#include <dir.h>
1506
Jason Tishler7961aa62005-05-20 00:56:54 +00001507#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001508#include <sys/types.h>
1509#include <dirent.h>
1510
Andrew MacIntyred9400542002-02-26 11:41:34 +00001511#elif defined(PYOS_OS2)
1512#define INCL_DOS
1513#define INCL_DOSERRORS
1514#define INCL_NOPMAPI
1515#include <os2.h>
1516
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001517#elif defined(RISCOS)
1518#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001519#endif
1520
Guido van Rossum0980bd91998-02-13 17:18:36 +00001521static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001522case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001523{
Tim Peters50d8d372001-02-28 05:34:27 +00001524/* Pick a platform-specific implementation; the sequence of #if's here should
1525 * match the sequence just above.
1526 */
1527
Jason Tishler7961aa62005-05-20 00:56:54 +00001528/* MS_WINDOWS */
1529#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001530 WIN32_FIND_DATA data;
1531 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001532
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001533 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001534 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001535
Guido van Rossum0980bd91998-02-13 17:18:36 +00001536 h = FindFirstFile(buf, &data);
1537 if (h == INVALID_HANDLE_VALUE) {
1538 PyErr_Format(PyExc_NameError,
1539 "Can't find file for module %.100s\n(filename %.300s)",
1540 name, buf);
1541 return 0;
1542 }
1543 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001544 return strncmp(data.cFileName, name, namelen) == 0;
1545
1546/* DJGPP */
1547#elif defined(DJGPP)
1548 struct ffblk ffblk;
1549 int done;
1550
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001551 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001552 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001553
1554 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1555 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001556 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001557 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001558 name, buf);
1559 return 0;
1560 }
Tim Peters50d8d372001-02-28 05:34:27 +00001561 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001562
Jason Tishler7961aa62005-05-20 00:56:54 +00001563/* new-fangled macintosh (macosx) or Cygwin */
1564#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001565 DIR *dirp;
1566 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001567 char dirname[MAXPATHLEN + 1];
1568 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001569
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001570 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001571 return 1;
1572
Tim Petersd1e87a82001-03-01 18:12:00 +00001573 /* Copy the dir component into dirname; substitute "." if empty */
1574 if (dirlen <= 0) {
1575 dirname[0] = '.';
1576 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001577 }
1578 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001579 assert(dirlen <= MAXPATHLEN);
1580 memcpy(dirname, buf, dirlen);
1581 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001582 }
1583 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001584 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001585 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001586 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001587 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001588 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001589#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001590 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001591#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001592 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001593#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001594 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001595 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001596 (void)closedir(dirp);
1597 return 1; /* Found */
1598 }
1599 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001600 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001601 }
Tim Peters430f5d42001-03-01 01:30:56 +00001602 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001603
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001604/* RISC OS */
1605#elif defined(RISCOS)
1606 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1607 char buf2[MAXPATHLEN+2];
1608 char *nameWithExt = buf+len-namelen;
1609 int canonlen;
1610 os_error *e;
1611
1612 if (Py_GETENV("PYTHONCASEOK") != NULL)
1613 return 1;
1614
1615 /* workaround:
1616 append wildcard, otherwise case of filename wouldn't be touched */
1617 strcpy(buf2, buf);
1618 strcat(buf2, "*");
1619
1620 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1621 canonlen = MAXPATHLEN+1-canonlen;
1622 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1623 return 0;
1624 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1625 return 1; /* match */
1626
1627 return 0;
1628
Andrew MacIntyred9400542002-02-26 11:41:34 +00001629/* OS/2 */
1630#elif defined(PYOS_OS2)
1631 HDIR hdir = 1;
1632 ULONG srchcnt = 1;
1633 FILEFINDBUF3 ffbuf;
1634 APIRET rc;
1635
Georg Brandlaed6c662008-01-07 17:25:53 +00001636 if (Py_GETENV("PYTHONCASEOK") != NULL)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001637 return 1;
1638
1639 rc = DosFindFirst(buf,
1640 &hdir,
1641 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1642 &ffbuf, sizeof(ffbuf),
1643 &srchcnt,
1644 FIL_STANDARD);
1645 if (rc != NO_ERROR)
1646 return 0;
1647 return strncmp(ffbuf.achName, name, namelen) == 0;
1648
Tim Peters50d8d372001-02-28 05:34:27 +00001649/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1650#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001651 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001652
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001653#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001654}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001655
Guido van Rossum0980bd91998-02-13 17:18:36 +00001656
Guido van Rossum197346f1997-10-31 18:38:52 +00001657#ifdef HAVE_STAT
1658/* Helper to look for __init__.py or __init__.py[co] in potential package */
1659static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001660find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001661{
Tim Peters0f9431f2001-07-05 03:47:53 +00001662 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001663 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001664 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001665 struct stat statbuf;
1666
Tim Peters0f9431f2001-07-05 03:47:53 +00001667/* For calling case_ok(buf, len, namelen, name):
1668 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1669 * ^ ^ ^ ^
1670 * |--------------------- buf ---------------------|
1671 * |------------------- len ------------------|
1672 * |------ name -------|
1673 * |----- namelen -----|
1674 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001675 if (save_len + 13 >= MAXPATHLEN)
1676 return 0;
1677 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001678 pname = buf + i;
1679 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001680 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001681 if (case_ok(buf,
1682 save_len + 9, /* len("/__init__") */
1683 8, /* len("__init__") */
1684 pname)) {
1685 buf[save_len] = '\0';
1686 return 1;
1687 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001688 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001689 i += strlen(pname);
1690 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001691 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001692 if (case_ok(buf,
1693 save_len + 9, /* len("/__init__") */
1694 8, /* len("__init__") */
1695 pname)) {
1696 buf[save_len] = '\0';
1697 return 1;
1698 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001699 }
1700 buf[save_len] = '\0';
1701 return 0;
1702}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001703
1704#else
1705
1706#ifdef RISCOS
1707static int
1708find_init_module(buf)
1709 char *buf;
1710{
1711 int save_len = strlen(buf);
1712 int i = save_len;
1713
1714 if (save_len + 13 >= MAXPATHLEN)
1715 return 0;
1716 buf[i++] = SEP;
1717 strcpy(buf+i, "__init__/py");
1718 if (isfile(buf)) {
1719 buf[save_len] = '\0';
1720 return 1;
1721 }
1722
1723 if (Py_OptimizeFlag)
1724 strcpy(buf+i, "o");
1725 else
1726 strcpy(buf+i, "c");
1727 if (isfile(buf)) {
1728 buf[save_len] = '\0';
1729 return 1;
1730 }
1731 buf[save_len] = '\0';
1732 return 0;
1733}
1734#endif /*RISCOS*/
1735
Guido van Rossum197346f1997-10-31 18:38:52 +00001736#endif /* HAVE_STAT */
1737
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001738
Tim Petersdbd9ba62000-07-09 03:09:57 +00001739static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001740
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001741/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001742 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001743
Guido van Rossum79f25d91997-04-29 20:08:16 +00001744static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001745load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001746{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001747 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001748 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001749 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001750
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001751 /* First check that there's an open file (if we need one) */
1752 switch (type) {
1753 case PY_SOURCE:
1754 case PY_COMPILED:
1755 if (fp == NULL) {
1756 PyErr_Format(PyExc_ValueError,
1757 "file object required for import (type code %d)",
1758 type);
1759 return NULL;
1760 }
1761 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001762
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001763 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001764
1765 case PY_SOURCE:
1766 m = load_source_module(name, buf, fp);
1767 break;
1768
1769 case PY_COMPILED:
1770 m = load_compiled_module(name, buf, fp);
1771 break;
1772
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001773#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001774 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001775 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001776 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001777#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001778
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001779 case PKG_DIRECTORY:
1780 m = load_package(name, buf);
1781 break;
1782
1783 case C_BUILTIN:
1784 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001785 if (buf != NULL && buf[0] != '\0')
1786 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001787 if (type == C_BUILTIN)
1788 err = init_builtin(name);
1789 else
1790 err = PyImport_ImportFrozenModule(name);
1791 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001792 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001793 if (err == 0) {
1794 PyErr_Format(PyExc_ImportError,
1795 "Purported %s module %.200s not found",
1796 type == C_BUILTIN ?
1797 "builtin" : "frozen",
1798 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001799 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001800 }
1801 modules = PyImport_GetModuleDict();
1802 m = PyDict_GetItemString(modules, name);
1803 if (m == NULL) {
1804 PyErr_Format(
1805 PyExc_ImportError,
1806 "%s module %.200s not properly initialized",
1807 type == C_BUILTIN ?
1808 "builtin" : "frozen",
1809 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001810 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001811 }
1812 Py_INCREF(m);
1813 break;
1814
Just van Rossum52e14d62002-12-30 22:08:05 +00001815 case IMP_HOOK: {
1816 if (loader == NULL) {
1817 PyErr_SetString(PyExc_ImportError,
1818 "import hook without loader");
1819 return NULL;
1820 }
1821 m = PyObject_CallMethod(loader, "load_module", "s", name);
1822 break;
1823 }
1824
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001825 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001826 PyErr_Format(PyExc_ImportError,
1827 "Don't know how to import %.200s (type code %d)",
1828 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001829 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001830
1831 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001832
1833 return m;
1834}
1835
1836
1837/* Initialize a built-in module.
Brett Cannon5a9aa4f2006-10-03 21:58:55 +00001838 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001839 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001840
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001841static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001842init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001843{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001844 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001845
Greg Ward201baee2001-10-04 14:52:06 +00001846 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001847 return 1;
1848
Guido van Rossum771c6c81997-10-31 18:37:24 +00001849 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001850 if (strcmp(name, p->name) == 0) {
1851 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001852 PyErr_Format(PyExc_ImportError,
1853 "Cannot re-init internal module %.200s",
1854 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001855 return -1;
1856 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001857 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001858 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001859 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001860 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001861 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001862 if (_PyImport_FixupExtension(name, name) == NULL)
1863 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001864 return 1;
1865 }
1866 }
1867 return 0;
1868}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001869
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001870
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001871/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001872
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001873static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001874find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001875{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001876 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001877
Guido van Rossum79f25d91997-04-29 20:08:16 +00001878 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001879 if (p->name == NULL)
1880 return NULL;
1881 if (strcmp(p->name, name) == 0)
1882 break;
1883 }
1884 return p;
1885}
1886
Guido van Rossum79f25d91997-04-29 20:08:16 +00001887static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001888get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001889{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001890 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001891 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001892
1893 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001894 PyErr_Format(PyExc_ImportError,
1895 "No such frozen object named %.200s",
1896 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001897 return NULL;
1898 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001899 if (p->code == NULL) {
1900 PyErr_Format(PyExc_ImportError,
1901 "Excluded frozen object named %.200s",
1902 name);
1903 return NULL;
1904 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001905 size = p->size;
1906 if (size < 0)
1907 size = -size;
1908 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001909}
1910
1911/* Initialize a frozen module.
1912 Return 1 for succes, 0 if the module is not found, and -1 with
1913 an exception set if the initialization failed.
1914 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001915
1916int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001917PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001918{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001919 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001920 PyObject *co;
1921 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001922 int ispackage;
1923 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001924
1925 if (p == NULL)
1926 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001927 if (p->code == NULL) {
1928 PyErr_Format(PyExc_ImportError,
1929 "Excluded frozen object named %.200s",
1930 name);
1931 return -1;
1932 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001933 size = p->size;
1934 ispackage = (size < 0);
1935 if (ispackage)
1936 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001937 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001938 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001939 name, ispackage ? " package" : "");
1940 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001941 if (co == NULL)
1942 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001943 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001944 PyErr_Format(PyExc_TypeError,
1945 "frozen object %.200s is not a code object",
1946 name);
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001947 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001948 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001949 if (ispackage) {
1950 /* Set __path__ to the package name */
1951 PyObject *d, *s;
1952 int err;
1953 m = PyImport_AddModule(name);
1954 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001955 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001956 d = PyModule_GetDict(m);
1957 s = PyString_InternFromString(name);
1958 if (s == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001959 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001960 err = PyDict_SetItemString(d, "__path__", s);
1961 Py_DECREF(s);
1962 if (err != 0)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001963 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001964 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001965 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001966 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001967 goto err_return;
1968 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001969 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001970 return 1;
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001971err_return:
1972 Py_DECREF(co);
1973 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001974}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001975
1976
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001977/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001978 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001979
Guido van Rossum79f25d91997-04-29 20:08:16 +00001980PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001981PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001982{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001983 PyObject *pname;
1984 PyObject *result;
1985
1986 pname = PyString_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001987 if (pname == NULL)
1988 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001989 result = PyImport_Import(pname);
1990 Py_DECREF(pname);
1991 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001992}
1993
Christian Heimes000a0742008-01-03 22:16:32 +00001994/* Import a module without blocking
1995 *
1996 * At first it tries to fetch the module from sys.modules. If the module was
1997 * never loaded before it loads it with PyImport_ImportModule() unless another
1998 * thread holds the import lock. In the latter case the function raises an
1999 * ImportError instead of blocking.
2000 *
2001 * Returns the module object with incremented ref count.
2002 */
2003PyObject *
2004PyImport_ImportModuleNoBlock(const char *name)
2005{
2006 PyObject *result;
2007 PyObject *modules;
2008 long me;
2009
2010 /* Try to get the module from sys.modules[name] */
2011 modules = PyImport_GetModuleDict();
2012 if (modules == NULL)
2013 return NULL;
2014
2015 result = PyDict_GetItemString(modules, name);
2016 if (result != NULL) {
2017 Py_INCREF(result);
2018 return result;
2019 }
2020 else {
2021 PyErr_Clear();
2022 }
2023
2024 /* check the import lock
2025 * me might be -1 but I ignore the error here, the lock function
2026 * takes care of the problem */
2027 me = PyThread_get_thread_ident();
2028 if (import_lock_thread == -1 || import_lock_thread == me) {
2029 /* no thread or me is holding the lock */
2030 return PyImport_ImportModule(name);
2031 }
2032 else {
2033 PyErr_Format(PyExc_ImportError,
2034 "Failed to import %.200s because the import lock"
2035 "is held by another thread.",
2036 name);
2037 return NULL;
2038 }
2039}
2040
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002041/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002042static PyObject *get_parent(PyObject *globals, char *buf,
2043 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002044static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002045 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002046static int mark_miss(char *name);
2047static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002048 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00002049static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002050
2051/* The Magnum Opus of dotted-name import :-) */
2052
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002053static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002054import_module_level(char *name, PyObject *globals, PyObject *locals,
2055 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002056{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002057 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00002058 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002059 PyObject *parent, *head, *next, *tail;
2060
Christian Heimes3403f152008-01-09 19:56:33 +00002061 if (strchr(name, '/') != NULL
2062#ifdef MS_WINDOWS
2063 || strchr(name, '\\') != NULL
2064#endif
2065 ) {
2066 PyErr_SetString(PyExc_ImportError,
2067 "Import by filename is not supported.");
2068 return NULL;
2069 }
2070
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002071 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002072 if (parent == NULL)
2073 return NULL;
2074
2075 head = load_next(parent, Py_None, &name, buf, &buflen);
2076 if (head == NULL)
2077 return NULL;
2078
2079 tail = head;
2080 Py_INCREF(tail);
2081 while (name) {
2082 next = load_next(tail, tail, &name, buf, &buflen);
2083 Py_DECREF(tail);
2084 if (next == NULL) {
2085 Py_DECREF(head);
2086 return NULL;
2087 }
2088 tail = next;
2089 }
Thomas Wouters8ddab272006-04-04 16:17:02 +00002090 if (tail == Py_None) {
2091 /* If tail is Py_None, both get_parent and load_next found
2092 an empty module name: someone called __import__("") or
2093 doctored faulty bytecode */
Thomas Wouters4bdaa272006-04-05 13:39:37 +00002094 Py_DECREF(tail);
2095 Py_DECREF(head);
Thomas Wouters8ddab272006-04-04 16:17:02 +00002096 PyErr_SetString(PyExc_ValueError,
2097 "Empty module name");
2098 return NULL;
2099 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002100
2101 if (fromlist != NULL) {
2102 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2103 fromlist = NULL;
2104 }
2105
2106 if (fromlist == NULL) {
2107 Py_DECREF(tail);
2108 return head;
2109 }
2110
2111 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002112 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002113 Py_DECREF(tail);
2114 return NULL;
2115 }
2116
2117 return tail;
2118}
2119
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002120PyObject *
2121PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2122 PyObject *fromlist, int level)
2123{
2124 PyObject *result;
2125 lock_import();
2126 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002127 if (unlock_import() < 0) {
2128 Py_XDECREF(result);
2129 PyErr_SetString(PyExc_RuntimeError,
2130 "not holding the import lock");
2131 return NULL;
2132 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002133 return result;
2134}
2135
Fred Drake87590902004-05-28 20:21:36 +00002136/* Return the package that an import is being performed in. If globals comes
2137 from the module foo.bar.bat (not itself a package), this returns the
2138 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Georg Brandl5f6861d2006-05-28 21:57:35 +00002139 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002140
2141 The *name* of the returned package is returned in buf, with the length of
2142 the name in *p_buflen.
2143
2144 If globals doesn't come from a package or a module in a package, or a
2145 corresponding entry is not found in sys.modules, Py_None is returned.
2146*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002147static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002148get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002149{
2150 static PyObject *namestr = NULL;
2151 static PyObject *pathstr = NULL;
Nick Coghlanef01d822007-12-03 12:55:17 +00002152 static PyObject *pkgstr = NULL;
2153 PyObject *pkgname, *modname, *modpath, *modules, *parent;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002154
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002155 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002156 return Py_None;
2157
2158 if (namestr == NULL) {
2159 namestr = PyString_InternFromString("__name__");
2160 if (namestr == NULL)
2161 return NULL;
2162 }
2163 if (pathstr == NULL) {
2164 pathstr = PyString_InternFromString("__path__");
2165 if (pathstr == NULL)
2166 return NULL;
2167 }
Nick Coghlanef01d822007-12-03 12:55:17 +00002168 if (pkgstr == NULL) {
2169 pkgstr = PyString_InternFromString("__package__");
2170 if (pkgstr == NULL)
2171 return NULL;
2172 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002173
2174 *buf = '\0';
2175 *p_buflen = 0;
Nick Coghlanef01d822007-12-03 12:55:17 +00002176 pkgname = PyDict_GetItem(globals, pkgstr);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002177
Nick Coghlanef01d822007-12-03 12:55:17 +00002178 if ((pkgname != NULL) && (pkgname != Py_None)) {
2179 /* __package__ is set, so use it */
2180 Py_ssize_t len;
2181 if (!PyString_Check(pkgname)) {
2182 PyErr_SetString(PyExc_ValueError,
2183 "__package__ set to non-string");
2184 return NULL;
2185 }
2186 len = PyString_GET_SIZE(pkgname);
2187 if (len == 0) {
2188 if (level > 0) {
2189 PyErr_SetString(PyExc_ValueError,
2190 "Attempted relative import in non-package");
2191 return NULL;
2192 }
2193 return Py_None;
2194 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002195 if (len > MAXPATHLEN) {
2196 PyErr_SetString(PyExc_ValueError,
Nick Coghlanef01d822007-12-03 12:55:17 +00002197 "Package name too long");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002198 return NULL;
2199 }
Nick Coghlanef01d822007-12-03 12:55:17 +00002200 strcpy(buf, PyString_AS_STRING(pkgname));
2201 } else {
2202 /* __package__ not set, so figure it out and set it */
2203 modname = PyDict_GetItem(globals, namestr);
2204 if (modname == NULL || !PyString_Check(modname))
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002205 return Py_None;
Nick Coghlanef01d822007-12-03 12:55:17 +00002206
2207 modpath = PyDict_GetItem(globals, pathstr);
2208 if (modpath != NULL) {
2209 /* __path__ is set, so modname is already the package name */
2210 Py_ssize_t len = PyString_GET_SIZE(modname);
2211 int error;
2212 if (len > MAXPATHLEN) {
2213 PyErr_SetString(PyExc_ValueError,
2214 "Module name too long");
2215 return NULL;
2216 }
2217 strcpy(buf, PyString_AS_STRING(modname));
2218 error = PyDict_SetItem(globals, pkgstr, modname);
2219 if (error) {
2220 PyErr_SetString(PyExc_ValueError,
2221 "Could not set __package__");
2222 return NULL;
2223 }
2224 } else {
2225 /* Normal module, so work out the package name if any */
2226 char *start = PyString_AS_STRING(modname);
2227 char *lastdot = strrchr(start, '.');
2228 size_t len;
2229 int error;
2230 if (lastdot == NULL && level > 0) {
2231 PyErr_SetString(PyExc_ValueError,
2232 "Attempted relative import in non-package");
2233 return NULL;
2234 }
2235 if (lastdot == NULL) {
2236 error = PyDict_SetItem(globals, pkgstr, Py_None);
2237 if (error) {
2238 PyErr_SetString(PyExc_ValueError,
2239 "Could not set __package__");
2240 return NULL;
2241 }
2242 return Py_None;
2243 }
2244 len = lastdot - start;
2245 if (len >= MAXPATHLEN) {
2246 PyErr_SetString(PyExc_ValueError,
2247 "Module name too long");
2248 return NULL;
2249 }
2250 strncpy(buf, start, len);
2251 buf[len] = '\0';
2252 pkgname = PyString_FromString(buf);
2253 if (pkgname == NULL) {
2254 return NULL;
2255 }
2256 error = PyDict_SetItem(globals, pkgstr, pkgname);
2257 Py_DECREF(pkgname);
2258 if (error) {
2259 PyErr_SetString(PyExc_ValueError,
2260 "Could not set __package__");
2261 return NULL;
2262 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002263 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002264 }
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002265 while (--level > 0) {
2266 char *dot = strrchr(buf, '.');
2267 if (dot == NULL) {
2268 PyErr_SetString(PyExc_ValueError,
Georg Brandl98775df2006-09-06 06:09:31 +00002269 "Attempted relative import beyond "
2270 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002271 return NULL;
2272 }
2273 *dot = '\0';
2274 }
2275 *p_buflen = strlen(buf);
2276
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002277 modules = PyImport_GetModuleDict();
2278 parent = PyDict_GetItemString(modules, buf);
2279 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002280 PyErr_Format(PyExc_SystemError,
2281 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002282 return parent;
2283 /* We expect, but can't guarantee, if parent != None, that:
2284 - parent.__name__ == buf
2285 - parent.__dict__ is globals
2286 If this is violated... Who cares? */
2287}
2288
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002289/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002290static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002291load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002292 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002293{
2294 char *name = *p_name;
2295 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002296 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002297 char *p;
2298 PyObject *result;
2299
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002300 if (strlen(name) == 0) {
Thomas Wouters8ddab272006-04-04 16:17:02 +00002301 /* completely empty module name should only happen in
2302 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002303 Py_INCREF(mod);
2304 *p_name = NULL;
2305 return mod;
2306 }
2307
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002308 if (dot == NULL) {
2309 *p_name = NULL;
2310 len = strlen(name);
2311 }
2312 else {
2313 *p_name = dot+1;
2314 len = dot-name;
2315 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002316 if (len == 0) {
2317 PyErr_SetString(PyExc_ValueError,
2318 "Empty module name");
2319 return NULL;
2320 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002321
2322 p = buf + *p_buflen;
2323 if (p != buf)
2324 *p++ = '.';
2325 if (p+len-buf >= MAXPATHLEN) {
2326 PyErr_SetString(PyExc_ValueError,
2327 "Module name too long");
2328 return NULL;
2329 }
2330 strncpy(p, name, len);
2331 p[len] = '\0';
2332 *p_buflen = p+len-buf;
2333
2334 result = import_submodule(mod, p, buf);
2335 if (result == Py_None && altmod != mod) {
2336 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002337 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002338 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002339 if (result != NULL && result != Py_None) {
2340 if (mark_miss(buf) != 0) {
2341 Py_DECREF(result);
2342 return NULL;
2343 }
2344 strncpy(buf, name, len);
2345 buf[len] = '\0';
2346 *p_buflen = len;
2347 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002348 }
2349 if (result == NULL)
2350 return NULL;
2351
2352 if (result == Py_None) {
2353 Py_DECREF(result);
2354 PyErr_Format(PyExc_ImportError,
2355 "No module named %.200s", name);
2356 return NULL;
2357 }
2358
2359 return result;
2360}
2361
2362static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002363mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002364{
2365 PyObject *modules = PyImport_GetModuleDict();
2366 return PyDict_SetItemString(modules, name, Py_None);
2367}
2368
2369static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002370ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002371 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002372{
2373 int i;
2374
2375 if (!PyObject_HasAttrString(mod, "__path__"))
2376 return 1;
2377
2378 for (i = 0; ; i++) {
2379 PyObject *item = PySequence_GetItem(fromlist, i);
2380 int hasit;
2381 if (item == NULL) {
2382 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2383 PyErr_Clear();
2384 return 1;
2385 }
2386 return 0;
2387 }
2388 if (!PyString_Check(item)) {
2389 PyErr_SetString(PyExc_TypeError,
2390 "Item in ``from list'' not a string");
2391 Py_DECREF(item);
2392 return 0;
2393 }
2394 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002395 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002396 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002397 /* See if the package defines __all__ */
2398 if (recursive)
2399 continue; /* Avoid endless recursion */
2400 all = PyObject_GetAttrString(mod, "__all__");
2401 if (all == NULL)
2402 PyErr_Clear();
2403 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002404 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002405 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002406 if (!ret)
2407 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002408 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002409 continue;
2410 }
2411 hasit = PyObject_HasAttr(mod, item);
2412 if (!hasit) {
2413 char *subname = PyString_AS_STRING(item);
2414 PyObject *submod;
2415 char *p;
2416 if (buflen + strlen(subname) >= MAXPATHLEN) {
2417 PyErr_SetString(PyExc_ValueError,
2418 "Module name too long");
2419 Py_DECREF(item);
2420 return 0;
2421 }
2422 p = buf + buflen;
2423 *p++ = '.';
2424 strcpy(p, subname);
2425 submod = import_submodule(mod, subname, buf);
2426 Py_XDECREF(submod);
2427 if (submod == NULL) {
2428 Py_DECREF(item);
2429 return 0;
2430 }
2431 }
2432 Py_DECREF(item);
2433 }
2434
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002435 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002436}
2437
Neil Schemenauer00b09662003-06-16 21:03:07 +00002438static int
2439add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2440 PyObject *modules)
2441{
2442 if (mod == Py_None)
2443 return 1;
2444 /* Irrespective of the success of this load, make a
2445 reference to it in the parent package module. A copy gets
2446 saved in the modules dictionary under the full name, so get a
2447 reference from there, if need be. (The exception is when the
2448 load failed with a SyntaxError -- then there's no trace in
2449 sys.modules. In that case, of course, do nothing extra.) */
2450 if (submod == NULL) {
2451 submod = PyDict_GetItemString(modules, fullname);
2452 if (submod == NULL)
2453 return 1;
2454 }
2455 if (PyModule_Check(mod)) {
2456 /* We can't use setattr here since it can give a
2457 * spurious warning if the submodule name shadows a
2458 * builtin name */
2459 PyObject *dict = PyModule_GetDict(mod);
2460 if (!dict)
2461 return 0;
2462 if (PyDict_SetItemString(dict, subname, submod) < 0)
2463 return 0;
2464 }
2465 else {
2466 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2467 return 0;
2468 }
2469 return 1;
2470}
2471
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002472static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002473import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002474{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002475 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002476 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002477
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002478 /* Require:
2479 if mod == None: subname == fullname
2480 else: mod.__name__ + "." + subname == fullname
2481 */
2482
Tim Peters50d8d372001-02-28 05:34:27 +00002483 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002484 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002485 }
2486 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002487 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002488 char buf[MAXPATHLEN+1];
2489 struct filedescr *fdp;
2490 FILE *fp = NULL;
2491
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002492 if (mod == Py_None)
2493 path = NULL;
2494 else {
2495 path = PyObject_GetAttrString(mod, "__path__");
2496 if (path == NULL) {
2497 PyErr_Clear();
2498 Py_INCREF(Py_None);
2499 return Py_None;
2500 }
2501 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002502
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002503 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002504 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2505 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002506 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002507 if (fdp == NULL) {
2508 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2509 return NULL;
2510 PyErr_Clear();
2511 Py_INCREF(Py_None);
2512 return Py_None;
2513 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002514 m = load_module(fullname, fp, buf, fdp->type, loader);
2515 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002516 if (fp)
2517 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002518 if (!add_submodule(mod, m, fullname, subname, modules)) {
2519 Py_XDECREF(m);
2520 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002521 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002522 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002523
2524 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002525}
2526
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002527
2528/* Re-import a module of any kind and return its module object, WITH
2529 INCREMENTED REFERENCE COUNT */
2530
Guido van Rossum79f25d91997-04-29 20:08:16 +00002531PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002532PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002533{
Collin Winter47c52a82007-03-13 23:02:15 +00002534 PyInterpreterState *interp = PyThreadState_Get()->interp;
2535 PyObject *modules_reloading = interp->modules_reloading;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002536 PyObject *modules = PyImport_GetModuleDict();
Collin Winter276887b2007-03-12 16:11:39 +00002537 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002538 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002539 char buf[MAXPATHLEN+1];
2540 struct filedescr *fdp;
2541 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002542 PyObject *newm;
Collin Winter47c52a82007-03-13 23:02:15 +00002543
2544 if (modules_reloading == NULL) {
2545 Py_FatalError("PyImport_ReloadModule: "
Neal Norwitz2fca81c2007-05-30 04:53:41 +00002546 "no modules_reloading dictionary!");
Collin Winter47c52a82007-03-13 23:02:15 +00002547 return NULL;
2548 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002549
Guido van Rossum79f25d91997-04-29 20:08:16 +00002550 if (m == NULL || !PyModule_Check(m)) {
2551 PyErr_SetString(PyExc_TypeError,
2552 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002553 return NULL;
2554 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002555 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002556 if (name == NULL)
2557 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002558 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002559 PyErr_Format(PyExc_ImportError,
2560 "reload(): module %.200s not in sys.modules",
2561 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002562 return NULL;
2563 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002564 existing_m = PyDict_GetItemString(modules_reloading, name);
2565 if (existing_m != NULL) {
2566 /* Due to a recursive reload, this module is already
2567 being reloaded. */
2568 Py_INCREF(existing_m);
2569 return existing_m;
Collin Winter276887b2007-03-12 16:11:39 +00002570 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002571 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2572 return NULL;
Collin Winter276887b2007-03-12 16:11:39 +00002573
Guido van Rossum222ef561997-09-06 19:41:09 +00002574 subname = strrchr(name, '.');
2575 if (subname == NULL)
2576 subname = name;
2577 else {
2578 PyObject *parentname, *parent;
2579 parentname = PyString_FromStringAndSize(name, (subname-name));
Collin Winter276887b2007-03-12 16:11:39 +00002580 if (parentname == NULL) {
2581 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002582 return NULL;
Neal Norwitz75c7c802007-03-13 05:31:38 +00002583 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002584 parent = PyDict_GetItem(modules, parentname);
2585 if (parent == NULL) {
2586 PyErr_Format(PyExc_ImportError,
2587 "reload(): parent %.200s not in sys.modules",
Georg Brandl0c55f292005-09-14 06:56:20 +00002588 PyString_AS_STRING(parentname));
2589 Py_DECREF(parentname);
Neal Norwitz2fca81c2007-05-30 04:53:41 +00002590 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002591 return NULL;
2592 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002593 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002594 subname++;
2595 path = PyObject_GetAttrString(parent, "__path__");
2596 if (path == NULL)
2597 PyErr_Clear();
2598 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002599 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002600 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002601 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002602
2603 if (fdp == NULL) {
2604 Py_XDECREF(loader);
Collin Winter276887b2007-03-12 16:11:39 +00002605 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002606 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002607 }
2608
2609 newm = load_module(name, fp, buf, fdp->type, loader);
2610 Py_XDECREF(loader);
2611
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002612 if (fp)
2613 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002614 if (newm == NULL) {
2615 /* load_module probably removed name from modules because of
2616 * the error. Put back the original module object. We're
2617 * going to return NULL in this case regardless of whether
2618 * replacing name succeeds, so the return value is ignored.
2619 */
2620 PyDict_SetItemString(modules, name, m);
2621 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002622 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002623 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002624}
2625
2626
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002627/* Higher-level import emulator which emulates the "import" statement
2628 more accurately -- it invokes the __import__() function from the
2629 builtins of the current globals. This means that the import is
2630 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002631 environment, e.g. by "rexec".
2632 A dummy list ["__doc__"] is passed as the 4th argument so that
2633 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2634 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002635
2636PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002637PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002638{
2639 static PyObject *silly_list = NULL;
2640 static PyObject *builtins_str = NULL;
2641 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002642 PyObject *globals = NULL;
2643 PyObject *import = NULL;
2644 PyObject *builtins = NULL;
2645 PyObject *r = NULL;
2646
2647 /* Initialize constant string objects */
2648 if (silly_list == NULL) {
2649 import_str = PyString_InternFromString("__import__");
2650 if (import_str == NULL)
2651 return NULL;
2652 builtins_str = PyString_InternFromString("__builtins__");
2653 if (builtins_str == NULL)
2654 return NULL;
2655 silly_list = Py_BuildValue("[s]", "__doc__");
2656 if (silly_list == NULL)
2657 return NULL;
2658 }
2659
2660 /* Get the builtins from current globals */
2661 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002662 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002663 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002664 builtins = PyObject_GetItem(globals, builtins_str);
2665 if (builtins == NULL)
2666 goto err;
2667 }
2668 else {
2669 /* No globals -- use standard builtins, and fake globals */
2670 PyErr_Clear();
2671
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002672 builtins = PyImport_ImportModuleLevel("__builtin__",
2673 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002674 if (builtins == NULL)
2675 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002676 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2677 if (globals == NULL)
2678 goto err;
2679 }
2680
2681 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002682 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002683 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002684 if (import == NULL)
2685 PyErr_SetObject(PyExc_KeyError, import_str);
2686 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002687 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002688 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002689 if (import == NULL)
2690 goto err;
2691
Christian Heimes000a0742008-01-03 22:16:32 +00002692 /* Call the __import__ function with the proper argument list
2693 * Always use absolute import here. */
2694 r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
2695 globals, silly_list, 0, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002696
2697 err:
2698 Py_XDECREF(globals);
2699 Py_XDECREF(builtins);
2700 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002701
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002702 return r;
2703}
2704
2705
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002706/* Module 'imp' provides Python access to the primitives used for
2707 importing modules.
2708*/
2709
Guido van Rossum79f25d91997-04-29 20:08:16 +00002710static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002711imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002712{
2713 char buf[4];
2714
Guido van Rossum96774c12000-05-01 20:19:08 +00002715 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2716 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2717 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2718 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002719
Guido van Rossum79f25d91997-04-29 20:08:16 +00002720 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002721}
2722
Guido van Rossum79f25d91997-04-29 20:08:16 +00002723static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002724imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002725{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002726 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002727 struct filedescr *fdp;
2728
Guido van Rossum79f25d91997-04-29 20:08:16 +00002729 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002730 if (list == NULL)
2731 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002732 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2733 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002734 fdp->suffix, fdp->mode, fdp->type);
2735 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002736 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002737 return NULL;
2738 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002739 if (PyList_Append(list, item) < 0) {
2740 Py_DECREF(list);
2741 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002742 return NULL;
2743 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002744 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002745 }
2746 return list;
2747}
2748
Guido van Rossum79f25d91997-04-29 20:08:16 +00002749static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002750call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002751{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002752 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002753 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002754 struct filedescr *fdp;
2755 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002756 FILE *fp = NULL;
2757
2758 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002759 if (path == Py_None)
2760 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002761 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002762 if (fdp == NULL)
2763 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002764 if (fp != NULL) {
2765 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2766 if (fob == NULL) {
2767 fclose(fp);
2768 return NULL;
2769 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002770 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002771 else {
2772 fob = Py_None;
2773 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002774 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002775 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002776 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002777 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002778 return ret;
2779}
2780
Guido van Rossum79f25d91997-04-29 20:08:16 +00002781static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002782imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002783{
2784 char *name;
2785 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002786 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002787 return NULL;
2788 return call_find_module(name, path);
2789}
2790
2791static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002792imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002793{
2794 char *name;
2795 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002796 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002797 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002798 return NULL;
2799 ret = init_builtin(name);
2800 if (ret < 0)
2801 return NULL;
2802 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002803 Py_INCREF(Py_None);
2804 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002805 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002806 m = PyImport_AddModule(name);
2807 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002808 return m;
2809}
2810
Guido van Rossum79f25d91997-04-29 20:08:16 +00002811static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002812imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002813{
2814 char *name;
2815 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002816 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002817 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002818 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002819 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002820 if (ret < 0)
2821 return NULL;
2822 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002823 Py_INCREF(Py_None);
2824 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002825 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002826 m = PyImport_AddModule(name);
2827 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002828 return m;
2829}
2830
Guido van Rossum79f25d91997-04-29 20:08:16 +00002831static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002832imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002833{
2834 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002835
Guido van Rossum43713e52000-02-29 13:59:29 +00002836 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002837 return NULL;
2838 return get_frozen_object(name);
2839}
2840
Guido van Rossum79f25d91997-04-29 20:08:16 +00002841static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002842imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002843{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002844 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002845 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002846 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002847 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002848}
2849
Guido van Rossum79f25d91997-04-29 20:08:16 +00002850static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002851imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002852{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002853 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002854 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002855 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002856 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002857 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002858 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002859}
2860
2861static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002862get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002863{
2864 FILE *fp;
2865 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002866 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002867 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002868 fp = fopen(pathname, mode);
2869 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002870 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002871 }
2872 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002873 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002874 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002875 PyErr_SetString(PyExc_ValueError,
2876 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002877 }
2878 return fp;
2879}
2880
Guido van Rossum79f25d91997-04-29 20:08:16 +00002881static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002882imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002883{
2884 char *name;
2885 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002886 PyObject *fob = NULL;
2887 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002888 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002889 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002890 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002891 return NULL;
2892 fp = get_file(pathname, fob, "rb");
2893 if (fp == NULL)
2894 return NULL;
2895 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002896 if (fob == NULL)
2897 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002898 return m;
2899}
2900
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002901#ifdef HAVE_DYNAMIC_LOADING
2902
Guido van Rossum79f25d91997-04-29 20:08:16 +00002903static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002904imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002905{
2906 char *name;
2907 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002908 PyObject *fob = NULL;
2909 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002910 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002911 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002912 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002913 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002914 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002915 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002916 if (fp == NULL)
2917 return NULL;
2918 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002919 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002920 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002921}
2922
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002923#endif /* HAVE_DYNAMIC_LOADING */
2924
Guido van Rossum79f25d91997-04-29 20:08:16 +00002925static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002926imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002927{
2928 char *name;
2929 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002930 PyObject *fob = NULL;
2931 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002932 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002933 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002934 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002935 return NULL;
2936 fp = get_file(pathname, fob, "r");
2937 if (fp == NULL)
2938 return NULL;
2939 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002940 if (fob == NULL)
2941 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002942 return m;
2943}
2944
Guido van Rossum79f25d91997-04-29 20:08:16 +00002945static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002946imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002947{
2948 char *name;
2949 PyObject *fob;
2950 char *pathname;
2951 char *suffix; /* Unused */
2952 char *mode;
2953 int type;
2954 FILE *fp;
2955
Guido van Rossum43713e52000-02-29 13:59:29 +00002956 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002957 &name, &fob, &pathname,
2958 &suffix, &mode, &type))
2959 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002960 if (*mode) {
2961 /* Mode must start with 'r' or 'U' and must not contain '+'.
2962 Implicit in this test is the assumption that the mode
2963 may contain other modifiers like 'b' or 't'. */
2964
2965 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002966 PyErr_Format(PyExc_ValueError,
2967 "invalid file open mode %.200s", mode);
2968 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002969 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002970 }
2971 if (fob == Py_None)
2972 fp = NULL;
2973 else {
2974 if (!PyFile_Check(fob)) {
2975 PyErr_SetString(PyExc_ValueError,
2976 "load_module arg#2 should be a file or None");
2977 return NULL;
2978 }
2979 fp = get_file(pathname, fob, mode);
2980 if (fp == NULL)
2981 return NULL;
2982 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002983 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002984}
2985
2986static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002987imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002988{
2989 char *name;
2990 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002991 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002992 return NULL;
2993 return load_package(name, pathname);
2994}
2995
2996static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002997imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002998{
2999 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00003000 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003001 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003002 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003003}
3004
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003005/* Doc strings */
3006
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003007PyDoc_STRVAR(doc_imp,
3008"This module provides the components needed to build your own\n\
3009__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003010
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003011PyDoc_STRVAR(doc_find_module,
3012"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003013Search for a module. If path is omitted or None, search for a\n\
3014built-in, frozen or special module and continue search in sys.path.\n\
3015The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003016package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003017
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003018PyDoc_STRVAR(doc_load_module,
3019"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003020Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003021The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003022
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003023PyDoc_STRVAR(doc_get_magic,
3024"get_magic() -> string\n\
3025Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003026
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003027PyDoc_STRVAR(doc_get_suffixes,
3028"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003029Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003030that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003031
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003032PyDoc_STRVAR(doc_new_module,
3033"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003034Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003035The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003036
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00003037PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00003038"lock_held() -> boolean\n\
3039Return True if the import lock is currently held, else False.\n\
3040On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00003041
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003042PyDoc_STRVAR(doc_acquire_lock,
3043"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00003044Acquires the interpreter's import lock for the current thread.\n\
3045This lock should be used by import hooks to ensure thread-safety\n\
3046when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00003047On platforms without threads, this function does nothing.");
3048
3049PyDoc_STRVAR(doc_release_lock,
3050"release_lock() -> None\n\
3051Release the interpreter's import lock.\n\
3052On platforms without threads, this function does nothing.");
3053
Guido van Rossum79f25d91997-04-29 20:08:16 +00003054static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00003055 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
3056 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
3057 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
3058 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
3059 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
3060 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
3061 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
3062 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003063 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00003064 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
3065 {"init_builtin", imp_init_builtin, METH_VARARGS},
3066 {"init_frozen", imp_init_frozen, METH_VARARGS},
3067 {"is_builtin", imp_is_builtin, METH_VARARGS},
3068 {"is_frozen", imp_is_frozen, METH_VARARGS},
3069 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003070#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00003071 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00003072#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00003073 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00003074 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003075 {NULL, NULL} /* sentinel */
3076};
3077
Guido van Rossum1a8791e1998-08-04 22:46:29 +00003078static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003079setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003080{
3081 PyObject *v;
3082 int err;
3083
3084 v = PyInt_FromLong((long)value);
3085 err = PyDict_SetItemString(d, name, v);
3086 Py_XDECREF(v);
3087 return err;
3088}
3089
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003090typedef struct {
3091 PyObject_HEAD
3092} NullImporter;
3093
3094static int
3095NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
3096{
3097 char *path;
Christian Heimescea681b2007-11-07 17:50:54 +00003098 Py_ssize_t pathlen;
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003099
3100 if (!_PyArg_NoKeywords("NullImporter()", kwds))
3101 return -1;
3102
3103 if (!PyArg_ParseTuple(args, "s:NullImporter",
3104 &path))
3105 return -1;
3106
Christian Heimescea681b2007-11-07 17:50:54 +00003107 pathlen = strlen(path);
3108 if (pathlen == 0) {
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003109 PyErr_SetString(PyExc_ImportError, "empty pathname");
3110 return -1;
3111 } else {
3112#ifndef RISCOS
3113 struct stat statbuf;
3114 int rv;
3115
3116 rv = stat(path, &statbuf);
Christian Heimes004c1c12007-11-07 18:30:22 +00003117#ifdef MS_WINDOWS
3118 /* MS Windows stat() chokes on paths like C:\path\. Try to
3119 * recover *one* time by stripping off a trailing slash or
3120 * backslash. http://bugs.python.org/issue1293
3121 */
Christian Heimescea681b2007-11-07 17:50:54 +00003122 if (rv != 0 && pathlen <= MAXPATHLEN &&
3123 (path[pathlen-1] == '/' || path[pathlen-1] == '\\')) {
3124 char mangled[MAXPATHLEN+1];
3125
3126 strcpy(mangled, path);
3127 mangled[pathlen-1] = '\0';
3128 rv = stat(mangled, &statbuf);
3129 }
Christian Heimescea681b2007-11-07 17:50:54 +00003130#endif
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003131 if (rv == 0) {
3132 /* it exists */
3133 if (S_ISDIR(statbuf.st_mode)) {
3134 /* it's a directory */
3135 PyErr_SetString(PyExc_ImportError,
3136 "existing directory");
3137 return -1;
3138 }
3139 }
3140#else
3141 if (object_exists(path)) {
3142 /* it exists */
3143 if (isdir(path)) {
3144 /* it's a directory */
3145 PyErr_SetString(PyExc_ImportError,
3146 "existing directory");
3147 return -1;
3148 }
3149 }
3150#endif
3151 }
3152 return 0;
3153}
3154
3155static PyObject *
3156NullImporter_find_module(NullImporter *self, PyObject *args)
3157{
3158 Py_RETURN_NONE;
3159}
3160
3161static PyMethodDef NullImporter_methods[] = {
3162 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3163 "Always return None"
3164 },
3165 {NULL} /* Sentinel */
3166};
3167
3168
Nick Coghlan327a39b2007-11-18 11:56:28 +00003169PyTypeObject PyNullImporter_Type = {
Martin v. Löwis68192102007-07-21 06:55:02 +00003170 PyVarObject_HEAD_INIT(NULL, 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003171 "imp.NullImporter", /*tp_name*/
3172 sizeof(NullImporter), /*tp_basicsize*/
3173 0, /*tp_itemsize*/
3174 0, /*tp_dealloc*/
3175 0, /*tp_print*/
3176 0, /*tp_getattr*/
3177 0, /*tp_setattr*/
3178 0, /*tp_compare*/
3179 0, /*tp_repr*/
3180 0, /*tp_as_number*/
3181 0, /*tp_as_sequence*/
3182 0, /*tp_as_mapping*/
3183 0, /*tp_hash */
3184 0, /*tp_call*/
3185 0, /*tp_str*/
3186 0, /*tp_getattro*/
3187 0, /*tp_setattro*/
3188 0, /*tp_as_buffer*/
3189 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3190 "Null importer object", /* tp_doc */
3191 0, /* tp_traverse */
3192 0, /* tp_clear */
3193 0, /* tp_richcompare */
3194 0, /* tp_weaklistoffset */
3195 0, /* tp_iter */
3196 0, /* tp_iternext */
3197 NullImporter_methods, /* tp_methods */
3198 0, /* tp_members */
3199 0, /* tp_getset */
3200 0, /* tp_base */
3201 0, /* tp_dict */
3202 0, /* tp_descr_get */
3203 0, /* tp_descr_set */
3204 0, /* tp_dictoffset */
3205 (initproc)NullImporter_init, /* tp_init */
3206 0, /* tp_alloc */
3207 PyType_GenericNew /* tp_new */
3208};
3209
3210
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003211PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003212initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003213{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003214 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003215
Nick Coghlan327a39b2007-11-18 11:56:28 +00003216 if (PyType_Ready(&PyNullImporter_Type) < 0)
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003217 goto failure;
3218
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003219 m = Py_InitModule4("imp", imp_methods, doc_imp,
3220 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00003221 if (m == NULL)
3222 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003223 d = PyModule_GetDict(m);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00003224 if (d == NULL)
3225 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003226
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003227 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3228 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3229 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3230 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3231 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3232 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3233 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3234 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003235 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003236 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003237
Nick Coghlan327a39b2007-11-18 11:56:28 +00003238 Py_INCREF(&PyNullImporter_Type);
3239 PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003240 failure:
3241 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003242}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003243
3244
Guido van Rossumb18618d2000-05-03 23:44:39 +00003245/* API for embedding applications that want to add their own entries
3246 to the table of built-in modules. This should normally be called
3247 *before* Py_Initialize(). When the table resize fails, -1 is
3248 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003249
3250 After a similar function by Just van Rossum. */
3251
3252int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003253PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003254{
3255 static struct _inittab *our_copy = NULL;
3256 struct _inittab *p;
3257 int i, n;
3258
3259 /* Count the number of entries in both tables */
3260 for (n = 0; newtab[n].name != NULL; n++)
3261 ;
3262 if (n == 0)
3263 return 0; /* Nothing to do */
3264 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3265 ;
3266
3267 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003268 p = our_copy;
3269 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003270 if (p == NULL)
3271 return -1;
3272
3273 /* Copy the tables into the new memory */
3274 if (our_copy != PyImport_Inittab)
3275 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3276 PyImport_Inittab = our_copy = p;
3277 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3278
3279 return 0;
3280}
3281
3282/* Shorthand to add a single entry given a name and a function */
3283
3284int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003285PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003286{
3287 struct _inittab newtab[2];
3288
3289 memset(newtab, '\0', sizeof newtab);
3290
3291 newtab[0].name = name;
3292 newtab[0].initfunc = initfunc;
3293
3294 return PyImport_ExtendInittab(newtab);
3295}
Anthony Baxterac6bd462006-04-13 02:06:09 +00003296
3297#ifdef __cplusplus
3298}
3299#endif