blob: 21dcbd45d7ab629fb180b3e7efee90d0f00dbafc [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"
Guido van Rossumd8faa362007-04-27 19:54:29 +00007#undef Yield /* undefine macro conflicting with winbase.h */
Neal Norwitzadb69fc2005-12-17 20:54:49 +00008#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00009#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000010#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000011#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000012#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000013#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000014#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000015#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000016#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017
Guido van Rossum55a83382000-09-20 20:31:38 +000018#ifdef HAVE_FCNTL_H
19#include <fcntl.h>
20#endif
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000021#ifdef __cplusplus
22extern "C" {
23#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000024
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000025extern time_t PyOS_GetLastModificationTime(char *, FILE *);
26 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000027
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000028/* Magic word to reject .pyc files generated by other Python versions.
29 It should change for each incompatible change to the bytecode.
30
31 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000032 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000033 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000034
Guido van Rossum45aecf42006-03-15 04:58:47 +000035 The magic numbers must be spaced apart at least 2 values, as the
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000036 -U interpeter flag will cause MAGIC+1 being used. They have been
37 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000038
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000039 There were a variety of old schemes for setting the magic number.
40 The current working scheme is to increment the previous value by
41 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000042
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000043 Known values:
44 Python 1.5: 20121
45 Python 1.5.1: 20121
46 Python 1.5.2: 20121
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000047 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000048 Python 2.0: 50823
49 Python 2.0.1: 50823
50 Python 2.1: 60202
51 Python 2.1.1: 60202
52 Python 2.1.2: 60202
53 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000054 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000055 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000056 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000057 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000058 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000059 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000060 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000061 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000062 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000063 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Thomas Wouters0e3f5912006-08-11 14:57:12 +000064 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
65 Python 2.5b3: 62111 (fix wrong code: x += yield)
66 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
67 storing constants that should have been removed)
Thomas Wouters89f507f2006-12-13 04:49:30 +000068 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
69 Python 2.6a0: 62141 (peephole optimizations)
Guido van Rossum45aecf42006-03-15 04:58:47 +000070 Python 3000: 3000
Brett Cannone2e23ef2006-08-25 05:05:30 +000071 3010 (removed UNARY_CONVERT)
Guido van Rossum86e58e22006-08-28 15:27:34 +000072 3020 (added BUILD_SET)
Guido van Rossum4f72a782006-10-27 23:31:49 +000073 3030 (added keyword-only parameters)
Guido van Rossum3203bdc2006-12-28 21:03:31 +000074 3040 (added signature annotations)
Guido van Rossum452bf512007-02-09 05:32:43 +000075 3050 (print becomes a function)
Guido van Rossum52cc1d82007-03-18 15:41:51 +000076 3060 (PEP 3115 metaclass syntax)
Guido van Rossum00bc0e02007-10-15 02:52:41 +000077 3070 (PEP 3109 raise changes)
78 3080 (PEP 3137 make __file__ and __name__ unicode)
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000079.
Tim Peters36515e22001-11-18 04:06:29 +000080*/
Guido van Rossum00bc0e02007-10-15 02:52:41 +000081#define MAGIC (3080 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000082
Guido van Rossum96774c12000-05-01 20:19:08 +000083/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000084 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000085 compiler works which are enabled by command line switches. */
86static long pyc_magic = MAGIC;
87
Guido van Rossum25ce5661997-08-02 03:10:38 +000088/* See _PyImport_FixupExtension() below */
89static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000090
Guido van Rossum771c6c81997-10-31 18:37:24 +000091/* This table is defined in config.c: */
92extern struct _inittab _PyImport_Inittab[];
93
94struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000095
Guido van Rossumed1170e1999-12-20 21:23:41 +000096/* these tables define the module suffixes that Python recognizes */
97struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +000098
Guido van Rossumed1170e1999-12-20 21:23:41 +000099static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +0000100 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000101#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +0000102 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +0000103#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000104 {".pyc", "rb", PY_COMPILED},
105 {0, 0}
106};
107
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000108static PyTypeObject NullImporterType; /* Forward reference */
109
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000110/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111
112void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000113_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000115 const struct filedescr *scan;
116 struct filedescr *filetab;
117 int countD = 0;
118 int countS = 0;
119
120 /* prepare _PyImport_Filetab: copy entries from
121 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
122 */
Guido van Rossum04110fb2007-08-24 16:32:05 +0000123#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000124 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
125 ++countD;
Guido van Rossum04110fb2007-08-24 16:32:05 +0000126#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000127 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
128 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000129 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000130 if (filetab == NULL)
131 Py_FatalError("Can't initialize import file table.");
Guido van Rossum04110fb2007-08-24 16:32:05 +0000132#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossumed1170e1999-12-20 21:23:41 +0000133 memcpy(filetab, _PyImport_DynLoadFiletab,
134 countD * sizeof(struct filedescr));
Guido van Rossum04110fb2007-08-24 16:32:05 +0000135#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000136 memcpy(filetab + countD, _PyImport_StandardFiletab,
137 countS * sizeof(struct filedescr));
138 filetab[countD + countS].suffix = NULL;
139
140 _PyImport_Filetab = filetab;
141
Guido van Rossum0824f631997-03-11 18:37:35 +0000142 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000143 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
144 for (; filetab->suffix != NULL; filetab++) {
145 if (strcmp(filetab->suffix, ".pyc") == 0)
146 filetab->suffix = ".pyo";
Guido van Rossum0824f631997-03-11 18:37:35 +0000147 }
148 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000149
Guido van Rossum572dbf82007-04-27 23:53:51 +0000150 {
Guido van Rossum96774c12000-05-01 20:19:08 +0000151 /* Fix the pyc_magic so that byte compiled code created
152 using the all-Unicode method doesn't interfere with
153 code created in normal operation mode. */
154 pyc_magic = MAGIC + 1;
155 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000156}
157
Guido van Rossum25ce5661997-08-02 03:10:38 +0000158void
Just van Rossum52e14d62002-12-30 22:08:05 +0000159_PyImportHooks_Init(void)
160{
161 PyObject *v, *path_hooks = NULL, *zimpimport;
162 int err = 0;
163
164 /* adding sys.path_hooks and sys.path_importer_cache, setting up
165 zipimport */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000166 if (PyType_Ready(&NullImporterType) < 0)
167 goto error;
Just van Rossum52e14d62002-12-30 22:08:05 +0000168
169 if (Py_VerboseFlag)
170 PySys_WriteStderr("# installing zipimport hook\n");
171
172 v = PyList_New(0);
173 if (v == NULL)
174 goto error;
175 err = PySys_SetObject("meta_path", v);
176 Py_DECREF(v);
177 if (err)
178 goto error;
179 v = PyDict_New();
180 if (v == NULL)
181 goto error;
182 err = PySys_SetObject("path_importer_cache", v);
183 Py_DECREF(v);
184 if (err)
185 goto error;
186 path_hooks = PyList_New(0);
187 if (path_hooks == NULL)
188 goto error;
189 err = PySys_SetObject("path_hooks", path_hooks);
190 if (err) {
191 error:
192 PyErr_Print();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000193 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
194 "path_importer_cache, or NullImporter failed"
195 );
Just van Rossum52e14d62002-12-30 22:08:05 +0000196 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000197
Just van Rossum52e14d62002-12-30 22:08:05 +0000198 zimpimport = PyImport_ImportModule("zipimport");
199 if (zimpimport == NULL) {
200 PyErr_Clear(); /* No zip import module -- okay */
201 if (Py_VerboseFlag)
202 PySys_WriteStderr("# can't import zipimport\n");
203 }
204 else {
205 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
206 "zipimporter");
207 Py_DECREF(zimpimport);
208 if (zipimporter == NULL) {
209 PyErr_Clear(); /* No zipimporter object -- okay */
210 if (Py_VerboseFlag)
211 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000212 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000213 }
214 else {
215 /* sys.path_hooks.append(zipimporter) */
216 err = PyList_Append(path_hooks, zipimporter);
217 Py_DECREF(zipimporter);
218 if (err)
219 goto error;
220 if (Py_VerboseFlag)
221 PySys_WriteStderr(
222 "# installed zipimport hook\n");
223 }
224 }
225 Py_DECREF(path_hooks);
226}
227
228void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000229_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000230{
231 Py_XDECREF(extensions);
232 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000233 PyMem_DEL(_PyImport_Filetab);
234 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000235}
236
237
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000238/* Locking primitives to prevent parallel imports of the same module
239 in different threads to return with a partially loaded module.
240 These calls are serialized by the global interpreter lock. */
241
242#ifdef WITH_THREAD
243
Guido van Rossum49b56061998-10-01 20:42:43 +0000244#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000245
Guido van Rossum65d5b571998-12-21 19:32:43 +0000246static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000247static long import_lock_thread = -1;
248static int import_lock_level = 0;
249
250static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000251lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000252{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000253 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000254 if (me == -1)
255 return; /* Too bad */
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000256 if (import_lock == NULL) {
Guido van Rossum65d5b571998-12-21 19:32:43 +0000257 import_lock = PyThread_allocate_lock();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000258 if (import_lock == NULL)
259 return; /* Nothing much we can do. */
260 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000261 if (import_lock_thread == me) {
262 import_lock_level++;
263 return;
264 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000265 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
266 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000267 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000268 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000269 PyEval_RestoreThread(tstate);
270 }
271 import_lock_thread = me;
272 import_lock_level = 1;
273}
274
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000275static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000276unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000277{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000278 long me = PyThread_get_thread_ident();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000279 if (me == -1 || import_lock == NULL)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000280 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000281 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000282 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000283 import_lock_level--;
284 if (import_lock_level == 0) {
285 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000286 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000287 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000288 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000289}
290
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000291/* This function is called from PyOS_AfterFork to ensure that newly
292 created child processes do not share locks with the parent. */
293
294void
295_PyImport_ReInitLock(void)
296{
297#ifdef _AIX
298 if (import_lock != NULL)
299 import_lock = PyThread_allocate_lock();
300#endif
301}
302
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000303#else
304
305#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000306#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000307
308#endif
309
Tim Peters69232342001-08-30 05:16:13 +0000310static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000311imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000312{
Tim Peters69232342001-08-30 05:16:13 +0000313#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000314 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000315#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000316 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000317#endif
318}
319
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000320static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000321imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000322{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000323#ifdef WITH_THREAD
324 lock_import();
325#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000326 Py_INCREF(Py_None);
327 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000328}
329
330static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000331imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000332{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000333#ifdef WITH_THREAD
334 if (unlock_import() < 0) {
335 PyErr_SetString(PyExc_RuntimeError,
336 "not holding the import lock");
337 return NULL;
338 }
339#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000340 Py_INCREF(Py_None);
341 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000342}
343
Guido van Rossumd8faa362007-04-27 19:54:29 +0000344static void
345imp_modules_reloading_clear(void)
346{
347 PyInterpreterState *interp = PyThreadState_Get()->interp;
348 if (interp->modules_reloading != NULL)
349 PyDict_Clear(interp->modules_reloading);
350}
351
Guido van Rossum25ce5661997-08-02 03:10:38 +0000352/* Helper for sys */
353
354PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000355PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000356{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000357 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000358 if (interp->modules == NULL)
359 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
360 return interp->modules;
361}
362
Guido van Rossum3f5da241990-12-20 15:06:42 +0000363
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000364/* List of names to clear in sys */
365static char* sys_deletes[] = {
Collin Winter670e6922007-03-21 02:57:17 +0000366 "path", "argv", "ps1", "ps2",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000367 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000368 "path_hooks", "path_importer_cache", "meta_path",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000369 NULL
370};
371
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000372static char* sys_files[] = {
373 "stdin", "__stdin__",
374 "stdout", "__stdout__",
375 "stderr", "__stderr__",
376 NULL
377};
378
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000379
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000380/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000381
Guido van Rossum3f5da241990-12-20 15:06:42 +0000382void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000383PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000384{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000385 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000386 char *name;
387 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000388 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000389 PyObject *modules = interp->modules;
390
391 if (modules == NULL)
392 return; /* Already done */
393
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000394 /* Delete some special variables first. These are common
395 places where user values hide and people complain when their
396 destructors fail. Since the modules containing them are
397 deleted *last* of all, they would come too late in the normal
398 destruction order. Sigh. */
399
400 value = PyDict_GetItemString(modules, "__builtin__");
401 if (value != NULL && PyModule_Check(value)) {
402 dict = PyModule_GetDict(value);
403 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000404 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000405 PyDict_SetItemString(dict, "_", Py_None);
406 }
407 value = PyDict_GetItemString(modules, "sys");
408 if (value != NULL && PyModule_Check(value)) {
409 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000410 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000411 dict = PyModule_GetDict(value);
412 for (p = sys_deletes; *p != NULL; p++) {
413 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000414 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000415 PyDict_SetItemString(dict, *p, Py_None);
416 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000417 for (p = sys_files; *p != NULL; p+=2) {
418 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000419 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000420 v = PyDict_GetItemString(dict, *(p+1));
421 if (v == NULL)
422 v = Py_None;
423 PyDict_SetItemString(dict, *p, v);
424 }
425 }
426
427 /* First, delete __main__ */
428 value = PyDict_GetItemString(modules, "__main__");
429 if (value != NULL && PyModule_Check(value)) {
430 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000431 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000432 _PyModule_Clear(value);
433 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000434 }
435
Guido van Rossum758eec01998-01-19 21:58:26 +0000436 /* The special treatment of __builtin__ here is because even
437 when it's not referenced as a module, its dictionary is
438 referenced by almost every module's __builtins__. Since
439 deleting a module clears its dictionary (even if there are
440 references left to it), we need to delete the __builtin__
441 module last. Likewise, we don't delete sys until the very
442 end because it is implicitly referenced (e.g. by print).
443
444 Also note that we 'delete' modules by replacing their entry
445 in the modules dict with None, rather than really deleting
446 them; this avoids a rehash of the modules dictionary and
447 also marks them as "non existent" so they won't be
448 re-imported. */
449
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000450 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000451 one (skipping __builtin__ and sys) and delete them */
452 do {
453 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000454 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000455 while (PyDict_Next(modules, &pos, &key, &value)) {
456 if (value->ob_refcnt != 1)
457 continue;
Neal Norwitz80e7f272007-08-26 06:45:23 +0000458 if (PyUnicode_Check(key) && PyModule_Check(value)) {
459 name = PyUnicode_AsString(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000460 if (strcmp(name, "__builtin__") == 0)
461 continue;
462 if (strcmp(name, "sys") == 0)
463 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000464 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000465 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000466 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000467 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000468 PyDict_SetItem(modules, key, Py_None);
469 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000470 }
471 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000472 } while (ndone > 0);
473
Guido van Rossum758eec01998-01-19 21:58:26 +0000474 /* Next, delete all modules (still skipping __builtin__ and sys) */
475 pos = 0;
476 while (PyDict_Next(modules, &pos, &key, &value)) {
Neal Norwitz80e7f272007-08-26 06:45:23 +0000477 if (PyUnicode_Check(key) && PyModule_Check(value)) {
478 name = PyUnicode_AsString(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000479 if (strcmp(name, "__builtin__") == 0)
480 continue;
481 if (strcmp(name, "sys") == 0)
482 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000483 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000484 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000485 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000486 PyDict_SetItem(modules, key, Py_None);
487 }
488 }
489
490 /* Next, delete sys and __builtin__ (in that order) */
491 value = PyDict_GetItemString(modules, "sys");
492 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000493 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000494 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000495 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000496 PyDict_SetItemString(modules, "sys", Py_None);
497 }
498 value = PyDict_GetItemString(modules, "__builtin__");
499 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000500 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000501 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000502 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000503 PyDict_SetItemString(modules, "__builtin__", Py_None);
504 }
505
506 /* Finally, clear and delete the modules directory */
507 PyDict_Clear(modules);
508 interp->modules = NULL;
509 Py_DECREF(modules);
Guido van Rossumd8faa362007-04-27 19:54:29 +0000510 Py_CLEAR(interp->modules_reloading);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000511}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000512
513
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000514/* Helper for pythonrun.c -- return magic number */
515
516long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000517PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000518{
Guido van Rossum96774c12000-05-01 20:19:08 +0000519 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000520}
521
522
Guido van Rossum25ce5661997-08-02 03:10:38 +0000523/* Magic for extension modules (built-in as well as dynamically
524 loaded). To prevent initializing an extension module more than
525 once, we keep a static dictionary 'extensions' keyed by module name
526 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000527 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000528 dictionary is stored by calling _PyImport_FixupExtension()
529 immediately after the module initialization function succeeds. A
530 copy can be retrieved from there by calling
531 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000532
Guido van Rossum79f25d91997-04-29 20:08:16 +0000533PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000534_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000535{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000536 PyObject *modules, *mod, *dict, *copy;
537 if (extensions == NULL) {
538 extensions = PyDict_New();
539 if (extensions == NULL)
540 return NULL;
541 }
542 modules = PyImport_GetModuleDict();
543 mod = PyDict_GetItemString(modules, name);
544 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000545 PyErr_Format(PyExc_SystemError,
546 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000547 return NULL;
548 }
549 dict = PyModule_GetDict(mod);
550 if (dict == NULL)
551 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000552 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000553 if (copy == NULL)
554 return NULL;
555 PyDict_SetItemString(extensions, filename, copy);
556 Py_DECREF(copy);
557 return copy;
558}
559
560PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000561_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000563 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000564 if (extensions == NULL)
565 return NULL;
566 dict = PyDict_GetItemString(extensions, filename);
567 if (dict == NULL)
568 return NULL;
569 mod = PyImport_AddModule(name);
570 if (mod == NULL)
571 return NULL;
572 mdict = PyModule_GetDict(mod);
573 if (mdict == NULL)
574 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000575 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000577 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000578 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000579 name, filename);
580 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000581}
582
583
584/* Get the module object corresponding to a module name.
585 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000586 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000587 Because the former action is most common, THIS DOES NOT RETURN A
588 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000589
Guido van Rossum79f25d91997-04-29 20:08:16 +0000590PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000591PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000592{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000593 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000594 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000595
Guido van Rossum25ce5661997-08-02 03:10:38 +0000596 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000597 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000598 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000599 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000600 if (m == NULL)
601 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000602 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000603 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000604 return NULL;
605 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000606 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000607
608 return m;
609}
610
Tim Peters1cd70172004-08-02 03:52:12 +0000611/* Remove name from sys.modules, if it's there. */
612static void
613_RemoveModule(const char *name)
614{
615 PyObject *modules = PyImport_GetModuleDict();
616 if (PyDict_GetItemString(modules, name) == NULL)
617 return;
618 if (PyDict_DelItemString(modules, name) < 0)
619 Py_FatalError("import: deleting existing key in"
620 "sys.modules failed");
621}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000622
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000623/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000624 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
625 * removed from sys.modules, to avoid leaving damaged module objects
626 * in sys.modules. The caller may wish to restore the original
627 * module object (if any) in this case; PyImport_ReloadModule is an
628 * example.
629 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000630PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000631PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000632{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000633 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
634}
635
636PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000637PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000638{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000639 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000640 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000641
Guido van Rossum79f25d91997-04-29 20:08:16 +0000642 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000643 if (m == NULL)
644 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000645 /* If the module is being reloaded, we get the old module back
646 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000647 d = PyModule_GetDict(m);
648 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
649 if (PyDict_SetItemString(d, "__builtins__",
650 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000651 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000652 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000653 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000654 v = NULL;
655 if (pathname != NULL) {
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000656 v = PyUnicode_DecodeFSDefault(pathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000657 if (v == NULL)
658 PyErr_Clear();
659 }
660 if (v == NULL) {
661 v = ((PyCodeObject *)co)->co_filename;
662 Py_INCREF(v);
663 }
664 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000665 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000666 Py_DECREF(v);
667
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000668 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000669 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000670 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000671 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000672
Guido van Rossum25ce5661997-08-02 03:10:38 +0000673 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000674 PyErr_Format(PyExc_ImportError,
675 "Loaded module %.200s not found in sys.modules",
676 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000677 return NULL;
678 }
679
Guido van Rossum79f25d91997-04-29 20:08:16 +0000680 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000681
682 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000683
684 error:
685 _RemoveModule(name);
686 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000687}
688
689
690/* Given a pathname for a Python source file, fill a buffer with the
691 pathname for the corresponding compiled file. Return the pathname
692 for the compiled file, or NULL if there's no space in the buffer.
693 Doesn't set an exception. */
694
695static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000696make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000697{
Tim Petersc1731372001-08-04 08:12:36 +0000698 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000699 if (len+2 > buflen)
700 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000701
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000702#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000703 /* Treat .pyw as if it were .py. The case of ".pyw" must match
704 that used in _PyImport_StandardFiletab. */
705 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
706 --len; /* pretend 'w' isn't there */
707#endif
708 memcpy(buf, pathname, len);
709 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
710 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000711
712 return buf;
713}
714
715
716/* Given a pathname for a Python source file, its time of last
717 modification, and a pathname for a compiled file, check whether the
718 compiled file represents the same version of the source. If so,
719 return a FILE pointer for the compiled file, positioned just after
720 the header; if not, return NULL.
721 Doesn't set an exception. */
722
723static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000724check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000725{
726 FILE *fp;
727 long magic;
728 long pyc_mtime;
729
730 fp = fopen(cpathname, "rb");
731 if (fp == NULL)
732 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000733 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000734 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000735 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000736 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737 fclose(fp);
738 return NULL;
739 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000740 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000741 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000742 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000743 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000744 fclose(fp);
745 return NULL;
746 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000747 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000748 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000749 return fp;
750}
751
752
753/* Read a code object from a file and check it for validity */
754
Guido van Rossum79f25d91997-04-29 20:08:16 +0000755static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000756read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000757{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000758 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000759
Tim Petersd9b9ac82001-01-28 00:27:39 +0000760 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000761 if (co == NULL)
762 return NULL;
763 if (!PyCode_Check(co)) {
764 PyErr_Format(PyExc_ImportError,
765 "Non-code object in %.200s", cpathname);
766 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000767 return NULL;
768 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000769 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000770}
771
772
773/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000774 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000775
Guido van Rossum79f25d91997-04-29 20:08:16 +0000776static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000777load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000778{
779 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000780 PyCodeObject *co;
781 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000782
Guido van Rossum79f25d91997-04-29 20:08:16 +0000783 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000784 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000785 PyErr_Format(PyExc_ImportError,
786 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000787 return NULL;
788 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000789 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000790 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000791 if (co == NULL)
792 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000793 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000794 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000795 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000796 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000797 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000798
799 return m;
800}
801
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000802/* Parse a source file and return the corresponding code object */
803
Guido van Rossum79f25d91997-04-29 20:08:16 +0000804static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000805parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000806{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000807 PyCodeObject *co = NULL;
808 mod_ty mod;
Thomas Wouters89f507f2006-12-13 04:49:30 +0000809 PyArena *arena = PyArena_New();
810 if (arena == NULL)
811 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000812
Martin v. Löwis85bcc662007-09-04 09:18:06 +0000813 mod = PyParser_ASTFromFile(fp, pathname, NULL,
814 Py_file_input, 0, 0, 0,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000815 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000816 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000817 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000818 }
Thomas Wouters89f507f2006-12-13 04:49:30 +0000819 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000820 return co;
821}
822
823
Guido van Rossum55a83382000-09-20 20:31:38 +0000824/* Helper to open a bytecode file for writing in exclusive mode */
825
826static FILE *
827open_exclusive(char *filename)
828{
829#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
830 /* Use O_EXCL to avoid a race condition when another process tries to
831 write the same file. When that happens, our open() call fails,
832 which is just fine (since it's only a cache).
833 XXX If the file exists and is writable but the directory is not
834 writable, the file will never be written. Oh well.
835 */
836 int fd;
837 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000838 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
839#ifdef O_BINARY
840 |O_BINARY /* necessary for Windows */
841#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000842#ifdef __VMS
Martin v. Löwis18e16552006-02-15 17:27:45 +0000843 , 0666, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000844#else
Martin v. Löwis18e16552006-02-15 17:27:45 +0000845 , 0666
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000846#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000847 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000848 if (fd < 0)
849 return NULL;
850 return fdopen(fd, "wb");
851#else
852 /* Best we can do -- on Windows this can't happen anyway */
853 return fopen(filename, "wb");
854#endif
855}
856
857
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000858/* Write a compiled module to a file, placing the time of last
859 modification of its source into the header.
860 Errors are ignored, if a write error occurs an attempt is made to
861 remove the file. */
862
863static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000864write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000865{
866 FILE *fp;
867
Guido van Rossum55a83382000-09-20 20:31:38 +0000868 fp = open_exclusive(cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000869 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000870 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000871 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000872 "# can't create %s\n", cpathname);
873 return;
874 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000875 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000876 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000877 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
878 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000879 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000880 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000881 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000882 /* Don't keep partial file */
883 fclose(fp);
884 (void) unlink(cpathname);
885 return;
886 }
887 /* Now write the true mtime */
888 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000889 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000890 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000891 fflush(fp);
892 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000893 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000894 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000895}
896
897
898/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000899 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
900 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000901
Guido van Rossum79f25d91997-04-29 20:08:16 +0000902static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000903load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000904{
Fred Drake4c82b232000-06-30 16:18:57 +0000905 time_t mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000906 FILE *fpc;
907 char buf[MAXPATHLEN+1];
908 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000909 PyCodeObject *co;
910 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000911
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000912 mtime = PyOS_GetLastModificationTime(pathname, fp);
Neal Norwitz708e51a2005-10-03 04:48:15 +0000913 if (mtime == (time_t)(-1)) {
914 PyErr_Format(PyExc_RuntimeError,
915 "unable to get modification time from '%s'",
916 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000917 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000918 }
Fred Drake4c82b232000-06-30 16:18:57 +0000919#if SIZEOF_TIME_T > 4
920 /* Python's .pyc timestamp handling presumes that the timestamp fits
921 in 4 bytes. This will be fine until sometime in the year 2038,
922 when a 4-byte signed time_t will overflow.
923 */
924 if (mtime >> 32) {
925 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000926 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000927 return NULL;
928 }
929#endif
Tim Peters36515e22001-11-18 04:06:29 +0000930 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000931 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000932 if (cpathname != NULL &&
933 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000934 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000935 fclose(fpc);
936 if (co == NULL)
937 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000938 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000939 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000940 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000941 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000942 }
943 else {
944 co = parse_source_module(pathname, fp);
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 # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000949 name, pathname);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000950 if (cpathname)
951 write_compiled_module(co, cpathname, mtime);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000952 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000953 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000954 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000955
956 return m;
957}
958
959
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000960/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +0000961static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
962static struct filedescr *find_module(char *, char *, PyObject *,
963 char *, size_t, FILE **, PyObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000964static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000965
966/* Load a package and return its module object WITH INCREMENTED
967 REFERENCE COUNT */
968
969static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000970load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000971{
Tim Peters1cd70172004-08-02 03:52:12 +0000972 PyObject *m, *d;
973 PyObject *file = NULL;
974 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000975 int err;
976 char buf[MAXPATHLEN+1];
977 FILE *fp = NULL;
978 struct filedescr *fdp;
979
980 m = PyImport_AddModule(name);
981 if (m == NULL)
982 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000983 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000984 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000985 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000986 d = PyModule_GetDict(m);
Guido van Rossum00bc0e02007-10-15 02:52:41 +0000987 file = PyUnicode_DecodeFSDefault(pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000988 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000989 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000990 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +0000991 if (path == NULL)
992 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000993 err = PyDict_SetItemString(d, "__file__", file);
994 if (err == 0)
995 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +0000996 if (err != 0)
997 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000998 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +0000999 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001000 if (fdp == NULL) {
1001 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1002 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +00001003 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001004 }
1005 else
1006 m = NULL;
1007 goto cleanup;
1008 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001009 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001010 if (fp != NULL)
1011 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00001012 goto cleanup;
1013
1014 error:
1015 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001016 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001017 Py_XDECREF(path);
1018 Py_XDECREF(file);
1019 return m;
1020}
1021
1022
1023/* Helper to test for built-in module */
1024
1025static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001026is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001027{
1028 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001029 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1030 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1031 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001032 return -1;
1033 else
1034 return 1;
1035 }
1036 }
1037 return 0;
1038}
1039
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001040
Just van Rossum52e14d62002-12-30 22:08:05 +00001041/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1042 possibly by fetching it from the path_importer_cache dict. If it
Thomas Wouters89f507f2006-12-13 04:49:30 +00001043 wasn't yet cached, traverse path_hooks until a hook is found
Just van Rossum52e14d62002-12-30 22:08:05 +00001044 that can handle the path item. Return None if no hook could;
1045 this tells our caller it should fall back to the builtin
1046 import mechanism. Cache the result in path_importer_cache.
1047 Returns a borrowed reference. */
1048
1049static PyObject *
1050get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1051 PyObject *p)
1052{
1053 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001054 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001055
1056 /* These conditions are the caller's responsibility: */
1057 assert(PyList_Check(path_hooks));
1058 assert(PyDict_Check(path_importer_cache));
1059
1060 nhooks = PyList_Size(path_hooks);
1061 if (nhooks < 0)
1062 return NULL; /* Shouldn't happen */
1063
1064 importer = PyDict_GetItem(path_importer_cache, p);
1065 if (importer != NULL)
1066 return importer;
1067
1068 /* set path_importer_cache[p] to None to avoid recursion */
1069 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1070 return NULL;
1071
1072 for (j = 0; j < nhooks; j++) {
1073 PyObject *hook = PyList_GetItem(path_hooks, j);
1074 if (hook == NULL)
1075 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001076 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001077 if (importer != NULL)
1078 break;
1079
1080 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1081 return NULL;
1082 }
1083 PyErr_Clear();
1084 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001085 if (importer == NULL) {
1086 importer = PyObject_CallFunctionObjArgs(
1087 (PyObject *)&NullImporterType, p, NULL
1088 );
1089 if (importer == NULL) {
1090 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1091 PyErr_Clear();
1092 return Py_None;
1093 }
1094 }
1095 }
1096 if (importer != NULL) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001097 int err = PyDict_SetItem(path_importer_cache, p, importer);
1098 Py_DECREF(importer);
1099 if (err != 0)
1100 return NULL;
1101 }
1102 return importer;
1103}
1104
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001105/* Search the path (default sys.path) for a module. Return the
1106 corresponding filedescr struct, and (via return arguments) the
1107 pathname and an open file. Return NULL if the module is not found. */
1108
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001109#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001110extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001111 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001112#endif
1113
Martin v. Löwis18e16552006-02-15 17:27:45 +00001114static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001115static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001116static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001117
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001118static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001119find_module(char *fullname, char *subname, PyObject *path, char *buf,
1120 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001121{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001122 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001123 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001124 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001125 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001126 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001127 PyObject *path_hooks, *path_importer_cache;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001128 struct stat statbuf;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001129 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1130 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1131 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001132 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001133#if defined(PYOS_OS2)
1134 size_t saved_len;
1135 size_t saved_namelen;
1136 char *saved_buf = NULL;
1137#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001138 if (p_loader != NULL)
1139 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001140
Just van Rossum52e14d62002-12-30 22:08:05 +00001141 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001142 PyErr_SetString(PyExc_OverflowError,
1143 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001144 return NULL;
1145 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001146 strcpy(name, subname);
1147
1148 /* sys.meta_path import hook */
1149 if (p_loader != NULL) {
1150 PyObject *meta_path;
1151
1152 meta_path = PySys_GetObject("meta_path");
1153 if (meta_path == NULL || !PyList_Check(meta_path)) {
1154 PyErr_SetString(PyExc_ImportError,
1155 "sys.meta_path must be a list of "
1156 "import hooks");
1157 return NULL;
1158 }
1159 Py_INCREF(meta_path); /* zap guard */
1160 npath = PyList_Size(meta_path);
1161 for (i = 0; i < npath; i++) {
1162 PyObject *loader;
1163 PyObject *hook = PyList_GetItem(meta_path, i);
1164 loader = PyObject_CallMethod(hook, "find_module",
1165 "sO", fullname,
1166 path != NULL ?
1167 path : Py_None);
1168 if (loader == NULL) {
1169 Py_DECREF(meta_path);
1170 return NULL; /* true error */
1171 }
1172 if (loader != Py_None) {
1173 /* a loader was found */
1174 *p_loader = loader;
1175 Py_DECREF(meta_path);
1176 return &importhookdescr;
1177 }
1178 Py_DECREF(loader);
1179 }
1180 Py_DECREF(meta_path);
1181 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001182
Guido van Rossum13d77992007-07-23 03:16:50 +00001183 if (path != NULL && PyUnicode_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001184 /* The only type of submodule allowed inside a "frozen"
1185 package are other frozen modules or packages. */
Guido van Rossum13d77992007-07-23 03:16:50 +00001186 char *p = PyUnicode_AsString(path);
1187 if (strlen(p) + 1 + strlen(name) >= (size_t)buflen) {
Guido van Rossum0506a431998-08-11 15:07:39 +00001188 PyErr_SetString(PyExc_ImportError,
1189 "full frozen module name too long");
1190 return NULL;
1191 }
Guido van Rossum13d77992007-07-23 03:16:50 +00001192 strcpy(buf, p);
Guido van Rossum0506a431998-08-11 15:07:39 +00001193 strcat(buf, ".");
1194 strcat(buf, name);
1195 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001196 if (find_frozen(name) != NULL) {
1197 strcpy(buf, name);
1198 return &fd_frozen;
1199 }
1200 PyErr_Format(PyExc_ImportError,
1201 "No frozen submodule named %.200s", name);
1202 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001203 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001204 if (path == NULL) {
1205 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001206 strcpy(buf, name);
1207 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001208 }
Greg Ward201baee2001-10-04 14:52:06 +00001209 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001210 strcpy(buf, name);
1211 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001212 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001213
Guido van Rossumac279101996-08-22 23:10:58 +00001214#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001215 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1216 if (fp != NULL) {
1217 *p_fp = fp;
1218 return fdp;
1219 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001220#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001221 path = PySys_GetObject("path");
1222 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001223 if (path == NULL || !PyList_Check(path)) {
1224 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001225 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001226 return NULL;
1227 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001228
1229 path_hooks = PySys_GetObject("path_hooks");
1230 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1231 PyErr_SetString(PyExc_ImportError,
1232 "sys.path_hooks must be a list of "
1233 "import hooks");
1234 return NULL;
1235 }
1236 path_importer_cache = PySys_GetObject("path_importer_cache");
1237 if (path_importer_cache == NULL ||
1238 !PyDict_Check(path_importer_cache)) {
1239 PyErr_SetString(PyExc_ImportError,
1240 "sys.path_importer_cache must be a dict");
1241 return NULL;
1242 }
1243
Guido van Rossum79f25d91997-04-29 20:08:16 +00001244 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001245 namelen = strlen(name);
1246 for (i = 0; i < npath; i++) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001247 PyObject *v = PyList_GetItem(path, i);
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001248 PyObject *origv = v;
Guido van Rossum6262cc72007-05-09 23:29:27 +00001249 const char *base;
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001250 Py_ssize_t size;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001251 if (!v)
1252 return NULL;
Guido van Rossuma4b8d1d2007-08-27 15:02:28 +00001253 if (PyUnicode_Check(v)) {
1254 v = _PyUnicode_AsDefaultEncodedString(v, NULL);
1255 if (v == NULL)
1256 return NULL;
1257 }
1258 if (!PyString_Check(v))
1259 continue;
1260 base = PyString_AS_STRING(v);
1261 size = PyString_GET_SIZE(v);
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001262 len = size;
Walter Dörwald3430d702002-06-17 10:43:59 +00001263 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001264 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001265 }
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001266 strcpy(buf, base);
Walter Dörwald3430d702002-06-17 10:43:59 +00001267 if (strlen(buf) != len) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001268 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001269 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001270
1271 /* sys.path_hooks import hook */
1272 if (p_loader != NULL) {
1273 PyObject *importer;
1274
1275 importer = get_path_importer(path_importer_cache,
Guido van Rossumf15a29f2007-05-04 00:41:39 +00001276 path_hooks, origv);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001277 if (importer == NULL) {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001278 return NULL;
Thomas Wouters477c8d52006-05-27 19:21:47 +00001279 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001280 /* Note: importer is a borrowed reference */
1281 if (importer != Py_None) {
Just van Rossum52e14d62002-12-30 22:08:05 +00001282 PyObject *loader;
1283 loader = PyObject_CallMethod(importer,
1284 "find_module",
1285 "s", fullname);
1286 if (loader == NULL)
1287 return NULL; /* error */
1288 if (loader != Py_None) {
1289 /* a loader was found */
1290 *p_loader = loader;
1291 return &importhookdescr;
1292 }
1293 Py_DECREF(loader);
Thomas Wouters477c8d52006-05-27 19:21:47 +00001294 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001295 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001296 }
Thomas Wouters477c8d52006-05-27 19:21:47 +00001297 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001298
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001299 if (len > 0 && buf[len-1] != SEP
1300#ifdef ALTSEP
1301 && buf[len-1] != ALTSEP
1302#endif
1303 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001304 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001305 strcpy(buf+len, name);
1306 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001307
1308 /* Check for package import (buf holds a directory name,
1309 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001310#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001311 if (stat(buf, &statbuf) == 0 && /* it exists */
1312 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001313 case_ok(buf, len, namelen, name)) { /* case matches */
1314 if (find_init_module(buf)) { /* and has __init__.py */
Thomas Wouters477c8d52006-05-27 19:21:47 +00001315 return &fd_package;
1316 }
1317 else {
1318 char warnstr[MAXPATHLEN+80];
1319 sprintf(warnstr, "Not importing directory "
1320 "'%.*s': missing __init__.py",
1321 MAXPATHLEN, buf);
Skip Montanaro46fc3372007-08-12 11:44:53 +00001322 if (PyErr_WarnEx(PyExc_ImportWarning,
1323 warnstr, 1)) {
Thomas Wouters477c8d52006-05-27 19:21:47 +00001324 return NULL;
1325 }
1326 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001327 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001328#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001329#if defined(PYOS_OS2)
1330 /* take a snapshot of the module spec for restoration
1331 * after the 8 character DLL hackery
1332 */
1333 saved_buf = strdup(buf);
1334 saved_len = len;
1335 saved_namelen = namelen;
1336#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001337 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum04110fb2007-08-24 16:32:05 +00001338#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001339 /* OS/2 limits DLLs to 8 character names (w/o
1340 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001341 * so if the name is longer than that and its a
1342 * dynamically loaded module we're going to try,
1343 * truncate the name before trying
1344 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001345 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001346 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001347 const struct filedescr *scan;
1348 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001349 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001350 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001351 break;
1352 else
1353 scan++;
1354 }
1355 if (scan->suffix != NULL) {
1356 /* yes, so truncate the name */
1357 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001358 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001359 buf[len] = '\0';
1360 }
1361 }
1362#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001363 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001364 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001365 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001366 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001367 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001368 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001369 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001370 if (fp != NULL) {
1371 if (case_ok(buf, len, namelen, name))
1372 break;
1373 else { /* continue search */
1374 fclose(fp);
1375 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001376 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001377 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001378#if defined(PYOS_OS2)
1379 /* restore the saved snapshot */
1380 strcpy(buf, saved_buf);
1381 len = saved_len;
1382 namelen = saved_namelen;
1383#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001384 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001385#if defined(PYOS_OS2)
1386 /* don't need/want the module name snapshot anymore */
1387 if (saved_buf)
1388 {
1389 free(saved_buf);
1390 saved_buf = NULL;
1391 }
1392#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001393 if (fp != NULL)
1394 break;
1395 }
1396 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001397 PyErr_Format(PyExc_ImportError,
1398 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001399 return NULL;
1400 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001401 *p_fp = fp;
1402 return fdp;
1403}
1404
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001405/* Helpers for main.c
1406 * Find the source file corresponding to a named module
1407 */
1408struct filedescr *
1409_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1410 size_t buflen, FILE **p_fp, PyObject **p_loader)
1411{
1412 return find_module((char *) name, (char *) name, path,
1413 buf, buflen, p_fp, p_loader);
1414}
1415
1416PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1417{
1418 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1419}
1420
Martin v. Löwis18e16552006-02-15 17:27:45 +00001421/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001422 * The arguments here are tricky, best shown by example:
1423 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1424 * ^ ^ ^ ^
1425 * |--------------------- buf ---------------------|
1426 * |------------------- len ------------------|
1427 * |------ name -------|
1428 * |----- namelen -----|
1429 * buf is the full path, but len only counts up to (& exclusive of) the
1430 * extension. name is the module name, also exclusive of extension.
1431 *
1432 * We've already done a successful stat() or fopen() on buf, so know that
1433 * there's some match, possibly case-insensitive.
1434 *
Tim Peters50d8d372001-02-28 05:34:27 +00001435 * case_ok() is to return 1 if there's a case-sensitive match for
1436 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1437 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001438 *
Tim Peters50d8d372001-02-28 05:34:27 +00001439 * case_ok() is used to implement case-sensitive import semantics even
1440 * on platforms with case-insensitive filesystems. It's trivial to implement
1441 * for case-sensitive filesystems. It's pretty much a cross-platform
1442 * nightmare for systems with case-insensitive filesystems.
1443 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001444
Tim Peters50d8d372001-02-28 05:34:27 +00001445/* First we may need a pile of platform-specific header files; the sequence
1446 * of #if's here should match the sequence in the body of case_ok().
1447 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001448#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001449#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001450
Tim Peters50d8d372001-02-28 05:34:27 +00001451#elif defined(DJGPP)
1452#include <dir.h>
1453
Jason Tishler7961aa62005-05-20 00:56:54 +00001454#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001455#include <sys/types.h>
1456#include <dirent.h>
1457
Andrew MacIntyred9400542002-02-26 11:41:34 +00001458#elif defined(PYOS_OS2)
1459#define INCL_DOS
1460#define INCL_DOSERRORS
1461#define INCL_NOPMAPI
1462#include <os2.h>
Tim Peters50d8d372001-02-28 05:34:27 +00001463#endif
1464
Guido van Rossum0980bd91998-02-13 17:18:36 +00001465static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001466case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001467{
Tim Peters50d8d372001-02-28 05:34:27 +00001468/* Pick a platform-specific implementation; the sequence of #if's here should
1469 * match the sequence just above.
1470 */
1471
Jason Tishler7961aa62005-05-20 00:56:54 +00001472/* MS_WINDOWS */
1473#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001474 WIN32_FIND_DATA data;
1475 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001476
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001477 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001478 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001479
Guido van Rossum0980bd91998-02-13 17:18:36 +00001480 h = FindFirstFile(buf, &data);
1481 if (h == INVALID_HANDLE_VALUE) {
1482 PyErr_Format(PyExc_NameError,
1483 "Can't find file for module %.100s\n(filename %.300s)",
1484 name, buf);
1485 return 0;
1486 }
1487 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001488 return strncmp(data.cFileName, name, namelen) == 0;
1489
1490/* DJGPP */
1491#elif defined(DJGPP)
1492 struct ffblk ffblk;
1493 int done;
1494
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001495 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001496 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001497
1498 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1499 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001500 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001501 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001502 name, buf);
1503 return 0;
1504 }
Tim Peters50d8d372001-02-28 05:34:27 +00001505 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001506
Jason Tishler7961aa62005-05-20 00:56:54 +00001507/* new-fangled macintosh (macosx) or Cygwin */
1508#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001509 DIR *dirp;
1510 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001511 char dirname[MAXPATHLEN + 1];
1512 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001513
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001514 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001515 return 1;
1516
Tim Petersd1e87a82001-03-01 18:12:00 +00001517 /* Copy the dir component into dirname; substitute "." if empty */
1518 if (dirlen <= 0) {
1519 dirname[0] = '.';
1520 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001521 }
1522 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001523 assert(dirlen <= MAXPATHLEN);
1524 memcpy(dirname, buf, dirlen);
1525 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001526 }
1527 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001528 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001529 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001530 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001531 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001532 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001533#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001534 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001535#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001536 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001537#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001538 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001539 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001540 (void)closedir(dirp);
1541 return 1; /* Found */
1542 }
1543 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001544 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001545 }
Tim Peters430f5d42001-03-01 01:30:56 +00001546 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001547
Andrew MacIntyred9400542002-02-26 11:41:34 +00001548/* OS/2 */
1549#elif defined(PYOS_OS2)
1550 HDIR hdir = 1;
1551 ULONG srchcnt = 1;
1552 FILEFINDBUF3 ffbuf;
1553 APIRET rc;
1554
1555 if (getenv("PYTHONCASEOK") != NULL)
1556 return 1;
1557
1558 rc = DosFindFirst(buf,
1559 &hdir,
1560 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1561 &ffbuf, sizeof(ffbuf),
1562 &srchcnt,
1563 FIL_STANDARD);
1564 if (rc != NO_ERROR)
1565 return 0;
1566 return strncmp(ffbuf.achName, name, namelen) == 0;
1567
Tim Peters50d8d372001-02-28 05:34:27 +00001568/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1569#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001570 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001571
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001572#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001573}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001574
Guido van Rossum0980bd91998-02-13 17:18:36 +00001575
Guido van Rossum197346f1997-10-31 18:38:52 +00001576#ifdef HAVE_STAT
1577/* Helper to look for __init__.py or __init__.py[co] in potential package */
1578static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001579find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001580{
Tim Peters0f9431f2001-07-05 03:47:53 +00001581 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001582 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001583 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001584 struct stat statbuf;
1585
Tim Peters0f9431f2001-07-05 03:47:53 +00001586/* For calling case_ok(buf, len, namelen, name):
1587 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1588 * ^ ^ ^ ^
1589 * |--------------------- buf ---------------------|
1590 * |------------------- len ------------------|
1591 * |------ name -------|
1592 * |----- namelen -----|
1593 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001594 if (save_len + 13 >= MAXPATHLEN)
1595 return 0;
1596 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001597 pname = buf + i;
1598 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001599 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001600 if (case_ok(buf,
1601 save_len + 9, /* len("/__init__") */
1602 8, /* len("__init__") */
1603 pname)) {
1604 buf[save_len] = '\0';
1605 return 1;
1606 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001607 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001608 i += strlen(pname);
1609 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001610 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001611 if (case_ok(buf,
1612 save_len + 9, /* len("/__init__") */
1613 8, /* len("__init__") */
1614 pname)) {
1615 buf[save_len] = '\0';
1616 return 1;
1617 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001618 }
1619 buf[save_len] = '\0';
1620 return 0;
1621}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001622
Guido van Rossum197346f1997-10-31 18:38:52 +00001623#endif /* HAVE_STAT */
1624
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001625
Tim Petersdbd9ba62000-07-09 03:09:57 +00001626static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001627
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001628/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001629 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001630
Guido van Rossum79f25d91997-04-29 20:08:16 +00001631static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001632load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001633{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001634 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001635 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001636 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001637
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001638 /* First check that there's an open file (if we need one) */
1639 switch (type) {
1640 case PY_SOURCE:
1641 case PY_COMPILED:
1642 if (fp == NULL) {
1643 PyErr_Format(PyExc_ValueError,
1644 "file object required for import (type code %d)",
1645 type);
1646 return NULL;
1647 }
1648 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001649
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001650 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001651
1652 case PY_SOURCE:
1653 m = load_source_module(name, buf, fp);
1654 break;
1655
1656 case PY_COMPILED:
1657 m = load_compiled_module(name, buf, fp);
1658 break;
1659
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001660#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001661 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001662 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001663 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001664#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001665
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001666 case PKG_DIRECTORY:
1667 m = load_package(name, buf);
1668 break;
1669
1670 case C_BUILTIN:
1671 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001672 if (buf != NULL && buf[0] != '\0')
1673 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001674 if (type == C_BUILTIN)
1675 err = init_builtin(name);
1676 else
1677 err = PyImport_ImportFrozenModule(name);
1678 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001679 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001680 if (err == 0) {
1681 PyErr_Format(PyExc_ImportError,
1682 "Purported %s module %.200s not found",
1683 type == C_BUILTIN ?
1684 "builtin" : "frozen",
1685 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001686 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001687 }
1688 modules = PyImport_GetModuleDict();
1689 m = PyDict_GetItemString(modules, name);
1690 if (m == NULL) {
1691 PyErr_Format(
1692 PyExc_ImportError,
1693 "%s module %.200s not properly initialized",
1694 type == C_BUILTIN ?
1695 "builtin" : "frozen",
1696 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001697 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001698 }
1699 Py_INCREF(m);
1700 break;
1701
Just van Rossum52e14d62002-12-30 22:08:05 +00001702 case IMP_HOOK: {
1703 if (loader == NULL) {
1704 PyErr_SetString(PyExc_ImportError,
1705 "import hook without loader");
1706 return NULL;
1707 }
1708 m = PyObject_CallMethod(loader, "load_module", "s", name);
1709 break;
1710 }
1711
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001712 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001713 PyErr_Format(PyExc_ImportError,
1714 "Don't know how to import %.200s (type code %d)",
1715 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001716 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001717
1718 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001719
1720 return m;
1721}
1722
1723
1724/* Initialize a built-in module.
Thomas Wouters89f507f2006-12-13 04:49:30 +00001725 Return 1 for success, 0 if the module is not found, and -1 with
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001726 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001727
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001728static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001729init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001730{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001731 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001732
Greg Ward201baee2001-10-04 14:52:06 +00001733 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001734 return 1;
1735
Guido van Rossum771c6c81997-10-31 18:37:24 +00001736 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001737 if (strcmp(name, p->name) == 0) {
1738 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001739 PyErr_Format(PyExc_ImportError,
1740 "Cannot re-init internal module %.200s",
1741 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001742 return -1;
1743 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001744 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001745 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001746 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001747 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001748 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001749 if (_PyImport_FixupExtension(name, name) == NULL)
1750 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001751 return 1;
1752 }
1753 }
1754 return 0;
1755}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001756
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001757
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001758/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001759
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001760static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001761find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001762{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001763 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001764
Guido van Rossum79f25d91997-04-29 20:08:16 +00001765 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001766 if (p->name == NULL)
1767 return NULL;
1768 if (strcmp(p->name, name) == 0)
1769 break;
1770 }
1771 return p;
1772}
1773
Guido van Rossum79f25d91997-04-29 20:08:16 +00001774static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001775get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001776{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001777 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001778 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001779
1780 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001781 PyErr_Format(PyExc_ImportError,
1782 "No such frozen object named %.200s",
1783 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001784 return NULL;
1785 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001786 if (p->code == NULL) {
1787 PyErr_Format(PyExc_ImportError,
1788 "Excluded frozen object named %.200s",
1789 name);
1790 return NULL;
1791 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001792 size = p->size;
1793 if (size < 0)
1794 size = -size;
1795 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001796}
1797
1798/* Initialize a frozen module.
1799 Return 1 for succes, 0 if the module is not found, and -1 with
1800 an exception set if the initialization failed.
1801 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001802
1803int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001804PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001805{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001806 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001807 PyObject *co;
1808 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001809 int ispackage;
1810 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001811
1812 if (p == NULL)
1813 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001814 if (p->code == NULL) {
1815 PyErr_Format(PyExc_ImportError,
1816 "Excluded frozen object named %.200s",
1817 name);
1818 return -1;
1819 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001820 size = p->size;
1821 ispackage = (size < 0);
1822 if (ispackage)
1823 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001824 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001825 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001826 name, ispackage ? " package" : "");
1827 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001828 if (co == NULL)
1829 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001830 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001831 PyErr_Format(PyExc_TypeError,
1832 "frozen object %.200s is not a code object",
1833 name);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001834 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001835 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001836 if (ispackage) {
1837 /* Set __path__ to the package name */
1838 PyObject *d, *s;
1839 int err;
1840 m = PyImport_AddModule(name);
1841 if (m == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001842 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001843 d = PyModule_GetDict(m);
Martin v. Löwis5b222132007-06-10 09:51:05 +00001844 s = PyUnicode_InternFromString(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001845 if (s == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001846 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001847 err = PyDict_SetItemString(d, "__path__", s);
1848 Py_DECREF(s);
1849 if (err != 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001850 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001851 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001852 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001853 if (m == NULL)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001854 goto err_return;
1855 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001856 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001857 return 1;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001858err_return:
1859 Py_DECREF(co);
1860 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001861}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001862
1863
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001864/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001865 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001866
Guido van Rossum79f25d91997-04-29 20:08:16 +00001867PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001868PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001869{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001870 PyObject *pname;
1871 PyObject *result;
1872
Martin v. Löwis5b222132007-06-10 09:51:05 +00001873 pname = PyUnicode_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001874 if (pname == NULL)
1875 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001876 result = PyImport_Import(pname);
1877 Py_DECREF(pname);
1878 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001879}
1880
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001881/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001882static PyObject *get_parent(PyObject *globals, char *buf,
1883 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001884static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001885 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001886static int mark_miss(char *name);
1887static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001888 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001889static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001890
1891/* The Magnum Opus of dotted-name import :-) */
1892
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001893static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001894import_module_level(char *name, PyObject *globals, PyObject *locals,
1895 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001896{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001897 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00001898 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001899 PyObject *parent, *head, *next, *tail;
1900
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001901 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001902 if (parent == NULL)
1903 return NULL;
1904
1905 head = load_next(parent, Py_None, &name, buf, &buflen);
1906 if (head == NULL)
1907 return NULL;
1908
1909 tail = head;
1910 Py_INCREF(tail);
1911 while (name) {
1912 next = load_next(tail, tail, &name, buf, &buflen);
1913 Py_DECREF(tail);
1914 if (next == NULL) {
1915 Py_DECREF(head);
1916 return NULL;
1917 }
1918 tail = next;
1919 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001920 if (tail == Py_None) {
1921 /* If tail is Py_None, both get_parent and load_next found
1922 an empty module name: someone called __import__("") or
1923 doctored faulty bytecode */
1924 Py_DECREF(tail);
1925 Py_DECREF(head);
1926 PyErr_SetString(PyExc_ValueError,
1927 "Empty module name");
1928 return NULL;
1929 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001930
1931 if (fromlist != NULL) {
1932 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1933 fromlist = NULL;
1934 }
1935
1936 if (fromlist == NULL) {
1937 Py_DECREF(tail);
1938 return head;
1939 }
1940
1941 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001942 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001943 Py_DECREF(tail);
1944 return NULL;
1945 }
1946
1947 return tail;
1948}
1949
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001950/* For DLL compatibility */
1951#undef PyImport_ImportModuleEx
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001952PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001953PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1954 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001955{
1956 PyObject *result;
1957 lock_import();
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001958 result = import_module_level(name, globals, locals, fromlist, -1);
1959 if (unlock_import() < 0) {
1960 Py_XDECREF(result);
1961 PyErr_SetString(PyExc_RuntimeError,
1962 "not holding the import lock");
1963 return NULL;
1964 }
1965 return result;
1966}
1967#define PyImport_ImportModuleEx(n, g, l, f) \
1968 PyImport_ImportModuleLevel(n, g, l, f, -1);
1969
1970PyObject *
1971PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
1972 PyObject *fromlist, int level)
1973{
1974 PyObject *result;
1975 lock_import();
1976 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00001977 if (unlock_import() < 0) {
1978 Py_XDECREF(result);
1979 PyErr_SetString(PyExc_RuntimeError,
1980 "not holding the import lock");
1981 return NULL;
1982 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001983 return result;
1984}
1985
Fred Drake87590902004-05-28 20:21:36 +00001986/* Return the package that an import is being performed in. If globals comes
1987 from the module foo.bar.bat (not itself a package), this returns the
1988 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001989 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00001990
1991 The *name* of the returned package is returned in buf, with the length of
1992 the name in *p_buflen.
1993
1994 If globals doesn't come from a package or a module in a package, or a
1995 corresponding entry is not found in sys.modules, Py_None is returned.
1996*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001997static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001998get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001999{
2000 static PyObject *namestr = NULL;
2001 static PyObject *pathstr = NULL;
2002 PyObject *modname, *modpath, *modules, *parent;
2003
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002004 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002005 return Py_None;
2006
2007 if (namestr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002008 namestr = PyUnicode_InternFromString("__name__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002009 if (namestr == NULL)
2010 return NULL;
2011 }
2012 if (pathstr == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002013 pathstr = PyUnicode_InternFromString("__path__");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002014 if (pathstr == NULL)
2015 return NULL;
2016 }
2017
2018 *buf = '\0';
2019 *p_buflen = 0;
2020 modname = PyDict_GetItem(globals, namestr);
Neal Norwitz80e7f272007-08-26 06:45:23 +00002021 if (modname == NULL || !PyUnicode_Check(modname))
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002022 return Py_None;
2023
2024 modpath = PyDict_GetItem(globals, pathstr);
2025 if (modpath != NULL) {
Neal Norwitz80e7f272007-08-26 06:45:23 +00002026 Py_ssize_t len = PyUnicode_GET_SIZE(modname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002027 if (len > MAXPATHLEN) {
2028 PyErr_SetString(PyExc_ValueError,
2029 "Module name too long");
2030 return NULL;
2031 }
Neal Norwitz80e7f272007-08-26 06:45:23 +00002032 strcpy(buf, PyUnicode_AsString(modname));
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002033 }
2034 else {
Neal Norwitz80e7f272007-08-26 06:45:23 +00002035 char *start = PyUnicode_AsString(modname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002036 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002037 size_t len;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002038 if (lastdot == NULL && level > 0) {
2039 PyErr_SetString(PyExc_ValueError,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002040 "Attempted relative import in non-package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002041 return NULL;
2042 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002043 if (lastdot == NULL)
2044 return Py_None;
2045 len = lastdot - start;
2046 if (len >= MAXPATHLEN) {
2047 PyErr_SetString(PyExc_ValueError,
2048 "Module name too long");
2049 return NULL;
2050 }
2051 strncpy(buf, start, len);
2052 buf[len] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002053 }
2054
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002055 while (--level > 0) {
2056 char *dot = strrchr(buf, '.');
2057 if (dot == NULL) {
2058 PyErr_SetString(PyExc_ValueError,
Thomas Wouters89f507f2006-12-13 04:49:30 +00002059 "Attempted relative import beyond "
2060 "toplevel package");
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002061 return NULL;
2062 }
2063 *dot = '\0';
2064 }
2065 *p_buflen = strlen(buf);
2066
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002067 modules = PyImport_GetModuleDict();
2068 parent = PyDict_GetItemString(modules, buf);
2069 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002070 PyErr_Format(PyExc_SystemError,
2071 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002072 return parent;
2073 /* We expect, but can't guarantee, if parent != None, that:
2074 - parent.__name__ == buf
2075 - parent.__dict__ is globals
2076 If this is violated... Who cares? */
2077}
2078
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002079/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002080static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002081load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002082 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002083{
2084 char *name = *p_name;
2085 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002086 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002087 char *p;
2088 PyObject *result;
2089
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002090 if (strlen(name) == 0) {
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002091 /* completely empty module name should only happen in
2092 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002093 Py_INCREF(mod);
2094 *p_name = NULL;
2095 return mod;
2096 }
2097
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002098 if (dot == NULL) {
2099 *p_name = NULL;
2100 len = strlen(name);
2101 }
2102 else {
2103 *p_name = dot+1;
2104 len = dot-name;
2105 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002106 if (len == 0) {
2107 PyErr_SetString(PyExc_ValueError,
2108 "Empty module name");
2109 return NULL;
2110 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002111
2112 p = buf + *p_buflen;
2113 if (p != buf)
2114 *p++ = '.';
2115 if (p+len-buf >= MAXPATHLEN) {
2116 PyErr_SetString(PyExc_ValueError,
2117 "Module name too long");
2118 return NULL;
2119 }
2120 strncpy(p, name, len);
2121 p[len] = '\0';
2122 *p_buflen = p+len-buf;
2123
2124 result = import_submodule(mod, p, buf);
2125 if (result == Py_None && altmod != mod) {
2126 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002127 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002128 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002129 if (result != NULL && result != Py_None) {
2130 if (mark_miss(buf) != 0) {
2131 Py_DECREF(result);
2132 return NULL;
2133 }
2134 strncpy(buf, name, len);
2135 buf[len] = '\0';
2136 *p_buflen = len;
2137 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002138 }
2139 if (result == NULL)
2140 return NULL;
2141
2142 if (result == Py_None) {
2143 Py_DECREF(result);
2144 PyErr_Format(PyExc_ImportError,
2145 "No module named %.200s", name);
2146 return NULL;
2147 }
2148
2149 return result;
2150}
2151
2152static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002153mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002154{
2155 PyObject *modules = PyImport_GetModuleDict();
2156 return PyDict_SetItemString(modules, name, Py_None);
2157}
2158
2159static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002160ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002161 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002162{
2163 int i;
2164
2165 if (!PyObject_HasAttrString(mod, "__path__"))
2166 return 1;
2167
2168 for (i = 0; ; i++) {
2169 PyObject *item = PySequence_GetItem(fromlist, i);
2170 int hasit;
2171 if (item == NULL) {
2172 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2173 PyErr_Clear();
2174 return 1;
2175 }
2176 return 0;
2177 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002178 if (!PyUnicode_Check(item)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002179 PyErr_SetString(PyExc_TypeError,
Neal Norwitz80e7f272007-08-26 06:45:23 +00002180 "Item in ``from list'' not a string");
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002181 Py_DECREF(item);
2182 return 0;
2183 }
Martin v. Löwis5b222132007-06-10 09:51:05 +00002184 if (PyUnicode_AS_UNICODE(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002185 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002186 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002187 /* See if the package defines __all__ */
2188 if (recursive)
2189 continue; /* Avoid endless recursion */
2190 all = PyObject_GetAttrString(mod, "__all__");
2191 if (all == NULL)
2192 PyErr_Clear();
2193 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002194 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002195 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002196 if (!ret)
2197 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002198 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002199 continue;
2200 }
2201 hasit = PyObject_HasAttr(mod, item);
2202 if (!hasit) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002203 PyObject *item8;
2204 char *subname;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002205 PyObject *submod;
2206 char *p;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002207 if (!Py_FileSystemDefaultEncoding) {
2208 item8 = PyUnicode_EncodeASCII(PyUnicode_AsUnicode(item),
2209 PyUnicode_GetSize(item),
Martin v. Löwis427dbff2007-06-12 05:53:00 +00002210 NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002211 } else {
Martin v. Löwis427dbff2007-06-12 05:53:00 +00002212 item8 = PyUnicode_AsEncodedString(item,
2213 Py_FileSystemDefaultEncoding, NULL);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002214 }
2215 if (!item8) {
2216 PyErr_SetString(PyExc_ValueError, "Cannot encode path item");
2217 return 0;
2218 }
2219 subname = PyBytes_AsString(item8);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002220 if (buflen + strlen(subname) >= MAXPATHLEN) {
2221 PyErr_SetString(PyExc_ValueError,
2222 "Module name too long");
2223 Py_DECREF(item);
2224 return 0;
2225 }
2226 p = buf + buflen;
2227 *p++ = '.';
2228 strcpy(p, subname);
2229 submod = import_submodule(mod, subname, buf);
Martin v. Löwis5b222132007-06-10 09:51:05 +00002230 Py_DECREF(item8);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002231 Py_XDECREF(submod);
2232 if (submod == NULL) {
2233 Py_DECREF(item);
2234 return 0;
2235 }
2236 }
2237 Py_DECREF(item);
2238 }
2239
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002240 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002241}
2242
Neil Schemenauer00b09662003-06-16 21:03:07 +00002243static int
2244add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2245 PyObject *modules)
2246{
2247 if (mod == Py_None)
2248 return 1;
2249 /* Irrespective of the success of this load, make a
2250 reference to it in the parent package module. A copy gets
2251 saved in the modules dictionary under the full name, so get a
2252 reference from there, if need be. (The exception is when the
2253 load failed with a SyntaxError -- then there's no trace in
2254 sys.modules. In that case, of course, do nothing extra.) */
2255 if (submod == NULL) {
2256 submod = PyDict_GetItemString(modules, fullname);
2257 if (submod == NULL)
2258 return 1;
2259 }
2260 if (PyModule_Check(mod)) {
2261 /* We can't use setattr here since it can give a
2262 * spurious warning if the submodule name shadows a
2263 * builtin name */
2264 PyObject *dict = PyModule_GetDict(mod);
2265 if (!dict)
2266 return 0;
2267 if (PyDict_SetItemString(dict, subname, submod) < 0)
2268 return 0;
2269 }
2270 else {
2271 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2272 return 0;
2273 }
2274 return 1;
2275}
2276
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002277static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002278import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002279{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002280 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002281 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002282
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002283 /* Require:
2284 if mod == None: subname == fullname
2285 else: mod.__name__ + "." + subname == fullname
2286 */
2287
Tim Peters50d8d372001-02-28 05:34:27 +00002288 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002289 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002290 }
2291 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002292 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002293 char buf[MAXPATHLEN+1];
2294 struct filedescr *fdp;
2295 FILE *fp = NULL;
2296
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002297 if (mod == Py_None)
2298 path = NULL;
2299 else {
2300 path = PyObject_GetAttrString(mod, "__path__");
2301 if (path == NULL) {
2302 PyErr_Clear();
2303 Py_INCREF(Py_None);
2304 return Py_None;
2305 }
2306 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002307
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002308 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002309 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2310 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002311 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002312 if (fdp == NULL) {
2313 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2314 return NULL;
2315 PyErr_Clear();
2316 Py_INCREF(Py_None);
2317 return Py_None;
2318 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002319 m = load_module(fullname, fp, buf, fdp->type, loader);
2320 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002321 if (fp)
2322 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002323 if (!add_submodule(mod, m, fullname, subname, modules)) {
2324 Py_XDECREF(m);
2325 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002326 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002327 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002328
2329 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002330}
2331
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002332
2333/* Re-import a module of any kind and return its module object, WITH
2334 INCREMENTED REFERENCE COUNT */
2335
Guido van Rossum79f25d91997-04-29 20:08:16 +00002336PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002337PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002338{
Guido van Rossumd8faa362007-04-27 19:54:29 +00002339 PyInterpreterState *interp = PyThreadState_Get()->interp;
2340 PyObject *modules_reloading = interp->modules_reloading;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002341 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossumd8faa362007-04-27 19:54:29 +00002342 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002343 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002344 char buf[MAXPATHLEN+1];
2345 struct filedescr *fdp;
2346 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002347 PyObject *newm;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002348
2349 if (modules_reloading == NULL) {
2350 Py_FatalError("PyImport_ReloadModule: "
Guido van Rossume7ba4952007-06-06 23:52:48 +00002351 "no modules_reloading dictionary!");
Guido van Rossumd8faa362007-04-27 19:54:29 +00002352 return NULL;
2353 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002354
Guido van Rossum79f25d91997-04-29 20:08:16 +00002355 if (m == NULL || !PyModule_Check(m)) {
2356 PyErr_SetString(PyExc_TypeError,
2357 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002358 return NULL;
2359 }
Neal Norwitz5616c6d2007-08-26 05:32:41 +00002360 name = (char*)PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002361 if (name == NULL)
2362 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002363 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002364 PyErr_Format(PyExc_ImportError,
2365 "reload(): module %.200s not in sys.modules",
2366 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002367 return NULL;
2368 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002369 existing_m = PyDict_GetItemString(modules_reloading, name);
2370 if (existing_m != NULL) {
2371 /* Due to a recursive reload, this module is already
2372 being reloaded. */
2373 Py_INCREF(existing_m);
2374 return existing_m;
2375 }
2376 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2377 return NULL;
2378
Guido van Rossum222ef561997-09-06 19:41:09 +00002379 subname = strrchr(name, '.');
2380 if (subname == NULL)
2381 subname = name;
2382 else {
2383 PyObject *parentname, *parent;
2384 parentname = PyString_FromStringAndSize(name, (subname-name));
Guido van Rossumd8faa362007-04-27 19:54:29 +00002385 if (parentname == NULL) {
2386 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002387 return NULL;
Guido van Rossumd8faa362007-04-27 19:54:29 +00002388 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002389 parent = PyDict_GetItem(modules, parentname);
2390 if (parent == NULL) {
2391 PyErr_Format(PyExc_ImportError,
2392 "reload(): parent %.200s not in sys.modules",
Georg Brandl0c55f292005-09-14 06:56:20 +00002393 PyString_AS_STRING(parentname));
2394 Py_DECREF(parentname);
Guido van Rossume7ba4952007-06-06 23:52:48 +00002395 imp_modules_reloading_clear();
Guido van Rossum222ef561997-09-06 19:41:09 +00002396 return NULL;
2397 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002398 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002399 subname++;
2400 path = PyObject_GetAttrString(parent, "__path__");
2401 if (path == NULL)
2402 PyErr_Clear();
2403 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002404 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002405 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002406 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002407
2408 if (fdp == NULL) {
2409 Py_XDECREF(loader);
Guido van Rossumd8faa362007-04-27 19:54:29 +00002410 imp_modules_reloading_clear();
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002411 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002412 }
2413
2414 newm = load_module(name, fp, buf, fdp->type, loader);
2415 Py_XDECREF(loader);
2416
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002417 if (fp)
2418 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002419 if (newm == NULL) {
2420 /* load_module probably removed name from modules because of
2421 * the error. Put back the original module object. We're
2422 * going to return NULL in this case regardless of whether
2423 * replacing name succeeds, so the return value is ignored.
2424 */
2425 PyDict_SetItemString(modules, name, m);
2426 }
Guido van Rossumd8faa362007-04-27 19:54:29 +00002427 imp_modules_reloading_clear();
Tim Peters1cd70172004-08-02 03:52:12 +00002428 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002429}
2430
2431
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002432/* Higher-level import emulator which emulates the "import" statement
2433 more accurately -- it invokes the __import__() function from the
2434 builtins of the current globals. This means that the import is
2435 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002436 environment, e.g. by "rexec".
2437 A dummy list ["__doc__"] is passed as the 4th argument so that
Neal Norwitz80e7f272007-08-26 06:45:23 +00002438 e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
Guido van Rossum6058eb41998-12-21 19:51:00 +00002439 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002440
2441PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002442PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002443{
2444 static PyObject *silly_list = NULL;
2445 static PyObject *builtins_str = NULL;
2446 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002447 PyObject *globals = NULL;
2448 PyObject *import = NULL;
2449 PyObject *builtins = NULL;
2450 PyObject *r = NULL;
2451
2452 /* Initialize constant string objects */
2453 if (silly_list == NULL) {
Martin v. Löwis5b222132007-06-10 09:51:05 +00002454 import_str = PyUnicode_InternFromString("__import__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002455 if (import_str == NULL)
2456 return NULL;
Martin v. Löwis5b222132007-06-10 09:51:05 +00002457 builtins_str = PyUnicode_InternFromString("__builtins__");
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002458 if (builtins_str == NULL)
2459 return NULL;
2460 silly_list = Py_BuildValue("[s]", "__doc__");
2461 if (silly_list == NULL)
2462 return NULL;
2463 }
2464
2465 /* Get the builtins from current globals */
2466 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002467 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002468 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002469 builtins = PyObject_GetItem(globals, builtins_str);
2470 if (builtins == NULL)
2471 goto err;
2472 }
2473 else {
2474 /* No globals -- use standard builtins, and fake globals */
2475 PyErr_Clear();
2476
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002477 builtins = PyImport_ImportModuleLevel("__builtin__",
2478 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002479 if (builtins == NULL)
2480 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002481 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2482 if (globals == NULL)
2483 goto err;
2484 }
2485
2486 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002487 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002488 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002489 if (import == NULL)
2490 PyErr_SetObject(PyExc_KeyError, import_str);
2491 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002492 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002493 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002494 if (import == NULL)
2495 goto err;
2496
Guido van Rossumd8faa362007-04-27 19:54:29 +00002497 /* Call the __import__ function with the proper argument list */
Thomas Wouters477c8d52006-05-27 19:21:47 +00002498 r = PyObject_CallFunctionObjArgs(import, module_name, globals,
2499 globals, silly_list, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002500
2501 err:
2502 Py_XDECREF(globals);
2503 Py_XDECREF(builtins);
2504 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002505
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002506 return r;
2507}
2508
2509
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002510/* Module 'imp' provides Python access to the primitives used for
2511 importing modules.
2512*/
2513
Guido van Rossum79f25d91997-04-29 20:08:16 +00002514static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002515imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002516{
2517 char buf[4];
2518
Guido van Rossum96774c12000-05-01 20:19:08 +00002519 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2520 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2521 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2522 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002523
Guido van Rossumad8d3002007-08-03 18:40:49 +00002524 return PyBytes_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002525}
2526
Guido van Rossum79f25d91997-04-29 20:08:16 +00002527static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002528imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002529{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002530 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002531 struct filedescr *fdp;
2532
Guido van Rossum79f25d91997-04-29 20:08:16 +00002533 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002534 if (list == NULL)
2535 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002536 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2537 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002538 fdp->suffix, fdp->mode, fdp->type);
2539 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002540 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002541 return NULL;
2542 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002543 if (PyList_Append(list, item) < 0) {
2544 Py_DECREF(list);
2545 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002546 return NULL;
2547 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002548 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002549 }
2550 return list;
2551}
2552
Guido van Rossum79f25d91997-04-29 20:08:16 +00002553static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002554call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002555{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002556 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002557 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002558 struct filedescr *fdp;
2559 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002560 FILE *fp = NULL;
2561
2562 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002563 if (path == Py_None)
2564 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002565 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002566 if (fdp == NULL)
2567 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002568 if (fp != NULL) {
2569 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2570 if (fob == NULL) {
2571 fclose(fp);
2572 return NULL;
2573 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002574 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002575 else {
2576 fob = Py_None;
2577 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002578 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002579 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002580 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002581 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002582 return ret;
2583}
2584
Guido van Rossum79f25d91997-04-29 20:08:16 +00002585static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002586imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002587{
2588 char *name;
2589 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002590 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002591 return NULL;
2592 return call_find_module(name, path);
2593}
2594
2595static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002596imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002597{
2598 char *name;
2599 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002600 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002601 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002602 return NULL;
2603 ret = init_builtin(name);
2604 if (ret < 0)
2605 return NULL;
2606 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002607 Py_INCREF(Py_None);
2608 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002609 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002610 m = PyImport_AddModule(name);
2611 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002612 return m;
2613}
2614
Guido van Rossum79f25d91997-04-29 20:08:16 +00002615static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002616imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002617{
2618 char *name;
2619 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002620 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002621 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002622 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002623 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002624 if (ret < 0)
2625 return NULL;
2626 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002627 Py_INCREF(Py_None);
2628 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002629 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002630 m = PyImport_AddModule(name);
2631 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002632 return m;
2633}
2634
Guido van Rossum79f25d91997-04-29 20:08:16 +00002635static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002636imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002637{
2638 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002639
Guido van Rossum43713e52000-02-29 13:59:29 +00002640 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002641 return NULL;
2642 return get_frozen_object(name);
2643}
2644
Guido van Rossum79f25d91997-04-29 20:08:16 +00002645static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002646imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002647{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002648 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002649 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002650 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002651 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002652}
2653
Guido van Rossum79f25d91997-04-29 20:08:16 +00002654static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002655imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002656{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002657 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002658 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002659 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002660 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002661 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002662 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002663}
2664
2665static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002666get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002667{
2668 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002669 if (mode[0] == 'U')
2670 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002671 if (fob == NULL) {
2672 fp = fopen(pathname, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002673 }
2674 else {
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002675 int fd = PyObject_AsFileDescriptor(fob);
2676 if (fd == -1)
2677 return NULL;
2678 /* XXX This will leak a FILE struct. Fix this!!!!
2679 (But it doesn't leak a file descrioptor!) */
2680 fp = fdopen(fd, mode);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002681 }
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002682 if (fp == NULL)
2683 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002684 return fp;
2685}
2686
Guido van Rossum79f25d91997-04-29 20:08:16 +00002687static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002688imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002689{
2690 char *name;
2691 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002692 PyObject *fob = NULL;
2693 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002694 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002695 if (!PyArg_ParseTuple(args, "ss|O:load_compiled",
2696 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002697 return NULL;
2698 fp = get_file(pathname, fob, "rb");
2699 if (fp == NULL)
2700 return NULL;
2701 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002702 if (fob == NULL)
2703 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002704 return m;
2705}
2706
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002707#ifdef HAVE_DYNAMIC_LOADING
2708
Guido van Rossum79f25d91997-04-29 20:08:16 +00002709static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002710imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002711{
2712 char *name;
2713 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002714 PyObject *fob = NULL;
2715 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002716 FILE *fp = NULL;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002717 if (!PyArg_ParseTuple(args, "ss|O:load_dynamic",
2718 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002719 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002720 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002721 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002722 if (fp == NULL)
2723 return NULL;
2724 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002725 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002726 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002727}
2728
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002729#endif /* HAVE_DYNAMIC_LOADING */
2730
Guido van Rossum79f25d91997-04-29 20:08:16 +00002731static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002732imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002733{
2734 char *name;
2735 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002736 PyObject *fob = NULL;
2737 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002738 FILE *fp;
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002739 if (!PyArg_ParseTuple(args, "ss|O:load_source",
2740 &name, &pathname, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002741 return NULL;
2742 fp = get_file(pathname, fob, "r");
2743 if (fp == NULL)
2744 return NULL;
2745 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002746 if (fob == NULL)
2747 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002748 return m;
2749}
2750
Guido van Rossum79f25d91997-04-29 20:08:16 +00002751static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002752imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002753{
2754 char *name;
2755 PyObject *fob;
2756 char *pathname;
2757 char *suffix; /* Unused */
2758 char *mode;
2759 int type;
2760 FILE *fp;
2761
Guido van Rossum43713e52000-02-29 13:59:29 +00002762 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002763 &name, &fob, &pathname,
2764 &suffix, &mode, &type))
2765 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002766 if (*mode) {
2767 /* Mode must start with 'r' or 'U' and must not contain '+'.
2768 Implicit in this test is the assumption that the mode
2769 may contain other modifiers like 'b' or 't'. */
2770
2771 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002772 PyErr_Format(PyExc_ValueError,
2773 "invalid file open mode %.200s", mode);
2774 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002775 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002776 }
2777 if (fob == Py_None)
2778 fp = NULL;
2779 else {
Guido van Rossumda5b8f22007-06-12 23:30:11 +00002780 fp = get_file(NULL, fob, mode);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002781 if (fp == NULL)
2782 return NULL;
2783 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002784 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002785}
2786
2787static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002788imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002789{
2790 char *name;
2791 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002792 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002793 return NULL;
2794 return load_package(name, pathname);
2795}
2796
2797static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002798imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002799{
2800 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002801 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002802 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002803 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002804}
2805
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002806/* Doc strings */
2807
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002808PyDoc_STRVAR(doc_imp,
2809"This module provides the components needed to build your own\n\
2810__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002811
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002812PyDoc_STRVAR(doc_find_module,
2813"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002814Search for a module. If path is omitted or None, search for a\n\
2815built-in, frozen or special module and continue search in sys.path.\n\
2816The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002817package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002818
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002819PyDoc_STRVAR(doc_load_module,
2820"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002821Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002822The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002823
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002824PyDoc_STRVAR(doc_get_magic,
2825"get_magic() -> string\n\
2826Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002827
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002828PyDoc_STRVAR(doc_get_suffixes,
2829"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002830Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002831that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002832
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002833PyDoc_STRVAR(doc_new_module,
2834"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002835Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002836The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002837
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002838PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002839"lock_held() -> boolean\n\
2840Return True if the import lock is currently held, else False.\n\
2841On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002842
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002843PyDoc_STRVAR(doc_acquire_lock,
2844"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002845Acquires the interpreter's import lock for the current thread.\n\
2846This lock should be used by import hooks to ensure thread-safety\n\
2847when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002848On platforms without threads, this function does nothing.");
2849
2850PyDoc_STRVAR(doc_release_lock,
2851"release_lock() -> None\n\
2852Release the interpreter's import lock.\n\
2853On platforms without threads, this function does nothing.");
2854
Guido van Rossum79f25d91997-04-29 20:08:16 +00002855static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002856 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2857 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2858 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2859 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2860 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2861 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2862 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2863 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002864 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00002865 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2866 {"init_builtin", imp_init_builtin, METH_VARARGS},
2867 {"init_frozen", imp_init_frozen, METH_VARARGS},
2868 {"is_builtin", imp_is_builtin, METH_VARARGS},
2869 {"is_frozen", imp_is_frozen, METH_VARARGS},
2870 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002871#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00002872 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002873#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002874 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00002875 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002876 {NULL, NULL} /* sentinel */
2877};
2878
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002879static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002880setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002881{
2882 PyObject *v;
2883 int err;
2884
2885 v = PyInt_FromLong((long)value);
2886 err = PyDict_SetItemString(d, name, v);
2887 Py_XDECREF(v);
2888 return err;
2889}
2890
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002891typedef struct {
2892 PyObject_HEAD
2893} NullImporter;
2894
2895static int
2896NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
2897{
2898 char *path;
2899
2900 if (!_PyArg_NoKeywords("NullImporter()", kwds))
2901 return -1;
2902
2903 if (!PyArg_ParseTuple(args, "s:NullImporter",
2904 &path))
2905 return -1;
2906
2907 if (strlen(path) == 0) {
2908 PyErr_SetString(PyExc_ImportError, "empty pathname");
2909 return -1;
2910 } else {
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002911 struct stat statbuf;
2912 int rv;
2913
2914 rv = stat(path, &statbuf);
2915 if (rv == 0) {
2916 /* it exists */
2917 if (S_ISDIR(statbuf.st_mode)) {
2918 /* it's a directory */
2919 PyErr_SetString(PyExc_ImportError,
2920 "existing directory");
2921 return -1;
2922 }
2923 }
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002924 }
2925 return 0;
2926}
2927
2928static PyObject *
2929NullImporter_find_module(NullImporter *self, PyObject *args)
2930{
2931 Py_RETURN_NONE;
2932}
2933
2934static PyMethodDef NullImporter_methods[] = {
2935 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
2936 "Always return None"
2937 },
2938 {NULL} /* Sentinel */
2939};
2940
2941
2942static PyTypeObject NullImporterType = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00002943 PyVarObject_HEAD_INIT(NULL, 0)
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002944 "imp.NullImporter", /*tp_name*/
2945 sizeof(NullImporter), /*tp_basicsize*/
2946 0, /*tp_itemsize*/
2947 0, /*tp_dealloc*/
2948 0, /*tp_print*/
2949 0, /*tp_getattr*/
2950 0, /*tp_setattr*/
2951 0, /*tp_compare*/
2952 0, /*tp_repr*/
2953 0, /*tp_as_number*/
2954 0, /*tp_as_sequence*/
2955 0, /*tp_as_mapping*/
2956 0, /*tp_hash */
2957 0, /*tp_call*/
2958 0, /*tp_str*/
2959 0, /*tp_getattro*/
2960 0, /*tp_setattro*/
2961 0, /*tp_as_buffer*/
2962 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2963 "Null importer object", /* tp_doc */
2964 0, /* tp_traverse */
2965 0, /* tp_clear */
2966 0, /* tp_richcompare */
2967 0, /* tp_weaklistoffset */
2968 0, /* tp_iter */
2969 0, /* tp_iternext */
2970 NullImporter_methods, /* tp_methods */
2971 0, /* tp_members */
2972 0, /* tp_getset */
2973 0, /* tp_base */
2974 0, /* tp_dict */
2975 0, /* tp_descr_get */
2976 0, /* tp_descr_set */
2977 0, /* tp_dictoffset */
2978 (initproc)NullImporter_init, /* tp_init */
2979 0, /* tp_alloc */
2980 PyType_GenericNew /* tp_new */
2981};
2982
2983
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002984PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002985initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002986{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002987 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002988
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002989 if (PyType_Ready(&NullImporterType) < 0)
2990 goto failure;
2991
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002992 m = Py_InitModule4("imp", imp_methods, doc_imp,
2993 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00002994 if (m == NULL)
2995 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002996 d = PyModule_GetDict(m);
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00002997 if (d == NULL)
2998 goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002999
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003000 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3001 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3002 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3003 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3004 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3005 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3006 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3007 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00003008 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00003009 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003010
Thomas Wouters0e3f5912006-08-11 14:57:12 +00003011 Py_INCREF(&NullImporterType);
3012 PyModule_AddObject(m, "NullImporter", (PyObject *)&NullImporterType);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00003013 failure:
3014 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00003015}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003016
3017
Guido van Rossumb18618d2000-05-03 23:44:39 +00003018/* API for embedding applications that want to add their own entries
3019 to the table of built-in modules. This should normally be called
3020 *before* Py_Initialize(). When the table resize fails, -1 is
3021 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003022
3023 After a similar function by Just van Rossum. */
3024
3025int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003026PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003027{
3028 static struct _inittab *our_copy = NULL;
3029 struct _inittab *p;
3030 int i, n;
3031
3032 /* Count the number of entries in both tables */
3033 for (n = 0; newtab[n].name != NULL; n++)
3034 ;
3035 if (n == 0)
3036 return 0; /* Nothing to do */
3037 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3038 ;
3039
3040 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00003041 p = our_copy;
3042 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003043 if (p == NULL)
3044 return -1;
3045
3046 /* Copy the tables into the new memory */
3047 if (our_copy != PyImport_Inittab)
3048 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3049 PyImport_Inittab = our_copy = p;
3050 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3051
3052 return 0;
3053}
3054
3055/* Shorthand to add a single entry given a name and a function */
3056
3057int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003058PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003059{
3060 struct _inittab newtab[2];
3061
3062 memset(newtab, '\0', sizeof newtab);
3063
3064 newtab[0].name = name;
3065 newtab[0].initfunc = initfunc;
3066
3067 return PyImport_ExtendInittab(newtab);
3068}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00003069
3070#ifdef __cplusplus
3071}
3072#endif