blob: 365f9786e78819cb20cc7fa63a65f8d14c62d65e [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"
Neal Norwitzadb69fc2005-12-17 20:54:49 +00007#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00008#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000010#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000011#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000012#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000013#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000014#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000015#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000016
Guido van Rossum55a83382000-09-20 20:31:38 +000017#ifdef HAVE_FCNTL_H
18#include <fcntl.h>
19#endif
Anthony Baxterac6bd462006-04-13 02:06:09 +000020#ifdef __cplusplus
21extern "C" {
22#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000023
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000024extern time_t PyOS_GetLastModificationTime(char *, FILE *);
25 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000026
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000027/* Magic word to reject .pyc files generated by other Python versions.
28 It should change for each incompatible change to the bytecode.
29
30 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000031 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000032 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000033
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000034 The magic numbers must be spaced apart atleast 2 values, as the
35 -U interpeter flag will cause MAGIC+1 being used. They have been
36 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000037
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000038 There were a variety of old schemes for setting the magic number.
39 The current working scheme is to increment the previous value by
40 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000041
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000042 Known values:
43 Python 1.5: 20121
44 Python 1.5.1: 20121
45 Python 1.5.2: 20121
Skip Montanaro4ec3c262006-03-25 14:12:03 +000046 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000047 Python 2.0: 50823
48 Python 2.0.1: 50823
49 Python 2.1: 60202
50 Python 2.1.1: 60202
51 Python 2.1.2: 60202
52 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000053 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000054 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000055 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000056 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000057 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000058 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000059 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000060 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000061 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000062 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Neal Norwitz0d62a062006-07-30 06:53:31 +000063 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
64 Python 2.5b3: 62111 (fix wrong code: x += yield)
Neal Norwitz9a70f952006-08-04 05:12:19 +000065 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
66 storing constants that should have been removed)
Neal Norwitzdac090d2006-09-05 03:53:08 +000067 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Neal Norwitzcbeb6872006-10-14 21:33:38 +000068 Python 2.6a0: 62141 (peephole optimizations)
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000069.
Tim Peters36515e22001-11-18 04:06:29 +000070*/
Neal Norwitzcbeb6872006-10-14 21:33:38 +000071#define MAGIC (62141 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000072
Guido van Rossum96774c12000-05-01 20:19:08 +000073/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000074 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000075 compiler works which are enabled by command line switches. */
76static long pyc_magic = MAGIC;
77
Guido van Rossum25ce5661997-08-02 03:10:38 +000078/* See _PyImport_FixupExtension() below */
79static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000080
Guido van Rossum771c6c81997-10-31 18:37:24 +000081/* This table is defined in config.c: */
82extern struct _inittab _PyImport_Inittab[];
83
84struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000085
Guido van Rossumed1170e1999-12-20 21:23:41 +000086/* these tables define the module suffixes that Python recognizes */
87struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +000088
89#ifdef RISCOS
90static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000091 {"/py", "U", PY_SOURCE},
Guido van Rossum48a680c2001-03-02 06:34:14 +000092 {"/pyc", "rb", PY_COMPILED},
93 {0, 0}
94};
95#else
Guido van Rossumed1170e1999-12-20 21:23:41 +000096static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000097 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000098#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +000099 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000100#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000101 {".pyc", "rb", PY_COMPILED},
102 {0, 0}
103};
Guido van Rossum48a680c2001-03-02 06:34:14 +0000104#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000105
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000106static PyTypeObject NullImporterType; /* Forward reference */
107
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 */
121 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
122 ++countD;
123 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
124 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000125 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Neal Norwitze1fdb322006-07-21 05:32:28 +0000126 if (filetab == NULL)
Neal Norwitz33722ae2006-07-21 07:59:02 +0000127 Py_FatalError("Can't initialize import file table.");
Guido van Rossumed1170e1999-12-20 21:23:41 +0000128 memcpy(filetab, _PyImport_DynLoadFiletab,
129 countD * sizeof(struct filedescr));
130 memcpy(filetab + countD, _PyImport_StandardFiletab,
131 countS * sizeof(struct filedescr));
132 filetab[countD + countS].suffix = NULL;
133
134 _PyImport_Filetab = filetab;
135
Guido van Rossum0824f631997-03-11 18:37:35 +0000136 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000137 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
138 for (; filetab->suffix != NULL; filetab++) {
Guido van Rossum48a680c2001-03-02 06:34:14 +0000139#ifndef RISCOS
Guido van Rossumed1170e1999-12-20 21:23:41 +0000140 if (strcmp(filetab->suffix, ".pyc") == 0)
141 filetab->suffix = ".pyo";
Guido van Rossum48a680c2001-03-02 06:34:14 +0000142#else
143 if (strcmp(filetab->suffix, "/pyc") == 0)
144 filetab->suffix = "/pyo";
145#endif
Guido van Rossum0824f631997-03-11 18:37:35 +0000146 }
147 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000148
149 if (Py_UnicodeFlag) {
150 /* Fix the pyc_magic so that byte compiled code created
151 using the all-Unicode method doesn't interfere with
152 code created in normal operation mode. */
153 pyc_magic = MAGIC + 1;
154 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000155}
156
Guido van Rossum25ce5661997-08-02 03:10:38 +0000157void
Just van Rossum52e14d62002-12-30 22:08:05 +0000158_PyImportHooks_Init(void)
159{
160 PyObject *v, *path_hooks = NULL, *zimpimport;
161 int err = 0;
162
163 /* adding sys.path_hooks and sys.path_importer_cache, setting up
164 zipimport */
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000165 if (PyType_Ready(&NullImporterType) < 0)
166 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000167
168 if (Py_VerboseFlag)
169 PySys_WriteStderr("# installing zipimport hook\n");
170
171 v = PyList_New(0);
172 if (v == NULL)
173 goto error;
174 err = PySys_SetObject("meta_path", v);
175 Py_DECREF(v);
176 if (err)
177 goto error;
178 v = PyDict_New();
179 if (v == NULL)
180 goto error;
181 err = PySys_SetObject("path_importer_cache", v);
182 Py_DECREF(v);
183 if (err)
184 goto error;
185 path_hooks = PyList_New(0);
186 if (path_hooks == NULL)
187 goto error;
188 err = PySys_SetObject("path_hooks", path_hooks);
189 if (err) {
190 error:
191 PyErr_Print();
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000192 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
193 "path_importer_cache, or NullImporter failed"
194 );
Just van Rossum52e14d62002-12-30 22:08:05 +0000195 }
Phillip J. Ebyf7575d02006-07-28 21:12:07 +0000196
Just van Rossum52e14d62002-12-30 22:08:05 +0000197 zimpimport = PyImport_ImportModule("zipimport");
198 if (zimpimport == NULL) {
199 PyErr_Clear(); /* No zip import module -- okay */
200 if (Py_VerboseFlag)
201 PySys_WriteStderr("# can't import zipimport\n");
202 }
203 else {
204 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
205 "zipimporter");
206 Py_DECREF(zimpimport);
207 if (zipimporter == NULL) {
208 PyErr_Clear(); /* No zipimporter object -- okay */
209 if (Py_VerboseFlag)
210 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000211 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000212 }
213 else {
214 /* sys.path_hooks.append(zipimporter) */
215 err = PyList_Append(path_hooks, zipimporter);
216 Py_DECREF(zipimporter);
217 if (err)
218 goto error;
219 if (Py_VerboseFlag)
220 PySys_WriteStderr(
221 "# installed zipimport hook\n");
222 }
223 }
224 Py_DECREF(path_hooks);
225}
226
227void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000228_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000229{
230 Py_XDECREF(extensions);
231 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000232 PyMem_DEL(_PyImport_Filetab);
233 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000234}
235
236
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000237/* Locking primitives to prevent parallel imports of the same module
238 in different threads to return with a partially loaded module.
239 These calls are serialized by the global interpreter lock. */
240
241#ifdef WITH_THREAD
242
Guido van Rossum49b56061998-10-01 20:42:43 +0000243#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000244
Guido van Rossum65d5b571998-12-21 19:32:43 +0000245static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000246static long import_lock_thread = -1;
247static int import_lock_level = 0;
248
249static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000250lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000251{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000252 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000253 if (me == -1)
254 return; /* Too bad */
Neal Norwitze1fdb322006-07-21 05:32:28 +0000255 if (import_lock == NULL) {
Guido van Rossum65d5b571998-12-21 19:32:43 +0000256 import_lock = PyThread_allocate_lock();
Neal Norwitze1fdb322006-07-21 05:32:28 +0000257 if (import_lock == NULL)
258 return; /* Nothing much we can do. */
259 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000260 if (import_lock_thread == me) {
261 import_lock_level++;
262 return;
263 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000264 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
265 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000266 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000267 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000268 PyEval_RestoreThread(tstate);
269 }
270 import_lock_thread = me;
271 import_lock_level = 1;
272}
273
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000274static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000275unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000276{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000277 long me = PyThread_get_thread_ident();
Neal Norwitze1fdb322006-07-21 05:32:28 +0000278 if (me == -1 || import_lock == NULL)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000279 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000280 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000281 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000282 import_lock_level--;
283 if (import_lock_level == 0) {
284 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000285 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000286 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000287 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000288}
289
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000290/* This function is called from PyOS_AfterFork to ensure that newly
291 created child processes do not share locks with the parent. */
292
293void
294_PyImport_ReInitLock(void)
295{
296#ifdef _AIX
297 if (import_lock != NULL)
298 import_lock = PyThread_allocate_lock();
299#endif
300}
301
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000302#else
303
304#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000305#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000306
307#endif
308
Tim Peters69232342001-08-30 05:16:13 +0000309static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000310imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000311{
Tim Peters69232342001-08-30 05:16:13 +0000312#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000313 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000314#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000315 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000316#endif
317}
318
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000319static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000320imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000321{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000322#ifdef WITH_THREAD
323 lock_import();
324#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000325 Py_INCREF(Py_None);
326 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000327}
328
329static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000330imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000331{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000332#ifdef WITH_THREAD
333 if (unlock_import() < 0) {
334 PyErr_SetString(PyExc_RuntimeError,
335 "not holding the import lock");
336 return NULL;
337 }
338#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000339 Py_INCREF(Py_None);
340 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000341}
342
Collin Winter276887b2007-03-12 16:11:39 +0000343PyObject *
344PyImport_GetModulesReloading(void)
345{
346 PyInterpreterState *interp = PyThreadState_Get()->interp;
347 if (interp->modules_reloading == NULL)
Neal Norwitz75c7c802007-03-13 05:31:38 +0000348 Py_FatalError("PyImport_GetModulesReloading: "
349 "no modules_reloading dictionary!");
Collin Winter276887b2007-03-12 16:11:39 +0000350 return interp->modules_reloading;
351}
352
353static void
Neal Norwitz75c7c802007-03-13 05:31:38 +0000354imp_modules_reloading_clear(void)
Collin Winter276887b2007-03-12 16:11:39 +0000355{
356 PyInterpreterState *interp = PyThreadState_Get()->interp;
Neal Norwitz75c7c802007-03-13 05:31:38 +0000357 if (interp->modules_reloading != NULL)
358 PyDict_Clear(interp->modules_reloading);
Collin Winter276887b2007-03-12 16:11:39 +0000359}
360
Guido van Rossum25ce5661997-08-02 03:10:38 +0000361/* Helper for sys */
362
363PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000364PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000365{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000366 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000367 if (interp->modules == NULL)
368 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
369 return interp->modules;
370}
371
Guido van Rossum3f5da241990-12-20 15:06:42 +0000372
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000373/* List of names to clear in sys */
374static char* sys_deletes[] = {
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000375 "path", "argv", "ps1", "ps2", "exitfunc",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000376 "exc_type", "exc_value", "exc_traceback",
377 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000378 "path_hooks", "path_importer_cache", "meta_path",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000379 NULL
380};
381
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000382static char* sys_files[] = {
383 "stdin", "__stdin__",
384 "stdout", "__stdout__",
385 "stderr", "__stderr__",
386 NULL
387};
388
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000389
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000390/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000391
Guido van Rossum3f5da241990-12-20 15:06:42 +0000392void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000393PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000394{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000395 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000396 char *name;
397 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000398 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000399 PyObject *modules = interp->modules;
400
401 if (modules == NULL)
402 return; /* Already done */
403
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000404 /* Delete some special variables first. These are common
405 places where user values hide and people complain when their
406 destructors fail. Since the modules containing them are
407 deleted *last* of all, they would come too late in the normal
408 destruction order. Sigh. */
409
410 value = PyDict_GetItemString(modules, "__builtin__");
411 if (value != NULL && PyModule_Check(value)) {
412 dict = PyModule_GetDict(value);
413 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000414 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000415 PyDict_SetItemString(dict, "_", Py_None);
416 }
417 value = PyDict_GetItemString(modules, "sys");
418 if (value != NULL && PyModule_Check(value)) {
419 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000420 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000421 dict = PyModule_GetDict(value);
422 for (p = sys_deletes; *p != NULL; p++) {
423 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000424 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000425 PyDict_SetItemString(dict, *p, Py_None);
426 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000427 for (p = sys_files; *p != NULL; p+=2) {
428 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000429 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000430 v = PyDict_GetItemString(dict, *(p+1));
431 if (v == NULL)
432 v = Py_None;
433 PyDict_SetItemString(dict, *p, v);
434 }
435 }
436
437 /* First, delete __main__ */
438 value = PyDict_GetItemString(modules, "__main__");
439 if (value != NULL && PyModule_Check(value)) {
440 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000441 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000442 _PyModule_Clear(value);
443 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000444 }
445
Guido van Rossum758eec01998-01-19 21:58:26 +0000446 /* The special treatment of __builtin__ here is because even
447 when it's not referenced as a module, its dictionary is
448 referenced by almost every module's __builtins__. Since
449 deleting a module clears its dictionary (even if there are
450 references left to it), we need to delete the __builtin__
451 module last. Likewise, we don't delete sys until the very
452 end because it is implicitly referenced (e.g. by print).
453
454 Also note that we 'delete' modules by replacing their entry
455 in the modules dict with None, rather than really deleting
456 them; this avoids a rehash of the modules dictionary and
457 also marks them as "non existent" so they won't be
458 re-imported. */
459
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000460 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000461 one (skipping __builtin__ and sys) and delete them */
462 do {
463 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000464 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000465 while (PyDict_Next(modules, &pos, &key, &value)) {
466 if (value->ob_refcnt != 1)
467 continue;
Guido van Rossum566373e1998-10-01 15:24:50 +0000468 if (PyString_Check(key) && PyModule_Check(value)) {
469 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000470 if (strcmp(name, "__builtin__") == 0)
471 continue;
472 if (strcmp(name, "sys") == 0)
473 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000474 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000475 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000476 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000477 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000478 PyDict_SetItem(modules, key, Py_None);
479 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000480 }
481 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000482 } while (ndone > 0);
483
Guido van Rossum758eec01998-01-19 21:58:26 +0000484 /* Next, delete all modules (still skipping __builtin__ and sys) */
485 pos = 0;
486 while (PyDict_Next(modules, &pos, &key, &value)) {
Guido van Rossum566373e1998-10-01 15:24:50 +0000487 if (PyString_Check(key) && PyModule_Check(value)) {
488 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000489 if (strcmp(name, "__builtin__") == 0)
490 continue;
491 if (strcmp(name, "sys") == 0)
492 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000493 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000494 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000495 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000496 PyDict_SetItem(modules, key, Py_None);
497 }
498 }
499
500 /* Next, delete sys and __builtin__ (in that order) */
501 value = PyDict_GetItemString(modules, "sys");
502 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000503 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000504 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000505 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000506 PyDict_SetItemString(modules, "sys", Py_None);
507 }
508 value = PyDict_GetItemString(modules, "__builtin__");
509 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000510 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000511 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000512 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000513 PyDict_SetItemString(modules, "__builtin__", Py_None);
514 }
515
516 /* Finally, clear and delete the modules directory */
517 PyDict_Clear(modules);
518 interp->modules = NULL;
519 Py_DECREF(modules);
Collin Winter276887b2007-03-12 16:11:39 +0000520 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000521}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000522
523
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000524/* Helper for pythonrun.c -- return magic number */
525
526long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000527PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000528{
Guido van Rossum96774c12000-05-01 20:19:08 +0000529 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000530}
531
532
Guido van Rossum25ce5661997-08-02 03:10:38 +0000533/* Magic for extension modules (built-in as well as dynamically
534 loaded). To prevent initializing an extension module more than
535 once, we keep a static dictionary 'extensions' keyed by module name
536 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000537 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000538 dictionary is stored by calling _PyImport_FixupExtension()
539 immediately after the module initialization function succeeds. A
540 copy can be retrieved from there by calling
541 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000542
Guido van Rossum79f25d91997-04-29 20:08:16 +0000543PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000544_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000545{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000546 PyObject *modules, *mod, *dict, *copy;
547 if (extensions == NULL) {
548 extensions = PyDict_New();
549 if (extensions == NULL)
550 return NULL;
551 }
552 modules = PyImport_GetModuleDict();
553 mod = PyDict_GetItemString(modules, name);
554 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000555 PyErr_Format(PyExc_SystemError,
556 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000557 return NULL;
558 }
559 dict = PyModule_GetDict(mod);
560 if (dict == NULL)
561 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000562 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000563 if (copy == NULL)
564 return NULL;
565 PyDict_SetItemString(extensions, filename, copy);
566 Py_DECREF(copy);
567 return copy;
568}
569
570PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000571_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000572{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000573 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000574 if (extensions == NULL)
575 return NULL;
576 dict = PyDict_GetItemString(extensions, filename);
577 if (dict == NULL)
578 return NULL;
579 mod = PyImport_AddModule(name);
580 if (mod == NULL)
581 return NULL;
582 mdict = PyModule_GetDict(mod);
583 if (mdict == NULL)
584 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000585 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000586 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000587 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000588 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000589 name, filename);
590 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000591}
592
593
594/* Get the module object corresponding to a module name.
595 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000596 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000597 Because the former action is most common, THIS DOES NOT RETURN A
598 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000599
Guido van Rossum79f25d91997-04-29 20:08:16 +0000600PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000601PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000602{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000603 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000604 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000605
Guido van Rossum25ce5661997-08-02 03:10:38 +0000606 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000607 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000608 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000609 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000610 if (m == NULL)
611 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000612 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000613 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000614 return NULL;
615 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000616 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000617
618 return m;
619}
620
Tim Peters1cd70172004-08-02 03:52:12 +0000621/* Remove name from sys.modules, if it's there. */
622static void
623_RemoveModule(const char *name)
624{
625 PyObject *modules = PyImport_GetModuleDict();
626 if (PyDict_GetItemString(modules, name) == NULL)
627 return;
628 if (PyDict_DelItemString(modules, name) < 0)
629 Py_FatalError("import: deleting existing key in"
630 "sys.modules failed");
631}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000632
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000633/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000634 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
635 * removed from sys.modules, to avoid leaving damaged module objects
636 * in sys.modules. The caller may wish to restore the original
637 * module object (if any) in this case; PyImport_ReloadModule is an
638 * example.
639 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000640PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000641PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000642{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000643 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
644}
645
646PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000647PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000648{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000649 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000650 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000651
Guido van Rossum79f25d91997-04-29 20:08:16 +0000652 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000653 if (m == NULL)
654 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000655 /* If the module is being reloaded, we get the old module back
656 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000657 d = PyModule_GetDict(m);
658 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
659 if (PyDict_SetItemString(d, "__builtins__",
660 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000661 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000662 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000663 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000664 v = NULL;
665 if (pathname != NULL) {
666 v = PyString_FromString(pathname);
667 if (v == NULL)
668 PyErr_Clear();
669 }
670 if (v == NULL) {
671 v = ((PyCodeObject *)co)->co_filename;
672 Py_INCREF(v);
673 }
674 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000675 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000676 Py_DECREF(v);
677
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000678 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000679 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000680 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000681 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000682
Guido van Rossum25ce5661997-08-02 03:10:38 +0000683 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000684 PyErr_Format(PyExc_ImportError,
685 "Loaded module %.200s not found in sys.modules",
686 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000687 return NULL;
688 }
689
Guido van Rossum79f25d91997-04-29 20:08:16 +0000690 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000691
692 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000693
694 error:
695 _RemoveModule(name);
696 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000697}
698
699
700/* Given a pathname for a Python source file, fill a buffer with the
701 pathname for the corresponding compiled file. Return the pathname
702 for the compiled file, or NULL if there's no space in the buffer.
703 Doesn't set an exception. */
704
705static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000706make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000707{
Tim Petersc1731372001-08-04 08:12:36 +0000708 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000709 if (len+2 > buflen)
710 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000711
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000712#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000713 /* Treat .pyw as if it were .py. The case of ".pyw" must match
714 that used in _PyImport_StandardFiletab. */
715 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
716 --len; /* pretend 'w' isn't there */
717#endif
718 memcpy(buf, pathname, len);
719 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
720 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000721
722 return buf;
723}
724
725
726/* Given a pathname for a Python source file, its time of last
727 modification, and a pathname for a compiled file, check whether the
728 compiled file represents the same version of the source. If so,
729 return a FILE pointer for the compiled file, positioned just after
730 the header; if not, return NULL.
731 Doesn't set an exception. */
732
733static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000734check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000735{
736 FILE *fp;
737 long magic;
738 long pyc_mtime;
739
740 fp = fopen(cpathname, "rb");
741 if (fp == NULL)
742 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000743 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000744 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000745 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000746 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000747 fclose(fp);
748 return NULL;
749 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000750 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000751 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000752 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000753 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000754 fclose(fp);
755 return NULL;
756 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000757 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000758 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759 return fp;
760}
761
762
763/* Read a code object from a file and check it for validity */
764
Guido van Rossum79f25d91997-04-29 20:08:16 +0000765static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000766read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000767{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000768 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000769
Tim Petersd9b9ac82001-01-28 00:27:39 +0000770 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000771 if (co == NULL)
772 return NULL;
773 if (!PyCode_Check(co)) {
774 PyErr_Format(PyExc_ImportError,
775 "Non-code object in %.200s", cpathname);
776 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000777 return NULL;
778 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000779 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000780}
781
782
783/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000784 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000785
Guido van Rossum79f25d91997-04-29 20:08:16 +0000786static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000787load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000788{
789 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000790 PyCodeObject *co;
791 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000792
Guido van Rossum79f25d91997-04-29 20:08:16 +0000793 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000794 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000795 PyErr_Format(PyExc_ImportError,
796 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000797 return NULL;
798 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000799 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000800 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000801 if (co == NULL)
802 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000803 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000804 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000805 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000806 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000807 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000808
809 return m;
810}
811
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000812/* Parse a source file and return the corresponding code object */
813
Guido van Rossum79f25d91997-04-29 20:08:16 +0000814static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000815parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000816{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000817 PyCodeObject *co = NULL;
818 mod_ty mod;
Neal Norwitz2a399b02006-09-11 04:28:16 +0000819 PyArena *arena = PyArena_New();
820 if (arena == NULL)
821 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000822
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000823 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, 0,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000824 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000825 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000826 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827 }
Neal Norwitz2a399b02006-09-11 04:28:16 +0000828 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000829 return co;
830}
831
832
Guido van Rossum55a83382000-09-20 20:31:38 +0000833/* Helper to open a bytecode file for writing in exclusive mode */
834
835static FILE *
836open_exclusive(char *filename)
837{
838#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
839 /* Use O_EXCL to avoid a race condition when another process tries to
840 write the same file. When that happens, our open() call fails,
841 which is just fine (since it's only a cache).
842 XXX If the file exists and is writable but the directory is not
843 writable, the file will never be written. Oh well.
844 */
845 int fd;
846 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000847 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
848#ifdef O_BINARY
849 |O_BINARY /* necessary for Windows */
850#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000851#ifdef __VMS
Martin v. Löwis18e16552006-02-15 17:27:45 +0000852 , 0666, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000853#else
Martin v. Löwis18e16552006-02-15 17:27:45 +0000854 , 0666
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000855#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000856 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000857 if (fd < 0)
858 return NULL;
859 return fdopen(fd, "wb");
860#else
861 /* Best we can do -- on Windows this can't happen anyway */
862 return fopen(filename, "wb");
863#endif
864}
865
866
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000867/* Write a compiled module to a file, placing the time of last
868 modification of its source into the header.
869 Errors are ignored, if a write error occurs an attempt is made to
870 remove the file. */
871
872static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000873write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000874{
875 FILE *fp;
876
Guido van Rossum55a83382000-09-20 20:31:38 +0000877 fp = open_exclusive(cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000878 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000879 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000880 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000881 "# can't create %s\n", cpathname);
882 return;
883 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000884 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000885 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000886 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
887 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000888 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000889 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000890 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000891 /* Don't keep partial file */
892 fclose(fp);
893 (void) unlink(cpathname);
894 return;
895 }
896 /* Now write the true mtime */
897 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000898 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000899 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000900 fflush(fp);
901 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000902 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000903 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000904}
905
906
907/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000908 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
909 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000910
Guido van Rossum79f25d91997-04-29 20:08:16 +0000911static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000912load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000913{
Fred Drake4c82b232000-06-30 16:18:57 +0000914 time_t mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000915 FILE *fpc;
916 char buf[MAXPATHLEN+1];
917 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000918 PyCodeObject *co;
919 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000920
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000921 mtime = PyOS_GetLastModificationTime(pathname, fp);
Neal Norwitz708e51a2005-10-03 04:48:15 +0000922 if (mtime == (time_t)(-1)) {
923 PyErr_Format(PyExc_RuntimeError,
924 "unable to get modification time from '%s'",
925 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000926 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000927 }
Fred Drake4c82b232000-06-30 16:18:57 +0000928#if SIZEOF_TIME_T > 4
929 /* Python's .pyc timestamp handling presumes that the timestamp fits
930 in 4 bytes. This will be fine until sometime in the year 2038,
931 when a 4-byte signed time_t will overflow.
932 */
933 if (mtime >> 32) {
934 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000935 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000936 return NULL;
937 }
938#endif
Tim Peters36515e22001-11-18 04:06:29 +0000939 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000940 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000941 if (cpathname != NULL &&
942 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000943 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000944 fclose(fpc);
945 if (co == NULL)
946 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000947 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000948 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000949 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000950 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000951 }
952 else {
953 co = parse_source_module(pathname, fp);
954 if (co == NULL)
955 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000956 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000957 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000958 name, pathname);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +0000959 if (cpathname)
960 write_compiled_module(co, cpathname, mtime);
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(
1096 (PyObject *)&NullImporterType, p, NULL
1097 );
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
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001114/* Search the path (default sys.path) for a module. Return the
1115 corresponding filedescr struct, and (via return arguments) the
1116 pathname and an open file. Return NULL if the module is not found. */
1117
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001118#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001119extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001120 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001121#endif
1122
Martin v. Löwis18e16552006-02-15 17:27:45 +00001123static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001124static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001125static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001126
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001127static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001128find_module(char *fullname, char *subname, PyObject *path, char *buf,
1129 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001130{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001131 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001132 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001133 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001134 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001135 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001136 PyObject *path_hooks, *path_importer_cache;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001137#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001138 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001139#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001140 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1141 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1142 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001143 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001144#if defined(PYOS_OS2)
1145 size_t saved_len;
1146 size_t saved_namelen;
1147 char *saved_buf = NULL;
1148#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001149 if (p_loader != NULL)
1150 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001151
Just van Rossum52e14d62002-12-30 22:08:05 +00001152 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001153 PyErr_SetString(PyExc_OverflowError,
1154 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001155 return NULL;
1156 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001157 strcpy(name, subname);
1158
1159 /* sys.meta_path import hook */
1160 if (p_loader != NULL) {
1161 PyObject *meta_path;
1162
1163 meta_path = PySys_GetObject("meta_path");
1164 if (meta_path == NULL || !PyList_Check(meta_path)) {
1165 PyErr_SetString(PyExc_ImportError,
1166 "sys.meta_path must be a list of "
1167 "import hooks");
1168 return NULL;
1169 }
1170 Py_INCREF(meta_path); /* zap guard */
1171 npath = PyList_Size(meta_path);
1172 for (i = 0; i < npath; i++) {
1173 PyObject *loader;
1174 PyObject *hook = PyList_GetItem(meta_path, i);
1175 loader = PyObject_CallMethod(hook, "find_module",
1176 "sO", fullname,
1177 path != NULL ?
1178 path : Py_None);
1179 if (loader == NULL) {
1180 Py_DECREF(meta_path);
1181 return NULL; /* true error */
1182 }
1183 if (loader != Py_None) {
1184 /* a loader was found */
1185 *p_loader = loader;
1186 Py_DECREF(meta_path);
1187 return &importhookdescr;
1188 }
1189 Py_DECREF(loader);
1190 }
1191 Py_DECREF(meta_path);
1192 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001193
1194 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001195 /* The only type of submodule allowed inside a "frozen"
1196 package are other frozen modules or packages. */
Guido van Rossum0506a431998-08-11 15:07:39 +00001197 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1198 PyErr_SetString(PyExc_ImportError,
1199 "full frozen module name too long");
1200 return NULL;
1201 }
1202 strcpy(buf, PyString_AsString(path));
1203 strcat(buf, ".");
1204 strcat(buf, name);
1205 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001206 if (find_frozen(name) != NULL) {
1207 strcpy(buf, name);
1208 return &fd_frozen;
1209 }
1210 PyErr_Format(PyExc_ImportError,
1211 "No frozen submodule named %.200s", name);
1212 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001213 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001214 if (path == NULL) {
1215 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001216 strcpy(buf, name);
1217 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001218 }
Greg Ward201baee2001-10-04 14:52:06 +00001219 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001220 strcpy(buf, name);
1221 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001222 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001223
Guido van Rossumac279101996-08-22 23:10:58 +00001224#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001225 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1226 if (fp != NULL) {
1227 *p_fp = fp;
1228 return fdp;
1229 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001230#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001231 path = PySys_GetObject("path");
1232 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001233 if (path == NULL || !PyList_Check(path)) {
1234 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001235 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001236 return NULL;
1237 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001238
1239 path_hooks = PySys_GetObject("path_hooks");
1240 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1241 PyErr_SetString(PyExc_ImportError,
1242 "sys.path_hooks must be a list of "
1243 "import hooks");
1244 return NULL;
1245 }
1246 path_importer_cache = PySys_GetObject("path_importer_cache");
1247 if (path_importer_cache == NULL ||
1248 !PyDict_Check(path_importer_cache)) {
1249 PyErr_SetString(PyExc_ImportError,
1250 "sys.path_importer_cache must be a dict");
1251 return NULL;
1252 }
1253
Guido van Rossum79f25d91997-04-29 20:08:16 +00001254 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001255 namelen = strlen(name);
1256 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +00001257 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001258 PyObject *v = PyList_GetItem(path, i);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00001259 if (!v)
1260 return NULL;
Walter Dörwald3430d702002-06-17 10:43:59 +00001261#ifdef Py_USING_UNICODE
1262 if (PyUnicode_Check(v)) {
1263 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1264 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1265 if (copy == NULL)
1266 return NULL;
1267 v = copy;
1268 }
1269 else
1270#endif
Guido van Rossum79f25d91997-04-29 20:08:16 +00001271 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001272 continue;
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00001273 len = PyString_GET_SIZE(v);
Walter Dörwald3430d702002-06-17 10:43:59 +00001274 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1275 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001276 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001277 }
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00001278 strcpy(buf, PyString_AS_STRING(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001279 if (strlen(buf) != len) {
1280 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001281 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001282 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001283
1284 /* sys.path_hooks import hook */
1285 if (p_loader != NULL) {
1286 PyObject *importer;
1287
1288 importer = get_path_importer(path_importer_cache,
1289 path_hooks, v);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001290 if (importer == NULL) {
1291 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001292 return NULL;
Neal Norwitza4df11d2006-07-06 04:28:59 +00001293 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001294 /* Note: importer is a borrowed reference */
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00001295 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001296 PyObject *loader;
1297 loader = PyObject_CallMethod(importer,
1298 "find_module",
1299 "s", fullname);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001300 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001301 if (loader == NULL)
1302 return NULL; /* error */
1303 if (loader != Py_None) {
1304 /* a loader was found */
1305 *p_loader = loader;
1306 return &importhookdescr;
1307 }
1308 Py_DECREF(loader);
Georg Brandlf4ef1162006-05-26 18:03:31 +00001309 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001310 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001311 }
Georg Brandlf4ef1162006-05-26 18:03:31 +00001312 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001313
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001314 if (len > 0 && buf[len-1] != SEP
1315#ifdef ALTSEP
1316 && buf[len-1] != ALTSEP
1317#endif
1318 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001319 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001320 strcpy(buf+len, name);
1321 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001322
1323 /* Check for package import (buf holds a directory name,
1324 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001325#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001326 if (stat(buf, &statbuf) == 0 && /* it exists */
1327 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001328 case_ok(buf, len, namelen, name)) { /* case matches */
1329 if (find_init_module(buf)) { /* and has __init__.py */
1330 Py_XDECREF(copy);
1331 return &fd_package;
1332 }
1333 else {
1334 char warnstr[MAXPATHLEN+80];
1335 sprintf(warnstr, "Not importing directory "
1336 "'%.*s': missing __init__.py",
1337 MAXPATHLEN, buf);
1338 if (PyErr_Warn(PyExc_ImportWarning,
1339 warnstr)) {
1340 Py_XDECREF(copy);
1341 return NULL;
1342 }
1343 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001344 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001345#else
1346 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001347#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001348 if (isdir(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001349 case_ok(buf, len, namelen, name)) {
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001350 if (find_init_module(buf)) {
1351 Py_XDECREF(copy);
1352 return &fd_package;
1353 }
1354 else {
1355 char warnstr[MAXPATHLEN+80];
1356 sprintf(warnstr, "Not importing directory "
1357 "'%.*s': missing __init__.py",
1358 MAXPATHLEN, buf);
1359 if (PyErr_Warn(PyExc_ImportWarning,
1360 warnstr)) {
1361 Py_XDECREF(copy);
1362 return NULL;
1363 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001364 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001365#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001366#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001367#if defined(PYOS_OS2)
1368 /* take a snapshot of the module spec for restoration
1369 * after the 8 character DLL hackery
1370 */
1371 saved_buf = strdup(buf);
1372 saved_len = len;
1373 saved_namelen = namelen;
1374#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001375 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001376#if defined(PYOS_OS2)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001377 /* OS/2 limits DLLs to 8 character names (w/o
1378 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001379 * so if the name is longer than that and its a
1380 * dynamically loaded module we're going to try,
1381 * truncate the name before trying
1382 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001383 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001384 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001385 const struct filedescr *scan;
1386 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001387 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001388 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001389 break;
1390 else
1391 scan++;
1392 }
1393 if (scan->suffix != NULL) {
1394 /* yes, so truncate the name */
1395 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001396 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001397 buf[len] = '\0';
1398 }
1399 }
1400#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001401 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001402 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001403 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001404 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001405 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001406 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001407 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001408 if (fp != NULL) {
1409 if (case_ok(buf, len, namelen, name))
1410 break;
1411 else { /* continue search */
1412 fclose(fp);
1413 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001414 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001415 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001416#if defined(PYOS_OS2)
1417 /* restore the saved snapshot */
1418 strcpy(buf, saved_buf);
1419 len = saved_len;
1420 namelen = saved_namelen;
1421#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001422 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001423#if defined(PYOS_OS2)
1424 /* don't need/want the module name snapshot anymore */
1425 if (saved_buf)
1426 {
1427 free(saved_buf);
1428 saved_buf = NULL;
1429 }
1430#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001431 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001432 if (fp != NULL)
1433 break;
1434 }
1435 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001436 PyErr_Format(PyExc_ImportError,
1437 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001438 return NULL;
1439 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001440 *p_fp = fp;
1441 return fdp;
1442}
1443
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001444/* Helpers for main.c
1445 * Find the source file corresponding to a named module
1446 */
1447struct filedescr *
1448_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1449 size_t buflen, FILE **p_fp, PyObject **p_loader)
1450{
1451 return find_module((char *) name, (char *) name, path,
1452 buf, buflen, p_fp, p_loader);
1453}
1454
1455PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1456{
1457 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1458}
1459
Martin v. Löwis18e16552006-02-15 17:27:45 +00001460/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001461 * The arguments here are tricky, best shown by example:
1462 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1463 * ^ ^ ^ ^
1464 * |--------------------- buf ---------------------|
1465 * |------------------- len ------------------|
1466 * |------ name -------|
1467 * |----- namelen -----|
1468 * buf is the full path, but len only counts up to (& exclusive of) the
1469 * extension. name is the module name, also exclusive of extension.
1470 *
1471 * We've already done a successful stat() or fopen() on buf, so know that
1472 * there's some match, possibly case-insensitive.
1473 *
Tim Peters50d8d372001-02-28 05:34:27 +00001474 * case_ok() is to return 1 if there's a case-sensitive match for
1475 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1476 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001477 *
Tim Peters50d8d372001-02-28 05:34:27 +00001478 * case_ok() is used to implement case-sensitive import semantics even
1479 * on platforms with case-insensitive filesystems. It's trivial to implement
1480 * for case-sensitive filesystems. It's pretty much a cross-platform
1481 * nightmare for systems with case-insensitive filesystems.
1482 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001483
Tim Peters50d8d372001-02-28 05:34:27 +00001484/* First we may need a pile of platform-specific header files; the sequence
1485 * of #if's here should match the sequence in the body of case_ok().
1486 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001487#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001488#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001489
Tim Peters50d8d372001-02-28 05:34:27 +00001490#elif defined(DJGPP)
1491#include <dir.h>
1492
Jason Tishler7961aa62005-05-20 00:56:54 +00001493#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001494#include <sys/types.h>
1495#include <dirent.h>
1496
Andrew MacIntyred9400542002-02-26 11:41:34 +00001497#elif defined(PYOS_OS2)
1498#define INCL_DOS
1499#define INCL_DOSERRORS
1500#define INCL_NOPMAPI
1501#include <os2.h>
1502
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001503#elif defined(RISCOS)
1504#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001505#endif
1506
Guido van Rossum0980bd91998-02-13 17:18:36 +00001507static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001508case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001509{
Tim Peters50d8d372001-02-28 05:34:27 +00001510/* Pick a platform-specific implementation; the sequence of #if's here should
1511 * match the sequence just above.
1512 */
1513
Jason Tishler7961aa62005-05-20 00:56:54 +00001514/* MS_WINDOWS */
1515#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001516 WIN32_FIND_DATA data;
1517 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001518
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001519 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001520 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001521
Guido van Rossum0980bd91998-02-13 17:18:36 +00001522 h = FindFirstFile(buf, &data);
1523 if (h == INVALID_HANDLE_VALUE) {
1524 PyErr_Format(PyExc_NameError,
1525 "Can't find file for module %.100s\n(filename %.300s)",
1526 name, buf);
1527 return 0;
1528 }
1529 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001530 return strncmp(data.cFileName, name, namelen) == 0;
1531
1532/* DJGPP */
1533#elif defined(DJGPP)
1534 struct ffblk ffblk;
1535 int done;
1536
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001537 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001538 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001539
1540 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1541 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001542 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001543 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001544 name, buf);
1545 return 0;
1546 }
Tim Peters50d8d372001-02-28 05:34:27 +00001547 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001548
Jason Tishler7961aa62005-05-20 00:56:54 +00001549/* new-fangled macintosh (macosx) or Cygwin */
1550#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001551 DIR *dirp;
1552 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001553 char dirname[MAXPATHLEN + 1];
1554 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001555
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001556 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001557 return 1;
1558
Tim Petersd1e87a82001-03-01 18:12:00 +00001559 /* Copy the dir component into dirname; substitute "." if empty */
1560 if (dirlen <= 0) {
1561 dirname[0] = '.';
1562 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001563 }
1564 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001565 assert(dirlen <= MAXPATHLEN);
1566 memcpy(dirname, buf, dirlen);
1567 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001568 }
1569 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001570 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001571 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001572 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001573 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001574 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001575#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001576 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001577#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001578 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001579#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001580 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001581 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001582 (void)closedir(dirp);
1583 return 1; /* Found */
1584 }
1585 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001586 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001587 }
Tim Peters430f5d42001-03-01 01:30:56 +00001588 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001589
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001590/* RISC OS */
1591#elif defined(RISCOS)
1592 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1593 char buf2[MAXPATHLEN+2];
1594 char *nameWithExt = buf+len-namelen;
1595 int canonlen;
1596 os_error *e;
1597
1598 if (Py_GETENV("PYTHONCASEOK") != NULL)
1599 return 1;
1600
1601 /* workaround:
1602 append wildcard, otherwise case of filename wouldn't be touched */
1603 strcpy(buf2, buf);
1604 strcat(buf2, "*");
1605
1606 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1607 canonlen = MAXPATHLEN+1-canonlen;
1608 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1609 return 0;
1610 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1611 return 1; /* match */
1612
1613 return 0;
1614
Andrew MacIntyred9400542002-02-26 11:41:34 +00001615/* OS/2 */
1616#elif defined(PYOS_OS2)
1617 HDIR hdir = 1;
1618 ULONG srchcnt = 1;
1619 FILEFINDBUF3 ffbuf;
1620 APIRET rc;
1621
1622 if (getenv("PYTHONCASEOK") != NULL)
1623 return 1;
1624
1625 rc = DosFindFirst(buf,
1626 &hdir,
1627 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1628 &ffbuf, sizeof(ffbuf),
1629 &srchcnt,
1630 FIL_STANDARD);
1631 if (rc != NO_ERROR)
1632 return 0;
1633 return strncmp(ffbuf.achName, name, namelen) == 0;
1634
Tim Peters50d8d372001-02-28 05:34:27 +00001635/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1636#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001637 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001638
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001639#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001640}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001641
Guido van Rossum0980bd91998-02-13 17:18:36 +00001642
Guido van Rossum197346f1997-10-31 18:38:52 +00001643#ifdef HAVE_STAT
1644/* Helper to look for __init__.py or __init__.py[co] in potential package */
1645static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001646find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001647{
Tim Peters0f9431f2001-07-05 03:47:53 +00001648 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001649 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001650 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001651 struct stat statbuf;
1652
Tim Peters0f9431f2001-07-05 03:47:53 +00001653/* For calling case_ok(buf, len, namelen, name):
1654 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1655 * ^ ^ ^ ^
1656 * |--------------------- buf ---------------------|
1657 * |------------------- len ------------------|
1658 * |------ name -------|
1659 * |----- namelen -----|
1660 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001661 if (save_len + 13 >= MAXPATHLEN)
1662 return 0;
1663 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001664 pname = buf + i;
1665 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001666 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001667 if (case_ok(buf,
1668 save_len + 9, /* len("/__init__") */
1669 8, /* len("__init__") */
1670 pname)) {
1671 buf[save_len] = '\0';
1672 return 1;
1673 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001674 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001675 i += strlen(pname);
1676 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001677 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001678 if (case_ok(buf,
1679 save_len + 9, /* len("/__init__") */
1680 8, /* len("__init__") */
1681 pname)) {
1682 buf[save_len] = '\0';
1683 return 1;
1684 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001685 }
1686 buf[save_len] = '\0';
1687 return 0;
1688}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001689
1690#else
1691
1692#ifdef RISCOS
1693static int
1694find_init_module(buf)
1695 char *buf;
1696{
1697 int save_len = strlen(buf);
1698 int i = save_len;
1699
1700 if (save_len + 13 >= MAXPATHLEN)
1701 return 0;
1702 buf[i++] = SEP;
1703 strcpy(buf+i, "__init__/py");
1704 if (isfile(buf)) {
1705 buf[save_len] = '\0';
1706 return 1;
1707 }
1708
1709 if (Py_OptimizeFlag)
1710 strcpy(buf+i, "o");
1711 else
1712 strcpy(buf+i, "c");
1713 if (isfile(buf)) {
1714 buf[save_len] = '\0';
1715 return 1;
1716 }
1717 buf[save_len] = '\0';
1718 return 0;
1719}
1720#endif /*RISCOS*/
1721
Guido van Rossum197346f1997-10-31 18:38:52 +00001722#endif /* HAVE_STAT */
1723
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001724
Tim Petersdbd9ba62000-07-09 03:09:57 +00001725static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001726
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001727/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001728 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001729
Guido van Rossum79f25d91997-04-29 20:08:16 +00001730static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001731load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001732{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001733 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001734 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001735 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001736
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001737 /* First check that there's an open file (if we need one) */
1738 switch (type) {
1739 case PY_SOURCE:
1740 case PY_COMPILED:
1741 if (fp == NULL) {
1742 PyErr_Format(PyExc_ValueError,
1743 "file object required for import (type code %d)",
1744 type);
1745 return NULL;
1746 }
1747 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001748
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001749 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001750
1751 case PY_SOURCE:
1752 m = load_source_module(name, buf, fp);
1753 break;
1754
1755 case PY_COMPILED:
1756 m = load_compiled_module(name, buf, fp);
1757 break;
1758
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001759#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001760 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001761 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001762 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001763#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001764
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001765 case PKG_DIRECTORY:
1766 m = load_package(name, buf);
1767 break;
1768
1769 case C_BUILTIN:
1770 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001771 if (buf != NULL && buf[0] != '\0')
1772 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001773 if (type == C_BUILTIN)
1774 err = init_builtin(name);
1775 else
1776 err = PyImport_ImportFrozenModule(name);
1777 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001778 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001779 if (err == 0) {
1780 PyErr_Format(PyExc_ImportError,
1781 "Purported %s module %.200s not found",
1782 type == C_BUILTIN ?
1783 "builtin" : "frozen",
1784 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001785 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001786 }
1787 modules = PyImport_GetModuleDict();
1788 m = PyDict_GetItemString(modules, name);
1789 if (m == NULL) {
1790 PyErr_Format(
1791 PyExc_ImportError,
1792 "%s module %.200s not properly initialized",
1793 type == C_BUILTIN ?
1794 "builtin" : "frozen",
1795 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001796 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001797 }
1798 Py_INCREF(m);
1799 break;
1800
Just van Rossum52e14d62002-12-30 22:08:05 +00001801 case IMP_HOOK: {
1802 if (loader == NULL) {
1803 PyErr_SetString(PyExc_ImportError,
1804 "import hook without loader");
1805 return NULL;
1806 }
1807 m = PyObject_CallMethod(loader, "load_module", "s", name);
1808 break;
1809 }
1810
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001811 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001812 PyErr_Format(PyExc_ImportError,
1813 "Don't know how to import %.200s (type code %d)",
1814 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001815 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001816
1817 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001818
1819 return m;
1820}
1821
1822
1823/* Initialize a built-in module.
Brett Cannon5a9aa4f2006-10-03 21:58:55 +00001824 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001825 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001826
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001827static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001828init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001829{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001830 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001831
Greg Ward201baee2001-10-04 14:52:06 +00001832 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001833 return 1;
1834
Guido van Rossum771c6c81997-10-31 18:37:24 +00001835 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001836 if (strcmp(name, p->name) == 0) {
1837 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001838 PyErr_Format(PyExc_ImportError,
1839 "Cannot re-init internal module %.200s",
1840 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001841 return -1;
1842 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001843 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001844 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001845 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001846 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001847 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001848 if (_PyImport_FixupExtension(name, name) == NULL)
1849 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001850 return 1;
1851 }
1852 }
1853 return 0;
1854}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001855
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001856
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001857/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001858
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001859static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001860find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001861{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001862 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001863
Guido van Rossum79f25d91997-04-29 20:08:16 +00001864 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001865 if (p->name == NULL)
1866 return NULL;
1867 if (strcmp(p->name, name) == 0)
1868 break;
1869 }
1870 return p;
1871}
1872
Guido van Rossum79f25d91997-04-29 20:08:16 +00001873static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001874get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001875{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001876 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001877 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001878
1879 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001880 PyErr_Format(PyExc_ImportError,
1881 "No such frozen object named %.200s",
1882 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001883 return NULL;
1884 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001885 if (p->code == NULL) {
1886 PyErr_Format(PyExc_ImportError,
1887 "Excluded frozen object named %.200s",
1888 name);
1889 return NULL;
1890 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001891 size = p->size;
1892 if (size < 0)
1893 size = -size;
1894 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001895}
1896
1897/* Initialize a frozen module.
1898 Return 1 for succes, 0 if the module is not found, and -1 with
1899 an exception set if the initialization failed.
1900 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001901
1902int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001903PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001904{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001905 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001906 PyObject *co;
1907 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001908 int ispackage;
1909 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001910
1911 if (p == NULL)
1912 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001913 if (p->code == NULL) {
1914 PyErr_Format(PyExc_ImportError,
1915 "Excluded frozen object named %.200s",
1916 name);
1917 return -1;
1918 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001919 size = p->size;
1920 ispackage = (size < 0);
1921 if (ispackage)
1922 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001923 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001924 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001925 name, ispackage ? " package" : "");
1926 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001927 if (co == NULL)
1928 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001929 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001930 PyErr_Format(PyExc_TypeError,
1931 "frozen object %.200s is not a code object",
1932 name);
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001933 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001934 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001935 if (ispackage) {
1936 /* Set __path__ to the package name */
1937 PyObject *d, *s;
1938 int err;
1939 m = PyImport_AddModule(name);
1940 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001941 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001942 d = PyModule_GetDict(m);
1943 s = PyString_InternFromString(name);
1944 if (s == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001945 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001946 err = PyDict_SetItemString(d, "__path__", s);
1947 Py_DECREF(s);
1948 if (err != 0)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001949 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001950 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001951 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001952 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001953 goto err_return;
1954 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001955 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001956 return 1;
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001957err_return:
1958 Py_DECREF(co);
1959 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001960}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001961
1962
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001963/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001964 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001965
Guido van Rossum79f25d91997-04-29 20:08:16 +00001966PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001967PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001968{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001969 PyObject *pname;
1970 PyObject *result;
1971
1972 pname = PyString_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001973 if (pname == NULL)
1974 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001975 result = PyImport_Import(pname);
1976 Py_DECREF(pname);
1977 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001978}
1979
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001980/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001981static PyObject *get_parent(PyObject *globals, char *buf,
1982 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001983static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001984 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001985static int mark_miss(char *name);
1986static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001987 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001988static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001989
1990/* The Magnum Opus of dotted-name import :-) */
1991
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001992static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001993import_module_level(char *name, PyObject *globals, PyObject *locals,
1994 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001995{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001996 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00001997 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001998 PyObject *parent, *head, *next, *tail;
1999
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002000 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002001 if (parent == NULL)
2002 return NULL;
2003
2004 head = load_next(parent, Py_None, &name, buf, &buflen);
2005 if (head == NULL)
2006 return NULL;
2007
2008 tail = head;
2009 Py_INCREF(tail);
2010 while (name) {
2011 next = load_next(tail, tail, &name, buf, &buflen);
2012 Py_DECREF(tail);
2013 if (next == NULL) {
2014 Py_DECREF(head);
2015 return NULL;
2016 }
2017 tail = next;
2018 }
Thomas Wouters8ddab272006-04-04 16:17:02 +00002019 if (tail == Py_None) {
2020 /* If tail is Py_None, both get_parent and load_next found
2021 an empty module name: someone called __import__("") or
2022 doctored faulty bytecode */
Thomas Wouters4bdaa272006-04-05 13:39:37 +00002023 Py_DECREF(tail);
2024 Py_DECREF(head);
Thomas Wouters8ddab272006-04-04 16:17:02 +00002025 PyErr_SetString(PyExc_ValueError,
2026 "Empty module name");
2027 return NULL;
2028 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002029
2030 if (fromlist != NULL) {
2031 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2032 fromlist = NULL;
2033 }
2034
2035 if (fromlist == NULL) {
2036 Py_DECREF(tail);
2037 return head;
2038 }
2039
2040 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002041 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002042 Py_DECREF(tail);
2043 return NULL;
2044 }
2045
2046 return tail;
2047}
2048
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002049/* For DLL compatibility */
2050#undef PyImport_ImportModuleEx
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002051PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002052PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
2053 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002054{
2055 PyObject *result;
2056 lock_import();
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002057 result = import_module_level(name, globals, locals, fromlist, -1);
2058 if (unlock_import() < 0) {
2059 Py_XDECREF(result);
2060 PyErr_SetString(PyExc_RuntimeError,
2061 "not holding the import lock");
2062 return NULL;
2063 }
2064 return result;
2065}
2066#define PyImport_ImportModuleEx(n, g, l, f) \
2067 PyImport_ImportModuleLevel(n, g, l, f, -1);
2068
2069PyObject *
2070PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2071 PyObject *fromlist, int level)
2072{
2073 PyObject *result;
2074 lock_import();
2075 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002076 if (unlock_import() < 0) {
2077 Py_XDECREF(result);
2078 PyErr_SetString(PyExc_RuntimeError,
2079 "not holding the import lock");
2080 return NULL;
2081 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002082 return result;
2083}
2084
Fred Drake87590902004-05-28 20:21:36 +00002085/* Return the package that an import is being performed in. If globals comes
2086 from the module foo.bar.bat (not itself a package), this returns the
2087 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Georg Brandl5f6861d2006-05-28 21:57:35 +00002088 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002089
2090 The *name* of the returned package is returned in buf, with the length of
2091 the name in *p_buflen.
2092
2093 If globals doesn't come from a package or a module in a package, or a
2094 corresponding entry is not found in sys.modules, Py_None is returned.
2095*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002096static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002097get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002098{
2099 static PyObject *namestr = NULL;
2100 static PyObject *pathstr = NULL;
2101 PyObject *modname, *modpath, *modules, *parent;
2102
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002103 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002104 return Py_None;
2105
2106 if (namestr == NULL) {
2107 namestr = PyString_InternFromString("__name__");
2108 if (namestr == NULL)
2109 return NULL;
2110 }
2111 if (pathstr == NULL) {
2112 pathstr = PyString_InternFromString("__path__");
2113 if (pathstr == NULL)
2114 return NULL;
2115 }
2116
2117 *buf = '\0';
2118 *p_buflen = 0;
2119 modname = PyDict_GetItem(globals, namestr);
2120 if (modname == NULL || !PyString_Check(modname))
2121 return Py_None;
2122
2123 modpath = PyDict_GetItem(globals, pathstr);
2124 if (modpath != NULL) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00002125 Py_ssize_t len = PyString_GET_SIZE(modname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002126 if (len > MAXPATHLEN) {
2127 PyErr_SetString(PyExc_ValueError,
2128 "Module name too long");
2129 return NULL;
2130 }
2131 strcpy(buf, PyString_AS_STRING(modname));
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002132 }
2133 else {
2134 char *start = PyString_AS_STRING(modname);
2135 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002136 size_t len;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002137 if (lastdot == NULL && level > 0) {
2138 PyErr_SetString(PyExc_ValueError,
Georg Brandl98775df2006-09-06 06:09:31 +00002139 "Attempted relative import in non-package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002140 return NULL;
2141 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002142 if (lastdot == NULL)
2143 return Py_None;
2144 len = lastdot - start;
2145 if (len >= MAXPATHLEN) {
2146 PyErr_SetString(PyExc_ValueError,
2147 "Module name too long");
2148 return NULL;
2149 }
2150 strncpy(buf, start, len);
2151 buf[len] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002152 }
2153
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002154 while (--level > 0) {
2155 char *dot = strrchr(buf, '.');
2156 if (dot == NULL) {
2157 PyErr_SetString(PyExc_ValueError,
Georg Brandl98775df2006-09-06 06:09:31 +00002158 "Attempted relative import beyond "
2159 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002160 return NULL;
2161 }
2162 *dot = '\0';
2163 }
2164 *p_buflen = strlen(buf);
2165
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002166 modules = PyImport_GetModuleDict();
2167 parent = PyDict_GetItemString(modules, buf);
2168 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002169 PyErr_Format(PyExc_SystemError,
2170 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002171 return parent;
2172 /* We expect, but can't guarantee, if parent != None, that:
2173 - parent.__name__ == buf
2174 - parent.__dict__ is globals
2175 If this is violated... Who cares? */
2176}
2177
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002178/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002179static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002180load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002181 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002182{
2183 char *name = *p_name;
2184 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002185 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002186 char *p;
2187 PyObject *result;
2188
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002189 if (strlen(name) == 0) {
Thomas Wouters8ddab272006-04-04 16:17:02 +00002190 /* completely empty module name should only happen in
2191 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002192 Py_INCREF(mod);
2193 *p_name = NULL;
2194 return mod;
2195 }
2196
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002197 if (dot == NULL) {
2198 *p_name = NULL;
2199 len = strlen(name);
2200 }
2201 else {
2202 *p_name = dot+1;
2203 len = dot-name;
2204 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002205 if (len == 0) {
2206 PyErr_SetString(PyExc_ValueError,
2207 "Empty module name");
2208 return NULL;
2209 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002210
2211 p = buf + *p_buflen;
2212 if (p != buf)
2213 *p++ = '.';
2214 if (p+len-buf >= MAXPATHLEN) {
2215 PyErr_SetString(PyExc_ValueError,
2216 "Module name too long");
2217 return NULL;
2218 }
2219 strncpy(p, name, len);
2220 p[len] = '\0';
2221 *p_buflen = p+len-buf;
2222
2223 result = import_submodule(mod, p, buf);
2224 if (result == Py_None && altmod != mod) {
2225 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002226 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002227 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002228 if (result != NULL && result != Py_None) {
2229 if (mark_miss(buf) != 0) {
2230 Py_DECREF(result);
2231 return NULL;
2232 }
2233 strncpy(buf, name, len);
2234 buf[len] = '\0';
2235 *p_buflen = len;
2236 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002237 }
2238 if (result == NULL)
2239 return NULL;
2240
2241 if (result == Py_None) {
2242 Py_DECREF(result);
2243 PyErr_Format(PyExc_ImportError,
2244 "No module named %.200s", name);
2245 return NULL;
2246 }
2247
2248 return result;
2249}
2250
2251static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002252mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002253{
2254 PyObject *modules = PyImport_GetModuleDict();
2255 return PyDict_SetItemString(modules, name, Py_None);
2256}
2257
2258static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002259ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002260 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002261{
2262 int i;
2263
2264 if (!PyObject_HasAttrString(mod, "__path__"))
2265 return 1;
2266
2267 for (i = 0; ; i++) {
2268 PyObject *item = PySequence_GetItem(fromlist, i);
2269 int hasit;
2270 if (item == NULL) {
2271 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2272 PyErr_Clear();
2273 return 1;
2274 }
2275 return 0;
2276 }
2277 if (!PyString_Check(item)) {
2278 PyErr_SetString(PyExc_TypeError,
2279 "Item in ``from list'' not a string");
2280 Py_DECREF(item);
2281 return 0;
2282 }
2283 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002284 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002285 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002286 /* See if the package defines __all__ */
2287 if (recursive)
2288 continue; /* Avoid endless recursion */
2289 all = PyObject_GetAttrString(mod, "__all__");
2290 if (all == NULL)
2291 PyErr_Clear();
2292 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002293 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002294 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002295 if (!ret)
2296 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002297 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002298 continue;
2299 }
2300 hasit = PyObject_HasAttr(mod, item);
2301 if (!hasit) {
2302 char *subname = PyString_AS_STRING(item);
2303 PyObject *submod;
2304 char *p;
2305 if (buflen + strlen(subname) >= MAXPATHLEN) {
2306 PyErr_SetString(PyExc_ValueError,
2307 "Module name too long");
2308 Py_DECREF(item);
2309 return 0;
2310 }
2311 p = buf + buflen;
2312 *p++ = '.';
2313 strcpy(p, subname);
2314 submod = import_submodule(mod, subname, buf);
2315 Py_XDECREF(submod);
2316 if (submod == NULL) {
2317 Py_DECREF(item);
2318 return 0;
2319 }
2320 }
2321 Py_DECREF(item);
2322 }
2323
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002324 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002325}
2326
Neil Schemenauer00b09662003-06-16 21:03:07 +00002327static int
2328add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2329 PyObject *modules)
2330{
2331 if (mod == Py_None)
2332 return 1;
2333 /* Irrespective of the success of this load, make a
2334 reference to it in the parent package module. A copy gets
2335 saved in the modules dictionary under the full name, so get a
2336 reference from there, if need be. (The exception is when the
2337 load failed with a SyntaxError -- then there's no trace in
2338 sys.modules. In that case, of course, do nothing extra.) */
2339 if (submod == NULL) {
2340 submod = PyDict_GetItemString(modules, fullname);
2341 if (submod == NULL)
2342 return 1;
2343 }
2344 if (PyModule_Check(mod)) {
2345 /* We can't use setattr here since it can give a
2346 * spurious warning if the submodule name shadows a
2347 * builtin name */
2348 PyObject *dict = PyModule_GetDict(mod);
2349 if (!dict)
2350 return 0;
2351 if (PyDict_SetItemString(dict, subname, submod) < 0)
2352 return 0;
2353 }
2354 else {
2355 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2356 return 0;
2357 }
2358 return 1;
2359}
2360
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002361static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002362import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002363{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002364 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002365 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002366
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002367 /* Require:
2368 if mod == None: subname == fullname
2369 else: mod.__name__ + "." + subname == fullname
2370 */
2371
Tim Peters50d8d372001-02-28 05:34:27 +00002372 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002373 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002374 }
2375 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002376 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002377 char buf[MAXPATHLEN+1];
2378 struct filedescr *fdp;
2379 FILE *fp = NULL;
2380
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002381 if (mod == Py_None)
2382 path = NULL;
2383 else {
2384 path = PyObject_GetAttrString(mod, "__path__");
2385 if (path == NULL) {
2386 PyErr_Clear();
2387 Py_INCREF(Py_None);
2388 return Py_None;
2389 }
2390 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002391
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002392 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002393 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2394 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002395 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002396 if (fdp == NULL) {
2397 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2398 return NULL;
2399 PyErr_Clear();
2400 Py_INCREF(Py_None);
2401 return Py_None;
2402 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002403 m = load_module(fullname, fp, buf, fdp->type, loader);
2404 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002405 if (fp)
2406 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002407 if (!add_submodule(mod, m, fullname, subname, modules)) {
2408 Py_XDECREF(m);
2409 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002410 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002411 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002412
2413 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002414}
2415
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002416
2417/* Re-import a module of any kind and return its module object, WITH
2418 INCREMENTED REFERENCE COUNT */
2419
Guido van Rossum79f25d91997-04-29 20:08:16 +00002420PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002421PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002422{
Collin Winter276887b2007-03-12 16:11:39 +00002423 PyObject *modules_reloading = PyImport_GetModulesReloading();
Guido van Rossum25ce5661997-08-02 03:10:38 +00002424 PyObject *modules = PyImport_GetModuleDict();
Collin Winter276887b2007-03-12 16:11:39 +00002425 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002426 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002427 char buf[MAXPATHLEN+1];
2428 struct filedescr *fdp;
2429 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002430 PyObject *newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002431
Guido van Rossum79f25d91997-04-29 20:08:16 +00002432 if (m == NULL || !PyModule_Check(m)) {
2433 PyErr_SetString(PyExc_TypeError,
2434 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002435 return NULL;
2436 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002437 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002438 if (name == NULL)
2439 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002440 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002441 PyErr_Format(PyExc_ImportError,
2442 "reload(): module %.200s not in sys.modules",
2443 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002444 return NULL;
2445 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002446 existing_m = PyDict_GetItemString(modules_reloading, name);
2447 if (existing_m != NULL) {
2448 /* Due to a recursive reload, this module is already
2449 being reloaded. */
2450 Py_INCREF(existing_m);
2451 return existing_m;
Collin Winter276887b2007-03-12 16:11:39 +00002452 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002453 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2454 return NULL;
Collin Winter276887b2007-03-12 16:11:39 +00002455
Guido van Rossum222ef561997-09-06 19:41:09 +00002456 subname = strrchr(name, '.');
2457 if (subname == NULL)
2458 subname = name;
2459 else {
2460 PyObject *parentname, *parent;
2461 parentname = PyString_FromStringAndSize(name, (subname-name));
Collin Winter276887b2007-03-12 16:11:39 +00002462 if (parentname == NULL) {
2463 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002464 return NULL;
Neal Norwitz75c7c802007-03-13 05:31:38 +00002465 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002466 parent = PyDict_GetItem(modules, parentname);
2467 if (parent == NULL) {
2468 PyErr_Format(PyExc_ImportError,
2469 "reload(): parent %.200s not in sys.modules",
Georg Brandl0c55f292005-09-14 06:56:20 +00002470 PyString_AS_STRING(parentname));
2471 Py_DECREF(parentname);
Collin Winter276887b2007-03-12 16:11:39 +00002472 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002473 return NULL;
2474 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002475 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002476 subname++;
2477 path = PyObject_GetAttrString(parent, "__path__");
2478 if (path == NULL)
2479 PyErr_Clear();
2480 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002481 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002482 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002483 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002484
2485 if (fdp == NULL) {
2486 Py_XDECREF(loader);
Collin Winter276887b2007-03-12 16:11:39 +00002487 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002488 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002489 }
2490
2491 newm = load_module(name, fp, buf, fdp->type, loader);
2492 Py_XDECREF(loader);
2493
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002494 if (fp)
2495 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002496 if (newm == NULL) {
2497 /* load_module probably removed name from modules because of
2498 * the error. Put back the original module object. We're
2499 * going to return NULL in this case regardless of whether
2500 * replacing name succeeds, so the return value is ignored.
2501 */
2502 PyDict_SetItemString(modules, name, m);
2503 }
Neal Norwitz75c7c802007-03-13 05:31:38 +00002504 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002505 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002506}
2507
2508
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002509/* Higher-level import emulator which emulates the "import" statement
2510 more accurately -- it invokes the __import__() function from the
2511 builtins of the current globals. This means that the import is
2512 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002513 environment, e.g. by "rexec".
2514 A dummy list ["__doc__"] is passed as the 4th argument so that
2515 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2516 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002517
2518PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002519PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002520{
2521 static PyObject *silly_list = NULL;
2522 static PyObject *builtins_str = NULL;
2523 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002524 PyObject *globals = NULL;
2525 PyObject *import = NULL;
2526 PyObject *builtins = NULL;
2527 PyObject *r = NULL;
2528
2529 /* Initialize constant string objects */
2530 if (silly_list == NULL) {
2531 import_str = PyString_InternFromString("__import__");
2532 if (import_str == NULL)
2533 return NULL;
2534 builtins_str = PyString_InternFromString("__builtins__");
2535 if (builtins_str == NULL)
2536 return NULL;
2537 silly_list = Py_BuildValue("[s]", "__doc__");
2538 if (silly_list == NULL)
2539 return NULL;
2540 }
2541
2542 /* Get the builtins from current globals */
2543 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002544 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002545 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002546 builtins = PyObject_GetItem(globals, builtins_str);
2547 if (builtins == NULL)
2548 goto err;
2549 }
2550 else {
2551 /* No globals -- use standard builtins, and fake globals */
2552 PyErr_Clear();
2553
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002554 builtins = PyImport_ImportModuleLevel("__builtin__",
2555 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002556 if (builtins == NULL)
2557 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002558 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2559 if (globals == NULL)
2560 goto err;
2561 }
2562
2563 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002564 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002565 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002566 if (import == NULL)
2567 PyErr_SetObject(PyExc_KeyError, import_str);
2568 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002569 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002570 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002571 if (import == NULL)
2572 goto err;
2573
Georg Brandl74780962007-03-10 07:38:14 +00002574 /* Call the __import__ function with the proper argument list */
Georg Brandl684fd0c2006-05-25 19:15:31 +00002575 r = PyObject_CallFunctionObjArgs(import, module_name, globals,
2576 globals, silly_list, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002577
2578 err:
2579 Py_XDECREF(globals);
2580 Py_XDECREF(builtins);
2581 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002582
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002583 return r;
2584}
2585
2586
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002587/* Module 'imp' provides Python access to the primitives used for
2588 importing modules.
2589*/
2590
Guido van Rossum79f25d91997-04-29 20:08:16 +00002591static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002592imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002593{
2594 char buf[4];
2595
Guido van Rossum96774c12000-05-01 20:19:08 +00002596 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2597 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2598 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2599 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002600
Guido van Rossum79f25d91997-04-29 20:08:16 +00002601 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002602}
2603
Guido van Rossum79f25d91997-04-29 20:08:16 +00002604static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002605imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002606{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002607 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002608 struct filedescr *fdp;
2609
Guido van Rossum79f25d91997-04-29 20:08:16 +00002610 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002611 if (list == NULL)
2612 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002613 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2614 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002615 fdp->suffix, fdp->mode, fdp->type);
2616 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002617 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002618 return NULL;
2619 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002620 if (PyList_Append(list, item) < 0) {
2621 Py_DECREF(list);
2622 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002623 return NULL;
2624 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002625 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002626 }
2627 return list;
2628}
2629
Guido van Rossum79f25d91997-04-29 20:08:16 +00002630static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002631call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002632{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002633 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002634 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002635 struct filedescr *fdp;
2636 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002637 FILE *fp = NULL;
2638
2639 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002640 if (path == Py_None)
2641 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002642 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002643 if (fdp == NULL)
2644 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002645 if (fp != NULL) {
2646 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2647 if (fob == NULL) {
2648 fclose(fp);
2649 return NULL;
2650 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002651 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002652 else {
2653 fob = Py_None;
2654 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002655 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002656 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002657 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002658 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002659 return ret;
2660}
2661
Guido van Rossum79f25d91997-04-29 20:08:16 +00002662static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002663imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002664{
2665 char *name;
2666 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002667 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002668 return NULL;
2669 return call_find_module(name, path);
2670}
2671
2672static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002673imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002674{
2675 char *name;
2676 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002677 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002678 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002679 return NULL;
2680 ret = init_builtin(name);
2681 if (ret < 0)
2682 return NULL;
2683 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002684 Py_INCREF(Py_None);
2685 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002686 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002687 m = PyImport_AddModule(name);
2688 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002689 return m;
2690}
2691
Guido van Rossum79f25d91997-04-29 20:08:16 +00002692static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002693imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002694{
2695 char *name;
2696 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002697 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002698 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002699 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002700 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002701 if (ret < 0)
2702 return NULL;
2703 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002704 Py_INCREF(Py_None);
2705 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002706 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002707 m = PyImport_AddModule(name);
2708 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002709 return m;
2710}
2711
Guido van Rossum79f25d91997-04-29 20:08:16 +00002712static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002713imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002714{
2715 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002716
Guido van Rossum43713e52000-02-29 13:59:29 +00002717 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002718 return NULL;
2719 return get_frozen_object(name);
2720}
2721
Guido van Rossum79f25d91997-04-29 20:08:16 +00002722static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002723imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002724{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002725 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002726 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002727 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002728 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002729}
2730
Guido van Rossum79f25d91997-04-29 20:08:16 +00002731static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002732imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002733{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002734 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002735 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002736 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002737 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002738 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002739 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002740}
2741
2742static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002743get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002744{
2745 FILE *fp;
2746 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002747 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002748 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002749 fp = fopen(pathname, mode);
2750 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002751 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002752 }
2753 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002754 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002755 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002756 PyErr_SetString(PyExc_ValueError,
2757 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002758 }
2759 return fp;
2760}
2761
Guido van Rossum79f25d91997-04-29 20:08:16 +00002762static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002763imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002764{
2765 char *name;
2766 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002767 PyObject *fob = NULL;
2768 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002769 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002770 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002771 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002772 return NULL;
2773 fp = get_file(pathname, fob, "rb");
2774 if (fp == NULL)
2775 return NULL;
2776 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002777 if (fob == NULL)
2778 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002779 return m;
2780}
2781
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002782#ifdef HAVE_DYNAMIC_LOADING
2783
Guido van Rossum79f25d91997-04-29 20:08:16 +00002784static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002785imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002786{
2787 char *name;
2788 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002789 PyObject *fob = NULL;
2790 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002791 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002792 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002793 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002794 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002795 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002796 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002797 if (fp == NULL)
2798 return NULL;
2799 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002800 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002801 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002802}
2803
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002804#endif /* HAVE_DYNAMIC_LOADING */
2805
Guido van Rossum79f25d91997-04-29 20:08:16 +00002806static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002807imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002808{
2809 char *name;
2810 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002811 PyObject *fob = NULL;
2812 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002813 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002814 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002815 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002816 return NULL;
2817 fp = get_file(pathname, fob, "r");
2818 if (fp == NULL)
2819 return NULL;
2820 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002821 if (fob == NULL)
2822 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002823 return m;
2824}
2825
Guido van Rossum79f25d91997-04-29 20:08:16 +00002826static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002827imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002828{
2829 char *name;
2830 PyObject *fob;
2831 char *pathname;
2832 char *suffix; /* Unused */
2833 char *mode;
2834 int type;
2835 FILE *fp;
2836
Guido van Rossum43713e52000-02-29 13:59:29 +00002837 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002838 &name, &fob, &pathname,
2839 &suffix, &mode, &type))
2840 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002841 if (*mode) {
2842 /* Mode must start with 'r' or 'U' and must not contain '+'.
2843 Implicit in this test is the assumption that the mode
2844 may contain other modifiers like 'b' or 't'. */
2845
2846 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002847 PyErr_Format(PyExc_ValueError,
2848 "invalid file open mode %.200s", mode);
2849 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002850 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002851 }
2852 if (fob == Py_None)
2853 fp = NULL;
2854 else {
2855 if (!PyFile_Check(fob)) {
2856 PyErr_SetString(PyExc_ValueError,
2857 "load_module arg#2 should be a file or None");
2858 return NULL;
2859 }
2860 fp = get_file(pathname, fob, mode);
2861 if (fp == NULL)
2862 return NULL;
2863 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002864 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002865}
2866
2867static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002868imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002869{
2870 char *name;
2871 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002872 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002873 return NULL;
2874 return load_package(name, pathname);
2875}
2876
2877static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002878imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002879{
2880 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002881 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002882 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002883 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002884}
2885
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002886/* Doc strings */
2887
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002888PyDoc_STRVAR(doc_imp,
2889"This module provides the components needed to build your own\n\
2890__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002891
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002892PyDoc_STRVAR(doc_find_module,
2893"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002894Search for a module. If path is omitted or None, search for a\n\
2895built-in, frozen or special module and continue search in sys.path.\n\
2896The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002897package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002898
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002899PyDoc_STRVAR(doc_load_module,
2900"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002901Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002902The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002903
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002904PyDoc_STRVAR(doc_get_magic,
2905"get_magic() -> string\n\
2906Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002907
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002908PyDoc_STRVAR(doc_get_suffixes,
2909"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002910Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002911that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002912
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002913PyDoc_STRVAR(doc_new_module,
2914"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002915Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002916The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002917
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002918PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002919"lock_held() -> boolean\n\
2920Return True if the import lock is currently held, else False.\n\
2921On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002922
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002923PyDoc_STRVAR(doc_acquire_lock,
2924"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002925Acquires the interpreter's import lock for the current thread.\n\
2926This lock should be used by import hooks to ensure thread-safety\n\
2927when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002928On platforms without threads, this function does nothing.");
2929
2930PyDoc_STRVAR(doc_release_lock,
2931"release_lock() -> None\n\
2932Release the interpreter's import lock.\n\
2933On platforms without threads, this function does nothing.");
2934
Guido van Rossum79f25d91997-04-29 20:08:16 +00002935static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002936 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2937 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2938 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2939 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2940 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2941 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2942 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2943 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002944 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00002945 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2946 {"init_builtin", imp_init_builtin, METH_VARARGS},
2947 {"init_frozen", imp_init_frozen, METH_VARARGS},
2948 {"is_builtin", imp_is_builtin, METH_VARARGS},
2949 {"is_frozen", imp_is_frozen, METH_VARARGS},
2950 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002951#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00002952 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002953#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002954 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00002955 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002956 {NULL, NULL} /* sentinel */
2957};
2958
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002959static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002960setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002961{
2962 PyObject *v;
2963 int err;
2964
2965 v = PyInt_FromLong((long)value);
2966 err = PyDict_SetItemString(d, name, v);
2967 Py_XDECREF(v);
2968 return err;
2969}
2970
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00002971typedef struct {
2972 PyObject_HEAD
2973} NullImporter;
2974
2975static int
2976NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
2977{
2978 char *path;
2979
2980 if (!_PyArg_NoKeywords("NullImporter()", kwds))
2981 return -1;
2982
2983 if (!PyArg_ParseTuple(args, "s:NullImporter",
2984 &path))
2985 return -1;
2986
2987 if (strlen(path) == 0) {
2988 PyErr_SetString(PyExc_ImportError, "empty pathname");
2989 return -1;
2990 } else {
2991#ifndef RISCOS
2992 struct stat statbuf;
2993 int rv;
2994
2995 rv = stat(path, &statbuf);
2996 if (rv == 0) {
2997 /* it exists */
2998 if (S_ISDIR(statbuf.st_mode)) {
2999 /* it's a directory */
3000 PyErr_SetString(PyExc_ImportError,
3001 "existing directory");
3002 return -1;
3003 }
3004 }
3005#else
3006 if (object_exists(path)) {
3007 /* it exists */
3008 if (isdir(path)) {
3009 /* it's a directory */
3010 PyErr_SetString(PyExc_ImportError,
3011 "existing directory");
3012 return -1;
3013 }
3014 }
3015#endif
3016 }
3017 return 0;
3018}
3019
3020static PyObject *
3021NullImporter_find_module(NullImporter *self, PyObject *args)
3022{
3023 Py_RETURN_NONE;
3024}
3025
3026static PyMethodDef NullImporter_methods[] = {
3027 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3028 "Always return None"
3029 },
3030 {NULL} /* Sentinel */
3031};
3032
3033
3034static PyTypeObject NullImporterType = {
3035 PyObject_HEAD_INIT(NULL)
3036 0, /*ob_size*/
3037 "imp.NullImporter", /*tp_name*/
3038 sizeof(NullImporter), /*tp_basicsize*/
3039 0, /*tp_itemsize*/
3040 0, /*tp_dealloc*/
3041 0, /*tp_print*/
3042 0, /*tp_getattr*/
3043 0, /*tp_setattr*/
3044 0, /*tp_compare*/
3045 0, /*tp_repr*/
3046 0, /*tp_as_number*/
3047 0, /*tp_as_sequence*/
3048 0, /*tp_as_mapping*/
3049 0, /*tp_hash */
3050 0, /*tp_call*/
3051 0, /*tp_str*/
3052 0, /*tp_getattro*/
3053 0, /*tp_setattro*/
3054 0, /*tp_as_buffer*/
3055 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3056 "Null importer object", /* tp_doc */
3057 0, /* tp_traverse */
3058 0, /* tp_clear */
3059 0, /* tp_richcompare */
3060 0, /* tp_weaklistoffset */
3061 0, /* tp_iter */
3062 0, /* tp_iternext */
3063 NullImporter_methods, /* tp_methods */
3064 0, /* tp_members */
3065 0, /* tp_getset */
3066 0, /* tp_base */
3067 0, /* tp_dict */
3068 0, /* tp_descr_get */
3069 0, /* tp_descr_set */
3070 0, /* tp_dictoffset */
3071 (initproc)NullImporter_init, /* tp_init */
3072 0, /* tp_alloc */
3073 PyType_GenericNew /* tp_new */
3074};
3075
3076
Jason Tishler6bc06ec2003-09-04 11:59:50 +00003077PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003078initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003079{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003080 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003081
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003082 if (PyType_Ready(&NullImporterType) < 0)
3083 goto failure;
3084
Guido van Rossum0207e6d1997-09-09 22:04:42 +00003085 m = Py_InitModule4("imp", imp_methods, doc_imp,
3086 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00003087 if (m == NULL)
3088 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00003089 d = PyModule_GetDict(m);
Neal Norwitz3cb31ac2006-08-13 18:10:47 +00003090 if (d == NULL)
3091 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003092
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003093 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3094 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3095 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3096 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3097 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3098 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3099 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3100 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003101 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003102 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003103
Phillip J. Ebyf7575d02006-07-28 21:12:07 +00003104 Py_INCREF(&NullImporterType);
3105 PyModule_AddObject(m, "NullImporter", (PyObject *)&NullImporterType);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003106 failure:
3107 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003108}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003109
3110
Guido van Rossumb18618d2000-05-03 23:44:39 +00003111/* API for embedding applications that want to add their own entries
3112 to the table of built-in modules. This should normally be called
3113 *before* Py_Initialize(). When the table resize fails, -1 is
3114 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003115
3116 After a similar function by Just van Rossum. */
3117
3118int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003119PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003120{
3121 static struct _inittab *our_copy = NULL;
3122 struct _inittab *p;
3123 int i, n;
3124
3125 /* Count the number of entries in both tables */
3126 for (n = 0; newtab[n].name != NULL; n++)
3127 ;
3128 if (n == 0)
3129 return 0; /* Nothing to do */
3130 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3131 ;
3132
3133 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003134 p = our_copy;
3135 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003136 if (p == NULL)
3137 return -1;
3138
3139 /* Copy the tables into the new memory */
3140 if (our_copy != PyImport_Inittab)
3141 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3142 PyImport_Inittab = our_copy = p;
3143 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3144
3145 return 0;
3146}
3147
3148/* Shorthand to add a single entry given a name and a function */
3149
3150int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003151PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003152{
3153 struct _inittab newtab[2];
3154
3155 memset(newtab, '\0', sizeof newtab);
3156
3157 newtab[0].name = name;
3158 newtab[0].initfunc = initfunc;
3159
3160 return PyImport_ExtendInittab(newtab);
3161}
Anthony Baxterac6bd462006-04-13 02:06:09 +00003162
3163#ifdef __cplusplus
3164}
3165#endif