blob: 7f79aee3a9de900dca712e95f6585802a83bb5c0 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* Module definition and import implementation */
3
Guido van Rossum79f25d91997-04-29 20:08:16 +00004#include "Python.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00006#include "Python-ast.h"
Neal Norwitzadb69fc2005-12-17 20:54:49 +00007#include "pyarena.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00008#include "pythonrun.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000010#include "marshal.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000011#include "code.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000012#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000013#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000014#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000015#include "importdl.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +000016
Guido van Rossum55a83382000-09-20 20:31:38 +000017#ifdef HAVE_FCNTL_H
18#include <fcntl.h>
19#endif
Anthony Baxterac6bd462006-04-13 02:06:09 +000020#ifdef __cplusplus
21extern "C" {
22#endif
Guido van Rossum55a83382000-09-20 20:31:38 +000023
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000024extern time_t PyOS_GetLastModificationTime(char *, FILE *);
25 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000026
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000027/* Magic word to reject .pyc files generated by other Python versions.
28 It should change for each incompatible change to the bytecode.
29
30 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000031 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000032 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000033
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000034 The magic numbers must be spaced apart atleast 2 values, as the
35 -U interpeter flag will cause MAGIC+1 being used. They have been
36 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000037
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000038 There were a variety of old schemes for setting the magic number.
39 The current working scheme is to increment the previous value by
40 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000041
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000042 Known values:
43 Python 1.5: 20121
44 Python 1.5.1: 20121
45 Python 1.5.2: 20121
Skip Montanaro4ec3c262006-03-25 14:12:03 +000046 Python 1.6: 50428
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000047 Python 2.0: 50823
48 Python 2.0.1: 50823
49 Python 2.1: 60202
50 Python 2.1.1: 60202
51 Python 2.1.2: 60202
52 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000053 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000054 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000055 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000056 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000057 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000058 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000059 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000060 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000061 Python 2.5a0: 62091 (with)
Guido van Rossumf6694362006-03-10 02:28:35 +000062 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
Neal Norwitzedef2be2006-07-12 05:26:17 +000063 Python 2.5c1: 62101 (fix wrong code: for x, in ...)
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000064.
Tim Peters36515e22001-11-18 04:06:29 +000065*/
Neal Norwitza1f10902006-07-12 07:28:29 +000066#define MAGIC (62101 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000067
Guido van Rossum96774c12000-05-01 20:19:08 +000068/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000069 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000070 compiler works which are enabled by command line switches. */
71static long pyc_magic = MAGIC;
72
Guido van Rossum25ce5661997-08-02 03:10:38 +000073/* See _PyImport_FixupExtension() below */
74static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000075
Guido van Rossum771c6c81997-10-31 18:37:24 +000076/* This table is defined in config.c: */
77extern struct _inittab _PyImport_Inittab[];
78
79struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000080
Guido van Rossumed1170e1999-12-20 21:23:41 +000081/* these tables define the module suffixes that Python recognizes */
82struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +000083
84#ifdef RISCOS
85static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000086 {"/py", "U", PY_SOURCE},
Guido van Rossum48a680c2001-03-02 06:34:14 +000087 {"/pyc", "rb", PY_COMPILED},
88 {0, 0}
89};
90#else
Guido van Rossumed1170e1999-12-20 21:23:41 +000091static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000092 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000093#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +000094 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +000095#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +000096 {".pyc", "rb", PY_COMPILED},
97 {0, 0}
98};
Guido van Rossum48a680c2001-03-02 06:34:14 +000099#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +0000100
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000101/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000102
103void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000104_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000105{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000106 const struct filedescr *scan;
107 struct filedescr *filetab;
108 int countD = 0;
109 int countS = 0;
110
111 /* prepare _PyImport_Filetab: copy entries from
112 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
113 */
114 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
115 ++countD;
116 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
117 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000118 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Neal Norwitze1fdb322006-07-21 05:32:28 +0000119 if (filetab == NULL)
Neal Norwitz33722ae2006-07-21 07:59:02 +0000120 Py_FatalError("Can't initialize import file table.");
Guido van Rossumed1170e1999-12-20 21:23:41 +0000121 memcpy(filetab, _PyImport_DynLoadFiletab,
122 countD * sizeof(struct filedescr));
123 memcpy(filetab + countD, _PyImport_StandardFiletab,
124 countS * sizeof(struct filedescr));
125 filetab[countD + countS].suffix = NULL;
126
127 _PyImport_Filetab = filetab;
128
Guido van Rossum0824f631997-03-11 18:37:35 +0000129 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000130 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
131 for (; filetab->suffix != NULL; filetab++) {
Guido van Rossum48a680c2001-03-02 06:34:14 +0000132#ifndef RISCOS
Guido van Rossumed1170e1999-12-20 21:23:41 +0000133 if (strcmp(filetab->suffix, ".pyc") == 0)
134 filetab->suffix = ".pyo";
Guido van Rossum48a680c2001-03-02 06:34:14 +0000135#else
136 if (strcmp(filetab->suffix, "/pyc") == 0)
137 filetab->suffix = "/pyo";
138#endif
Guido van Rossum0824f631997-03-11 18:37:35 +0000139 }
140 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000141
142 if (Py_UnicodeFlag) {
143 /* Fix the pyc_magic so that byte compiled code created
144 using the all-Unicode method doesn't interfere with
145 code created in normal operation mode. */
146 pyc_magic = MAGIC + 1;
147 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000148}
149
Guido van Rossum25ce5661997-08-02 03:10:38 +0000150void
Just van Rossum52e14d62002-12-30 22:08:05 +0000151_PyImportHooks_Init(void)
152{
153 PyObject *v, *path_hooks = NULL, *zimpimport;
154 int err = 0;
155
156 /* adding sys.path_hooks and sys.path_importer_cache, setting up
157 zipimport */
158
159 if (Py_VerboseFlag)
160 PySys_WriteStderr("# installing zipimport hook\n");
161
162 v = PyList_New(0);
163 if (v == NULL)
164 goto error;
165 err = PySys_SetObject("meta_path", v);
166 Py_DECREF(v);
167 if (err)
168 goto error;
169 v = PyDict_New();
170 if (v == NULL)
171 goto error;
172 err = PySys_SetObject("path_importer_cache", v);
173 Py_DECREF(v);
174 if (err)
175 goto error;
176 path_hooks = PyList_New(0);
177 if (path_hooks == NULL)
178 goto error;
179 err = PySys_SetObject("path_hooks", path_hooks);
180 if (err) {
181 error:
182 PyErr_Print();
183 Py_FatalError("initializing sys.meta_path, sys.path_hooks or "
184 "path_importer_cache failed");
185 }
186 zimpimport = PyImport_ImportModule("zipimport");
187 if (zimpimport == NULL) {
188 PyErr_Clear(); /* No zip import module -- okay */
189 if (Py_VerboseFlag)
190 PySys_WriteStderr("# can't import zipimport\n");
191 }
192 else {
193 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
194 "zipimporter");
195 Py_DECREF(zimpimport);
196 if (zipimporter == NULL) {
197 PyErr_Clear(); /* No zipimporter object -- okay */
198 if (Py_VerboseFlag)
199 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000200 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000201 }
202 else {
203 /* sys.path_hooks.append(zipimporter) */
204 err = PyList_Append(path_hooks, zipimporter);
205 Py_DECREF(zipimporter);
206 if (err)
207 goto error;
208 if (Py_VerboseFlag)
209 PySys_WriteStderr(
210 "# installed zipimport hook\n");
211 }
212 }
213 Py_DECREF(path_hooks);
214}
215
216void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000217_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000218{
219 Py_XDECREF(extensions);
220 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000221 PyMem_DEL(_PyImport_Filetab);
222 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000223}
224
225
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000226/* Locking primitives to prevent parallel imports of the same module
227 in different threads to return with a partially loaded module.
228 These calls are serialized by the global interpreter lock. */
229
230#ifdef WITH_THREAD
231
Guido van Rossum49b56061998-10-01 20:42:43 +0000232#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000233
Guido van Rossum65d5b571998-12-21 19:32:43 +0000234static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000235static long import_lock_thread = -1;
236static int import_lock_level = 0;
237
238static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000239lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000240{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000241 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000242 if (me == -1)
243 return; /* Too bad */
Neal Norwitze1fdb322006-07-21 05:32:28 +0000244 if (import_lock == NULL) {
Guido van Rossum65d5b571998-12-21 19:32:43 +0000245 import_lock = PyThread_allocate_lock();
Neal Norwitze1fdb322006-07-21 05:32:28 +0000246 if (import_lock == NULL)
247 return; /* Nothing much we can do. */
248 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000249 if (import_lock_thread == me) {
250 import_lock_level++;
251 return;
252 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000253 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
254 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000255 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000256 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000257 PyEval_RestoreThread(tstate);
258 }
259 import_lock_thread = me;
260 import_lock_level = 1;
261}
262
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000263static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000264unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000265{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000266 long me = PyThread_get_thread_ident();
Neal Norwitze1fdb322006-07-21 05:32:28 +0000267 if (me == -1 || import_lock == NULL)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000268 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000269 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000270 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000271 import_lock_level--;
272 if (import_lock_level == 0) {
273 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000274 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000275 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000276 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000277}
278
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000279/* This function is called from PyOS_AfterFork to ensure that newly
280 created child processes do not share locks with the parent. */
281
282void
283_PyImport_ReInitLock(void)
284{
285#ifdef _AIX
286 if (import_lock != NULL)
287 import_lock = PyThread_allocate_lock();
288#endif
289}
290
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000291#else
292
293#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000294#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000295
296#endif
297
Tim Peters69232342001-08-30 05:16:13 +0000298static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000299imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000300{
Tim Peters69232342001-08-30 05:16:13 +0000301#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000302 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000303#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000304 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000305#endif
306}
307
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000308static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000309imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000310{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000311#ifdef WITH_THREAD
312 lock_import();
313#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000314 Py_INCREF(Py_None);
315 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000316}
317
318static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000319imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000320{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000321#ifdef WITH_THREAD
322 if (unlock_import() < 0) {
323 PyErr_SetString(PyExc_RuntimeError,
324 "not holding the import lock");
325 return NULL;
326 }
327#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000328 Py_INCREF(Py_None);
329 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000330}
331
Guido van Rossum25ce5661997-08-02 03:10:38 +0000332/* Helper for sys */
333
334PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000335PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000336{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000337 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000338 if (interp->modules == NULL)
339 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
340 return interp->modules;
341}
342
Guido van Rossum3f5da241990-12-20 15:06:42 +0000343
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000344/* List of names to clear in sys */
345static char* sys_deletes[] = {
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000346 "path", "argv", "ps1", "ps2", "exitfunc",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000347 "exc_type", "exc_value", "exc_traceback",
348 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000349 "path_hooks", "path_importer_cache", "meta_path",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000350 NULL
351};
352
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000353static char* sys_files[] = {
354 "stdin", "__stdin__",
355 "stdout", "__stdout__",
356 "stderr", "__stderr__",
357 NULL
358};
359
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000360
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000361/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000362
Guido van Rossum3f5da241990-12-20 15:06:42 +0000363void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000364PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000365{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000366 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000367 char *name;
368 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000369 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000370 PyObject *modules = interp->modules;
371
372 if (modules == NULL)
373 return; /* Already done */
374
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000375 /* Delete some special variables first. These are common
376 places where user values hide and people complain when their
377 destructors fail. Since the modules containing them are
378 deleted *last* of all, they would come too late in the normal
379 destruction order. Sigh. */
380
381 value = PyDict_GetItemString(modules, "__builtin__");
382 if (value != NULL && PyModule_Check(value)) {
383 dict = PyModule_GetDict(value);
384 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000385 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000386 PyDict_SetItemString(dict, "_", Py_None);
387 }
388 value = PyDict_GetItemString(modules, "sys");
389 if (value != NULL && PyModule_Check(value)) {
390 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000391 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000392 dict = PyModule_GetDict(value);
393 for (p = sys_deletes; *p != NULL; p++) {
394 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000395 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000396 PyDict_SetItemString(dict, *p, Py_None);
397 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000398 for (p = sys_files; *p != NULL; p+=2) {
399 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000400 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000401 v = PyDict_GetItemString(dict, *(p+1));
402 if (v == NULL)
403 v = Py_None;
404 PyDict_SetItemString(dict, *p, v);
405 }
406 }
407
408 /* First, delete __main__ */
409 value = PyDict_GetItemString(modules, "__main__");
410 if (value != NULL && PyModule_Check(value)) {
411 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000412 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000413 _PyModule_Clear(value);
414 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000415 }
416
Guido van Rossum758eec01998-01-19 21:58:26 +0000417 /* The special treatment of __builtin__ here is because even
418 when it's not referenced as a module, its dictionary is
419 referenced by almost every module's __builtins__. Since
420 deleting a module clears its dictionary (even if there are
421 references left to it), we need to delete the __builtin__
422 module last. Likewise, we don't delete sys until the very
423 end because it is implicitly referenced (e.g. by print).
424
425 Also note that we 'delete' modules by replacing their entry
426 in the modules dict with None, rather than really deleting
427 them; this avoids a rehash of the modules dictionary and
428 also marks them as "non existent" so they won't be
429 re-imported. */
430
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000431 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000432 one (skipping __builtin__ and sys) and delete them */
433 do {
434 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000435 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000436 while (PyDict_Next(modules, &pos, &key, &value)) {
437 if (value->ob_refcnt != 1)
438 continue;
Guido van Rossum566373e1998-10-01 15:24:50 +0000439 if (PyString_Check(key) && PyModule_Check(value)) {
440 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000441 if (strcmp(name, "__builtin__") == 0)
442 continue;
443 if (strcmp(name, "sys") == 0)
444 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000445 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000446 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000447 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000448 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000449 PyDict_SetItem(modules, key, Py_None);
450 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000451 }
452 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000453 } while (ndone > 0);
454
Guido van Rossum758eec01998-01-19 21:58:26 +0000455 /* Next, delete all modules (still skipping __builtin__ and sys) */
456 pos = 0;
457 while (PyDict_Next(modules, &pos, &key, &value)) {
Guido van Rossum566373e1998-10-01 15:24:50 +0000458 if (PyString_Check(key) && PyModule_Check(value)) {
459 name = PyString_AS_STRING(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("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000466 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000467 PyDict_SetItem(modules, key, Py_None);
468 }
469 }
470
471 /* Next, delete sys and __builtin__ (in that order) */
472 value = PyDict_GetItemString(modules, "sys");
473 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000474 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000475 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000476 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000477 PyDict_SetItemString(modules, "sys", Py_None);
478 }
479 value = PyDict_GetItemString(modules, "__builtin__");
480 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000481 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000482 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000483 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000484 PyDict_SetItemString(modules, "__builtin__", Py_None);
485 }
486
487 /* Finally, clear and delete the modules directory */
488 PyDict_Clear(modules);
489 interp->modules = NULL;
490 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000491}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000492
493
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000494/* Helper for pythonrun.c -- return magic number */
495
496long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000497PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000498{
Guido van Rossum96774c12000-05-01 20:19:08 +0000499 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000500}
501
502
Guido van Rossum25ce5661997-08-02 03:10:38 +0000503/* Magic for extension modules (built-in as well as dynamically
504 loaded). To prevent initializing an extension module more than
505 once, we keep a static dictionary 'extensions' keyed by module name
506 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000507 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000508 dictionary is stored by calling _PyImport_FixupExtension()
509 immediately after the module initialization function succeeds. A
510 copy can be retrieved from there by calling
511 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000512
Guido van Rossum79f25d91997-04-29 20:08:16 +0000513PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000514_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000515{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000516 PyObject *modules, *mod, *dict, *copy;
517 if (extensions == NULL) {
518 extensions = PyDict_New();
519 if (extensions == NULL)
520 return NULL;
521 }
522 modules = PyImport_GetModuleDict();
523 mod = PyDict_GetItemString(modules, name);
524 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000525 PyErr_Format(PyExc_SystemError,
526 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000527 return NULL;
528 }
529 dict = PyModule_GetDict(mod);
530 if (dict == NULL)
531 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000532 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000533 if (copy == NULL)
534 return NULL;
535 PyDict_SetItemString(extensions, filename, copy);
536 Py_DECREF(copy);
537 return copy;
538}
539
540PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000541_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000542{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000543 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000544 if (extensions == NULL)
545 return NULL;
546 dict = PyDict_GetItemString(extensions, filename);
547 if (dict == NULL)
548 return NULL;
549 mod = PyImport_AddModule(name);
550 if (mod == NULL)
551 return NULL;
552 mdict = PyModule_GetDict(mod);
553 if (mdict == NULL)
554 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000555 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000556 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000557 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000558 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000559 name, filename);
560 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000561}
562
563
564/* Get the module object corresponding to a module name.
565 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000566 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000567 Because the former action is most common, THIS DOES NOT RETURN A
568 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000569
Guido van Rossum79f25d91997-04-29 20:08:16 +0000570PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000571PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000572{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000573 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000574 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000575
Guido van Rossum25ce5661997-08-02 03:10:38 +0000576 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000577 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000578 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000579 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000580 if (m == NULL)
581 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000582 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000583 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000584 return NULL;
585 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000586 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000587
588 return m;
589}
590
Tim Peters1cd70172004-08-02 03:52:12 +0000591/* Remove name from sys.modules, if it's there. */
592static void
593_RemoveModule(const char *name)
594{
595 PyObject *modules = PyImport_GetModuleDict();
596 if (PyDict_GetItemString(modules, name) == NULL)
597 return;
598 if (PyDict_DelItemString(modules, name) < 0)
599 Py_FatalError("import: deleting existing key in"
600 "sys.modules failed");
601}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000602
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000603/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000604 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
605 * removed from sys.modules, to avoid leaving damaged module objects
606 * in sys.modules. The caller may wish to restore the original
607 * module object (if any) in this case; PyImport_ReloadModule is an
608 * example.
609 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000610PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000611PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000612{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000613 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
614}
615
616PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000617PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000618{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000619 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000620 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000621
Guido van Rossum79f25d91997-04-29 20:08:16 +0000622 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000623 if (m == NULL)
624 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000625 /* If the module is being reloaded, we get the old module back
626 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000627 d = PyModule_GetDict(m);
628 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
629 if (PyDict_SetItemString(d, "__builtins__",
630 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000631 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000632 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000633 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000634 v = NULL;
635 if (pathname != NULL) {
636 v = PyString_FromString(pathname);
637 if (v == NULL)
638 PyErr_Clear();
639 }
640 if (v == NULL) {
641 v = ((PyCodeObject *)co)->co_filename;
642 Py_INCREF(v);
643 }
644 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000645 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000646 Py_DECREF(v);
647
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000648 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000649 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000650 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000651 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000652
Guido van Rossum25ce5661997-08-02 03:10:38 +0000653 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000654 PyErr_Format(PyExc_ImportError,
655 "Loaded module %.200s not found in sys.modules",
656 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000657 return NULL;
658 }
659
Guido van Rossum79f25d91997-04-29 20:08:16 +0000660 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000661
662 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000663
664 error:
665 _RemoveModule(name);
666 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000667}
668
669
670/* Given a pathname for a Python source file, fill a buffer with the
671 pathname for the corresponding compiled file. Return the pathname
672 for the compiled file, or NULL if there's no space in the buffer.
673 Doesn't set an exception. */
674
675static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000676make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000677{
Tim Petersc1731372001-08-04 08:12:36 +0000678 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000679 if (len+2 > buflen)
680 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000681
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000682#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000683 /* Treat .pyw as if it were .py. The case of ".pyw" must match
684 that used in _PyImport_StandardFiletab. */
685 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
686 --len; /* pretend 'w' isn't there */
687#endif
688 memcpy(buf, pathname, len);
689 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
690 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000691
692 return buf;
693}
694
695
696/* Given a pathname for a Python source file, its time of last
697 modification, and a pathname for a compiled file, check whether the
698 compiled file represents the same version of the source. If so,
699 return a FILE pointer for the compiled file, positioned just after
700 the header; if not, return NULL.
701 Doesn't set an exception. */
702
703static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000704check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000705{
706 FILE *fp;
707 long magic;
708 long pyc_mtime;
709
710 fp = fopen(cpathname, "rb");
711 if (fp == NULL)
712 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000713 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000714 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000715 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000716 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000717 fclose(fp);
718 return NULL;
719 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000720 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000721 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000722 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000723 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000724 fclose(fp);
725 return NULL;
726 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000727 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000728 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000729 return fp;
730}
731
732
733/* Read a code object from a file and check it for validity */
734
Guido van Rossum79f25d91997-04-29 20:08:16 +0000735static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000736read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000737{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000738 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000739
Tim Petersd9b9ac82001-01-28 00:27:39 +0000740 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000741 if (co == NULL)
742 return NULL;
743 if (!PyCode_Check(co)) {
744 PyErr_Format(PyExc_ImportError,
745 "Non-code object in %.200s", cpathname);
746 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000747 return NULL;
748 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000749 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000750}
751
752
753/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000754 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000755
Guido van Rossum79f25d91997-04-29 20:08:16 +0000756static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000757load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000758{
759 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000760 PyCodeObject *co;
761 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000762
Guido van Rossum79f25d91997-04-29 20:08:16 +0000763 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000764 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000765 PyErr_Format(PyExc_ImportError,
766 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000767 return NULL;
768 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000769 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000770 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000771 if (co == NULL)
772 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000773 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000774 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000775 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000776 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000777 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000778
779 return m;
780}
781
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000782/* Parse a source file and return the corresponding code object */
783
Guido van Rossum79f25d91997-04-29 20:08:16 +0000784static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000785parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000786{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000787 PyCodeObject *co = NULL;
788 mod_ty mod;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000789 PyArena *arena = PyArena_New();
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000790
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000791 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, 0,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000792 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000793 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000794 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000796 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000797 return co;
798}
799
800
Guido van Rossum55a83382000-09-20 20:31:38 +0000801/* Helper to open a bytecode file for writing in exclusive mode */
802
803static FILE *
804open_exclusive(char *filename)
805{
806#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
807 /* Use O_EXCL to avoid a race condition when another process tries to
808 write the same file. When that happens, our open() call fails,
809 which is just fine (since it's only a cache).
810 XXX If the file exists and is writable but the directory is not
811 writable, the file will never be written. Oh well.
812 */
813 int fd;
814 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000815 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
816#ifdef O_BINARY
817 |O_BINARY /* necessary for Windows */
818#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000819#ifdef __VMS
Martin v. Löwis18e16552006-02-15 17:27:45 +0000820 , 0666, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000821#else
Martin v. Löwis18e16552006-02-15 17:27:45 +0000822 , 0666
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000823#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000824 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000825 if (fd < 0)
826 return NULL;
827 return fdopen(fd, "wb");
828#else
829 /* Best we can do -- on Windows this can't happen anyway */
830 return fopen(filename, "wb");
831#endif
832}
833
834
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000835/* Write a compiled module to a file, placing the time of last
836 modification of its source into the header.
837 Errors are ignored, if a write error occurs an attempt is made to
838 remove the file. */
839
840static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000841write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000842{
843 FILE *fp;
844
Guido van Rossum55a83382000-09-20 20:31:38 +0000845 fp = open_exclusive(cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000846 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000847 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000848 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000849 "# can't create %s\n", cpathname);
850 return;
851 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000852 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000853 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000854 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
855 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000856 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000857 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000858 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000859 /* Don't keep partial file */
860 fclose(fp);
861 (void) unlink(cpathname);
862 return;
863 }
864 /* Now write the true mtime */
865 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000866 assert(mtime < LONG_MAX);
Martin v. Löwis725507b2006-03-07 12:08:51 +0000867 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000868 fflush(fp);
869 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000870 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000871 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000872}
873
874
875/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000876 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
877 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000878
Guido van Rossum79f25d91997-04-29 20:08:16 +0000879static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000880load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000881{
Fred Drake4c82b232000-06-30 16:18:57 +0000882 time_t mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000883 FILE *fpc;
884 char buf[MAXPATHLEN+1];
885 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000886 PyCodeObject *co;
887 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000888
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000889 mtime = PyOS_GetLastModificationTime(pathname, fp);
Neal Norwitz708e51a2005-10-03 04:48:15 +0000890 if (mtime == (time_t)(-1)) {
891 PyErr_Format(PyExc_RuntimeError,
892 "unable to get modification time from '%s'",
893 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000894 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000895 }
Fred Drake4c82b232000-06-30 16:18:57 +0000896#if SIZEOF_TIME_T > 4
897 /* Python's .pyc timestamp handling presumes that the timestamp fits
898 in 4 bytes. This will be fine until sometime in the year 2038,
899 when a 4-byte signed time_t will overflow.
900 */
901 if (mtime >> 32) {
902 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000903 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000904 return NULL;
905 }
906#endif
Tim Peters36515e22001-11-18 04:06:29 +0000907 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000908 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000909 if (cpathname != NULL &&
910 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000911 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000912 fclose(fpc);
913 if (co == NULL)
914 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000915 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000916 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000917 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000918 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000919 }
920 else {
921 co = parse_source_module(pathname, fp);
922 if (co == NULL)
923 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000924 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000925 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000926 name, pathname);
927 write_compiled_module(co, cpathname, mtime);
928 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000929 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000930 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000931
932 return m;
933}
934
935
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000936/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +0000937static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
938static struct filedescr *find_module(char *, char *, PyObject *,
939 char *, size_t, FILE **, PyObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000940static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000941
942/* Load a package and return its module object WITH INCREMENTED
943 REFERENCE COUNT */
944
945static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000946load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000947{
Tim Peters1cd70172004-08-02 03:52:12 +0000948 PyObject *m, *d;
949 PyObject *file = NULL;
950 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000951 int err;
952 char buf[MAXPATHLEN+1];
953 FILE *fp = NULL;
954 struct filedescr *fdp;
955
956 m = PyImport_AddModule(name);
957 if (m == NULL)
958 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000959 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000960 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000961 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000962 d = PyModule_GetDict(m);
963 file = PyString_FromString(pathname);
964 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000965 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000966 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +0000967 if (path == NULL)
968 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000969 err = PyDict_SetItemString(d, "__file__", file);
970 if (err == 0)
971 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +0000972 if (err != 0)
973 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000974 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +0000975 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000976 if (fdp == NULL) {
977 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
978 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +0000979 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000980 }
981 else
982 m = NULL;
983 goto cleanup;
984 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000985 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000986 if (fp != NULL)
987 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +0000988 goto cleanup;
989
990 error:
991 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000992 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000993 Py_XDECREF(path);
994 Py_XDECREF(file);
995 return m;
996}
997
998
999/* Helper to test for built-in module */
1000
1001static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001002is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001003{
1004 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +00001005 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1006 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1007 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001008 return -1;
1009 else
1010 return 1;
1011 }
1012 }
1013 return 0;
1014}
1015
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001016
Just van Rossum52e14d62002-12-30 22:08:05 +00001017/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1018 possibly by fetching it from the path_importer_cache dict. If it
1019 wasn't yet cached, traverse path_hooks until it a hook is found
1020 that can handle the path item. Return None if no hook could;
1021 this tells our caller it should fall back to the builtin
1022 import mechanism. Cache the result in path_importer_cache.
1023 Returns a borrowed reference. */
1024
1025static PyObject *
1026get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1027 PyObject *p)
1028{
1029 PyObject *importer;
Martin v. Löwis725507b2006-03-07 12:08:51 +00001030 Py_ssize_t j, nhooks;
Just van Rossum52e14d62002-12-30 22:08:05 +00001031
1032 /* These conditions are the caller's responsibility: */
1033 assert(PyList_Check(path_hooks));
1034 assert(PyDict_Check(path_importer_cache));
1035
1036 nhooks = PyList_Size(path_hooks);
1037 if (nhooks < 0)
1038 return NULL; /* Shouldn't happen */
1039
1040 importer = PyDict_GetItem(path_importer_cache, p);
1041 if (importer != NULL)
1042 return importer;
1043
1044 /* set path_importer_cache[p] to None to avoid recursion */
1045 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1046 return NULL;
1047
1048 for (j = 0; j < nhooks; j++) {
1049 PyObject *hook = PyList_GetItem(path_hooks, j);
1050 if (hook == NULL)
1051 return NULL;
Georg Brandl684fd0c2006-05-25 19:15:31 +00001052 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
Just van Rossum52e14d62002-12-30 22:08:05 +00001053 if (importer != NULL)
1054 break;
1055
1056 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1057 return NULL;
1058 }
1059 PyErr_Clear();
1060 }
1061 if (importer == NULL)
1062 importer = Py_None;
1063 else if (importer != Py_None) {
1064 int err = PyDict_SetItem(path_importer_cache, p, importer);
1065 Py_DECREF(importer);
1066 if (err != 0)
1067 return NULL;
1068 }
1069 return importer;
1070}
1071
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001072/* Search the path (default sys.path) for a module. Return the
1073 corresponding filedescr struct, and (via return arguments) the
1074 pathname and an open file. Return NULL if the module is not found. */
1075
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001076#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001077extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001078 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001079#endif
1080
Martin v. Löwis18e16552006-02-15 17:27:45 +00001081static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001082static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001083static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001084
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001085static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001086find_module(char *fullname, char *subname, PyObject *path, char *buf,
1087 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001088{
Martin v. Löwis725507b2006-03-07 12:08:51 +00001089 Py_ssize_t i, npath;
Fred Drake4c82b232000-06-30 16:18:57 +00001090 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001091 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001092 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001093 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001094 PyObject *path_hooks, *path_importer_cache;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001095#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001096 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001097#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001098 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1099 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1100 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001101 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001102#if defined(PYOS_OS2)
1103 size_t saved_len;
1104 size_t saved_namelen;
1105 char *saved_buf = NULL;
1106#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001107 if (p_loader != NULL)
1108 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001109
Just van Rossum52e14d62002-12-30 22:08:05 +00001110 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001111 PyErr_SetString(PyExc_OverflowError,
1112 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001113 return NULL;
1114 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001115 strcpy(name, subname);
1116
1117 /* sys.meta_path import hook */
1118 if (p_loader != NULL) {
1119 PyObject *meta_path;
1120
1121 meta_path = PySys_GetObject("meta_path");
1122 if (meta_path == NULL || !PyList_Check(meta_path)) {
1123 PyErr_SetString(PyExc_ImportError,
1124 "sys.meta_path must be a list of "
1125 "import hooks");
1126 return NULL;
1127 }
1128 Py_INCREF(meta_path); /* zap guard */
1129 npath = PyList_Size(meta_path);
1130 for (i = 0; i < npath; i++) {
1131 PyObject *loader;
1132 PyObject *hook = PyList_GetItem(meta_path, i);
1133 loader = PyObject_CallMethod(hook, "find_module",
1134 "sO", fullname,
1135 path != NULL ?
1136 path : Py_None);
1137 if (loader == NULL) {
1138 Py_DECREF(meta_path);
1139 return NULL; /* true error */
1140 }
1141 if (loader != Py_None) {
1142 /* a loader was found */
1143 *p_loader = loader;
1144 Py_DECREF(meta_path);
1145 return &importhookdescr;
1146 }
1147 Py_DECREF(loader);
1148 }
1149 Py_DECREF(meta_path);
1150 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001151
1152 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001153 /* The only type of submodule allowed inside a "frozen"
1154 package are other frozen modules or packages. */
Guido van Rossum0506a431998-08-11 15:07:39 +00001155 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1156 PyErr_SetString(PyExc_ImportError,
1157 "full frozen module name too long");
1158 return NULL;
1159 }
1160 strcpy(buf, PyString_AsString(path));
1161 strcat(buf, ".");
1162 strcat(buf, name);
1163 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001164 if (find_frozen(name) != NULL) {
1165 strcpy(buf, name);
1166 return &fd_frozen;
1167 }
1168 PyErr_Format(PyExc_ImportError,
1169 "No frozen submodule named %.200s", name);
1170 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001171 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001172 if (path == NULL) {
1173 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001174 strcpy(buf, name);
1175 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001176 }
Greg Ward201baee2001-10-04 14:52:06 +00001177 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001178 strcpy(buf, name);
1179 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001180 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001181
Guido van Rossumac279101996-08-22 23:10:58 +00001182#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001183 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1184 if (fp != NULL) {
1185 *p_fp = fp;
1186 return fdp;
1187 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001188#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001189 path = PySys_GetObject("path");
1190 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001191 if (path == NULL || !PyList_Check(path)) {
1192 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001193 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001194 return NULL;
1195 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001196
1197 path_hooks = PySys_GetObject("path_hooks");
1198 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1199 PyErr_SetString(PyExc_ImportError,
1200 "sys.path_hooks must be a list of "
1201 "import hooks");
1202 return NULL;
1203 }
1204 path_importer_cache = PySys_GetObject("path_importer_cache");
1205 if (path_importer_cache == NULL ||
1206 !PyDict_Check(path_importer_cache)) {
1207 PyErr_SetString(PyExc_ImportError,
1208 "sys.path_importer_cache must be a dict");
1209 return NULL;
1210 }
1211
Guido van Rossum79f25d91997-04-29 20:08:16 +00001212 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001213 namelen = strlen(name);
1214 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +00001215 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001216 PyObject *v = PyList_GetItem(path, i);
Walter Dörwald3430d702002-06-17 10:43:59 +00001217#ifdef Py_USING_UNICODE
1218 if (PyUnicode_Check(v)) {
1219 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1220 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1221 if (copy == NULL)
1222 return NULL;
1223 v = copy;
1224 }
1225 else
1226#endif
Guido van Rossum79f25d91997-04-29 20:08:16 +00001227 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001228 continue;
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00001229 len = PyString_GET_SIZE(v);
Walter Dörwald3430d702002-06-17 10:43:59 +00001230 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1231 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001232 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001233 }
Neal Norwitz2aa9a5d2006-03-20 01:53:23 +00001234 strcpy(buf, PyString_AS_STRING(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001235 if (strlen(buf) != len) {
1236 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001237 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001238 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001239
1240 /* sys.path_hooks import hook */
1241 if (p_loader != NULL) {
1242 PyObject *importer;
1243
1244 importer = get_path_importer(path_importer_cache,
1245 path_hooks, v);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001246 if (importer == NULL) {
1247 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001248 return NULL;
Neal Norwitza4df11d2006-07-06 04:28:59 +00001249 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001250 /* Note: importer is a borrowed reference */
Georg Brandlf4ef1162006-05-26 18:03:31 +00001251 if (importer == Py_False) {
1252 /* Cached as not being a valid dir. */
1253 Py_XDECREF(copy);
1254 continue;
1255 }
1256 else if (importer == Py_True) {
1257 /* Cached as being a valid dir, so just
1258 * continue below. */
1259 }
1260 else if (importer == Py_None) {
1261 /* No importer was found, so it has to be a file.
Georg Brandl0fd12912006-05-28 20:11:45 +00001262 * Check if the directory is valid.
1263 * Note that the empty string is a valid path, but
1264 * not stat'able, hence the check for len. */
Georg Brandlf4ef1162006-05-26 18:03:31 +00001265#ifdef HAVE_STAT
Georg Brandl0fd12912006-05-28 20:11:45 +00001266 if (len && stat(buf, &statbuf) != 0) {
Georg Brandlf4ef1162006-05-26 18:03:31 +00001267 /* Directory does not exist. */
1268 PyDict_SetItem(path_importer_cache,
1269 v, Py_False);
1270 Py_XDECREF(copy);
1271 continue;
1272 } else {
1273 PyDict_SetItem(path_importer_cache,
1274 v, Py_True);
1275 }
1276#endif
1277 }
1278 else {
1279 /* A real import hook importer was found. */
Just van Rossum52e14d62002-12-30 22:08:05 +00001280 PyObject *loader;
1281 loader = PyObject_CallMethod(importer,
1282 "find_module",
1283 "s", fullname);
Neal Norwitza4df11d2006-07-06 04:28:59 +00001284 Py_XDECREF(copy);
Just van Rossum52e14d62002-12-30 22:08:05 +00001285 if (loader == NULL)
1286 return NULL; /* error */
1287 if (loader != Py_None) {
1288 /* a loader was found */
1289 *p_loader = loader;
1290 return &importhookdescr;
1291 }
1292 Py_DECREF(loader);
Georg Brandlf4ef1162006-05-26 18:03:31 +00001293 continue;
Just van Rossum52e14d62002-12-30 22:08:05 +00001294 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001295 }
Georg Brandlf4ef1162006-05-26 18:03:31 +00001296 /* no hook was found, use builtin import */
Just van Rossum52e14d62002-12-30 22:08:05 +00001297
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001298 if (len > 0 && buf[len-1] != SEP
1299#ifdef ALTSEP
1300 && buf[len-1] != ALTSEP
1301#endif
1302 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001303 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001304 strcpy(buf+len, name);
1305 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001306
1307 /* Check for package import (buf holds a directory name,
1308 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001309#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001310 if (stat(buf, &statbuf) == 0 && /* it exists */
1311 S_ISDIR(statbuf.st_mode) && /* it's a directory */
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001312 case_ok(buf, len, namelen, name)) { /* case matches */
1313 if (find_init_module(buf)) { /* and has __init__.py */
1314 Py_XDECREF(copy);
1315 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);
1322 if (PyErr_Warn(PyExc_ImportWarning,
1323 warnstr)) {
1324 Py_XDECREF(copy);
1325 return NULL;
1326 }
1327 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001328 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001329#else
1330 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001331#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001332 if (isdir(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001333 case_ok(buf, len, namelen, name)) {
Thomas Wouters9df4e6f2006-04-27 23:13:20 +00001334 if (find_init_module(buf)) {
1335 Py_XDECREF(copy);
1336 return &fd_package;
1337 }
1338 else {
1339 char warnstr[MAXPATHLEN+80];
1340 sprintf(warnstr, "Not importing directory "
1341 "'%.*s': missing __init__.py",
1342 MAXPATHLEN, buf);
1343 if (PyErr_Warn(PyExc_ImportWarning,
1344 warnstr)) {
1345 Py_XDECREF(copy);
1346 return NULL;
1347 }
Walter Dörwald3430d702002-06-17 10:43:59 +00001348 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001349#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001350#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001351#if defined(PYOS_OS2)
1352 /* take a snapshot of the module spec for restoration
1353 * after the 8 character DLL hackery
1354 */
1355 saved_buf = strdup(buf);
1356 saved_len = len;
1357 saved_namelen = namelen;
1358#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001359 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001360#if defined(PYOS_OS2)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001361 /* OS/2 limits DLLs to 8 character names (w/o
1362 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001363 * so if the name is longer than that and its a
1364 * dynamically loaded module we're going to try,
1365 * truncate the name before trying
1366 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001367 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001368 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001369 const struct filedescr *scan;
1370 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001371 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001372 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001373 break;
1374 else
1375 scan++;
1376 }
1377 if (scan->suffix != NULL) {
1378 /* yes, so truncate the name */
1379 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001380 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001381 buf[len] = '\0';
1382 }
1383 }
1384#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001385 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001386 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001387 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001388 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001389 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001390 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001391 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001392 if (fp != NULL) {
1393 if (case_ok(buf, len, namelen, name))
1394 break;
1395 else { /* continue search */
1396 fclose(fp);
1397 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001398 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001399 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001400#if defined(PYOS_OS2)
1401 /* restore the saved snapshot */
1402 strcpy(buf, saved_buf);
1403 len = saved_len;
1404 namelen = saved_namelen;
1405#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001406 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001407#if defined(PYOS_OS2)
1408 /* don't need/want the module name snapshot anymore */
1409 if (saved_buf)
1410 {
1411 free(saved_buf);
1412 saved_buf = NULL;
1413 }
1414#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001415 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001416 if (fp != NULL)
1417 break;
1418 }
1419 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001420 PyErr_Format(PyExc_ImportError,
1421 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001422 return NULL;
1423 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001424 *p_fp = fp;
1425 return fdp;
1426}
1427
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001428/* Helpers for main.c
1429 * Find the source file corresponding to a named module
1430 */
1431struct filedescr *
1432_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1433 size_t buflen, FILE **p_fp, PyObject **p_loader)
1434{
1435 return find_module((char *) name, (char *) name, path,
1436 buf, buflen, p_fp, p_loader);
1437}
1438
1439PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1440{
1441 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1442}
1443
Martin v. Löwis18e16552006-02-15 17:27:45 +00001444/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001445 * The arguments here are tricky, best shown by example:
1446 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1447 * ^ ^ ^ ^
1448 * |--------------------- buf ---------------------|
1449 * |------------------- len ------------------|
1450 * |------ name -------|
1451 * |----- namelen -----|
1452 * buf is the full path, but len only counts up to (& exclusive of) the
1453 * extension. name is the module name, also exclusive of extension.
1454 *
1455 * We've already done a successful stat() or fopen() on buf, so know that
1456 * there's some match, possibly case-insensitive.
1457 *
Tim Peters50d8d372001-02-28 05:34:27 +00001458 * case_ok() is to return 1 if there's a case-sensitive match for
1459 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1460 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001461 *
Tim Peters50d8d372001-02-28 05:34:27 +00001462 * case_ok() is used to implement case-sensitive import semantics even
1463 * on platforms with case-insensitive filesystems. It's trivial to implement
1464 * for case-sensitive filesystems. It's pretty much a cross-platform
1465 * nightmare for systems with case-insensitive filesystems.
1466 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001467
Tim Peters50d8d372001-02-28 05:34:27 +00001468/* First we may need a pile of platform-specific header files; the sequence
1469 * of #if's here should match the sequence in the body of case_ok().
1470 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001471#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001472#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001473
Tim Peters50d8d372001-02-28 05:34:27 +00001474#elif defined(DJGPP)
1475#include <dir.h>
1476
Jason Tishler7961aa62005-05-20 00:56:54 +00001477#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001478#include <sys/types.h>
1479#include <dirent.h>
1480
Andrew MacIntyred9400542002-02-26 11:41:34 +00001481#elif defined(PYOS_OS2)
1482#define INCL_DOS
1483#define INCL_DOSERRORS
1484#define INCL_NOPMAPI
1485#include <os2.h>
1486
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001487#elif defined(RISCOS)
1488#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001489#endif
1490
Guido van Rossum0980bd91998-02-13 17:18:36 +00001491static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001492case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001493{
Tim Peters50d8d372001-02-28 05:34:27 +00001494/* Pick a platform-specific implementation; the sequence of #if's here should
1495 * match the sequence just above.
1496 */
1497
Jason Tishler7961aa62005-05-20 00:56:54 +00001498/* MS_WINDOWS */
1499#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001500 WIN32_FIND_DATA data;
1501 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001502
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001503 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001504 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001505
Guido van Rossum0980bd91998-02-13 17:18:36 +00001506 h = FindFirstFile(buf, &data);
1507 if (h == INVALID_HANDLE_VALUE) {
1508 PyErr_Format(PyExc_NameError,
1509 "Can't find file for module %.100s\n(filename %.300s)",
1510 name, buf);
1511 return 0;
1512 }
1513 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001514 return strncmp(data.cFileName, name, namelen) == 0;
1515
1516/* DJGPP */
1517#elif defined(DJGPP)
1518 struct ffblk ffblk;
1519 int done;
1520
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001521 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001522 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001523
1524 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1525 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001526 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001527 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001528 name, buf);
1529 return 0;
1530 }
Tim Peters50d8d372001-02-28 05:34:27 +00001531 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001532
Jason Tishler7961aa62005-05-20 00:56:54 +00001533/* new-fangled macintosh (macosx) or Cygwin */
1534#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001535 DIR *dirp;
1536 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001537 char dirname[MAXPATHLEN + 1];
1538 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001539
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001540 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001541 return 1;
1542
Tim Petersd1e87a82001-03-01 18:12:00 +00001543 /* Copy the dir component into dirname; substitute "." if empty */
1544 if (dirlen <= 0) {
1545 dirname[0] = '.';
1546 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001547 }
1548 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001549 assert(dirlen <= MAXPATHLEN);
1550 memcpy(dirname, buf, dirlen);
1551 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001552 }
1553 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001554 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001555 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001556 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001557 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001558 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001559#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001560 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001561#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001562 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001563#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001564 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001565 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001566 (void)closedir(dirp);
1567 return 1; /* Found */
1568 }
1569 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001570 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001571 }
Tim Peters430f5d42001-03-01 01:30:56 +00001572 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001573
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001574/* RISC OS */
1575#elif defined(RISCOS)
1576 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1577 char buf2[MAXPATHLEN+2];
1578 char *nameWithExt = buf+len-namelen;
1579 int canonlen;
1580 os_error *e;
1581
1582 if (Py_GETENV("PYTHONCASEOK") != NULL)
1583 return 1;
1584
1585 /* workaround:
1586 append wildcard, otherwise case of filename wouldn't be touched */
1587 strcpy(buf2, buf);
1588 strcat(buf2, "*");
1589
1590 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1591 canonlen = MAXPATHLEN+1-canonlen;
1592 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1593 return 0;
1594 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1595 return 1; /* match */
1596
1597 return 0;
1598
Andrew MacIntyred9400542002-02-26 11:41:34 +00001599/* OS/2 */
1600#elif defined(PYOS_OS2)
1601 HDIR hdir = 1;
1602 ULONG srchcnt = 1;
1603 FILEFINDBUF3 ffbuf;
1604 APIRET rc;
1605
1606 if (getenv("PYTHONCASEOK") != NULL)
1607 return 1;
1608
1609 rc = DosFindFirst(buf,
1610 &hdir,
1611 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1612 &ffbuf, sizeof(ffbuf),
1613 &srchcnt,
1614 FIL_STANDARD);
1615 if (rc != NO_ERROR)
1616 return 0;
1617 return strncmp(ffbuf.achName, name, namelen) == 0;
1618
Tim Peters50d8d372001-02-28 05:34:27 +00001619/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1620#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001621 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001622
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001623#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001624}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001625
Guido van Rossum0980bd91998-02-13 17:18:36 +00001626
Guido van Rossum197346f1997-10-31 18:38:52 +00001627#ifdef HAVE_STAT
1628/* Helper to look for __init__.py or __init__.py[co] in potential package */
1629static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001630find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001631{
Tim Peters0f9431f2001-07-05 03:47:53 +00001632 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001633 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001634 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001635 struct stat statbuf;
1636
Tim Peters0f9431f2001-07-05 03:47:53 +00001637/* For calling case_ok(buf, len, namelen, name):
1638 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1639 * ^ ^ ^ ^
1640 * |--------------------- buf ---------------------|
1641 * |------------------- len ------------------|
1642 * |------ name -------|
1643 * |----- namelen -----|
1644 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001645 if (save_len + 13 >= MAXPATHLEN)
1646 return 0;
1647 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001648 pname = buf + i;
1649 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001650 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001651 if (case_ok(buf,
1652 save_len + 9, /* len("/__init__") */
1653 8, /* len("__init__") */
1654 pname)) {
1655 buf[save_len] = '\0';
1656 return 1;
1657 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001658 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001659 i += strlen(pname);
1660 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001661 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001662 if (case_ok(buf,
1663 save_len + 9, /* len("/__init__") */
1664 8, /* len("__init__") */
1665 pname)) {
1666 buf[save_len] = '\0';
1667 return 1;
1668 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001669 }
1670 buf[save_len] = '\0';
1671 return 0;
1672}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001673
1674#else
1675
1676#ifdef RISCOS
1677static int
1678find_init_module(buf)
1679 char *buf;
1680{
1681 int save_len = strlen(buf);
1682 int i = save_len;
1683
1684 if (save_len + 13 >= MAXPATHLEN)
1685 return 0;
1686 buf[i++] = SEP;
1687 strcpy(buf+i, "__init__/py");
1688 if (isfile(buf)) {
1689 buf[save_len] = '\0';
1690 return 1;
1691 }
1692
1693 if (Py_OptimizeFlag)
1694 strcpy(buf+i, "o");
1695 else
1696 strcpy(buf+i, "c");
1697 if (isfile(buf)) {
1698 buf[save_len] = '\0';
1699 return 1;
1700 }
1701 buf[save_len] = '\0';
1702 return 0;
1703}
1704#endif /*RISCOS*/
1705
Guido van Rossum197346f1997-10-31 18:38:52 +00001706#endif /* HAVE_STAT */
1707
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001708
Tim Petersdbd9ba62000-07-09 03:09:57 +00001709static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001710
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001711/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001712 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001713
Guido van Rossum79f25d91997-04-29 20:08:16 +00001714static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001715load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001716{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001717 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001718 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001719 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001720
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001721 /* First check that there's an open file (if we need one) */
1722 switch (type) {
1723 case PY_SOURCE:
1724 case PY_COMPILED:
1725 if (fp == NULL) {
1726 PyErr_Format(PyExc_ValueError,
1727 "file object required for import (type code %d)",
1728 type);
1729 return NULL;
1730 }
1731 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001732
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001733 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001734
1735 case PY_SOURCE:
1736 m = load_source_module(name, buf, fp);
1737 break;
1738
1739 case PY_COMPILED:
1740 m = load_compiled_module(name, buf, fp);
1741 break;
1742
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001743#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001744 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001745 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001746 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001747#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001748
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001749 case PKG_DIRECTORY:
1750 m = load_package(name, buf);
1751 break;
1752
1753 case C_BUILTIN:
1754 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001755 if (buf != NULL && buf[0] != '\0')
1756 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001757 if (type == C_BUILTIN)
1758 err = init_builtin(name);
1759 else
1760 err = PyImport_ImportFrozenModule(name);
1761 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001762 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001763 if (err == 0) {
1764 PyErr_Format(PyExc_ImportError,
1765 "Purported %s module %.200s not found",
1766 type == C_BUILTIN ?
1767 "builtin" : "frozen",
1768 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001769 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001770 }
1771 modules = PyImport_GetModuleDict();
1772 m = PyDict_GetItemString(modules, name);
1773 if (m == NULL) {
1774 PyErr_Format(
1775 PyExc_ImportError,
1776 "%s module %.200s not properly initialized",
1777 type == C_BUILTIN ?
1778 "builtin" : "frozen",
1779 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001780 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001781 }
1782 Py_INCREF(m);
1783 break;
1784
Just van Rossum52e14d62002-12-30 22:08:05 +00001785 case IMP_HOOK: {
1786 if (loader == NULL) {
1787 PyErr_SetString(PyExc_ImportError,
1788 "import hook without loader");
1789 return NULL;
1790 }
1791 m = PyObject_CallMethod(loader, "load_module", "s", name);
1792 break;
1793 }
1794
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001795 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001796 PyErr_Format(PyExc_ImportError,
1797 "Don't know how to import %.200s (type code %d)",
1798 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001799 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001800
1801 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001802
1803 return m;
1804}
1805
1806
1807/* Initialize a built-in module.
1808 Return 1 for succes, 0 if the module is not found, and -1 with
1809 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001810
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001811static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001812init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001813{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001814 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001815
Greg Ward201baee2001-10-04 14:52:06 +00001816 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001817 return 1;
1818
Guido van Rossum771c6c81997-10-31 18:37:24 +00001819 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001820 if (strcmp(name, p->name) == 0) {
1821 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001822 PyErr_Format(PyExc_ImportError,
1823 "Cannot re-init internal module %.200s",
1824 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001825 return -1;
1826 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001827 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001828 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001829 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001830 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001831 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001832 if (_PyImport_FixupExtension(name, name) == NULL)
1833 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001834 return 1;
1835 }
1836 }
1837 return 0;
1838}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001839
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001840
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001841/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001842
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001843static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001844find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001845{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001846 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001847
Guido van Rossum79f25d91997-04-29 20:08:16 +00001848 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001849 if (p->name == NULL)
1850 return NULL;
1851 if (strcmp(p->name, name) == 0)
1852 break;
1853 }
1854 return p;
1855}
1856
Guido van Rossum79f25d91997-04-29 20:08:16 +00001857static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001858get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001859{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001860 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001861 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001862
1863 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001864 PyErr_Format(PyExc_ImportError,
1865 "No such frozen object named %.200s",
1866 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001867 return NULL;
1868 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001869 if (p->code == NULL) {
1870 PyErr_Format(PyExc_ImportError,
1871 "Excluded frozen object named %.200s",
1872 name);
1873 return NULL;
1874 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001875 size = p->size;
1876 if (size < 0)
1877 size = -size;
1878 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001879}
1880
1881/* Initialize a frozen module.
1882 Return 1 for succes, 0 if the module is not found, and -1 with
1883 an exception set if the initialization failed.
1884 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001885
1886int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001887PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001888{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001889 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001890 PyObject *co;
1891 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001892 int ispackage;
1893 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001894
1895 if (p == NULL)
1896 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001897 if (p->code == NULL) {
1898 PyErr_Format(PyExc_ImportError,
1899 "Excluded frozen object named %.200s",
1900 name);
1901 return -1;
1902 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001903 size = p->size;
1904 ispackage = (size < 0);
1905 if (ispackage)
1906 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001907 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001908 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001909 name, ispackage ? " package" : "");
1910 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001911 if (co == NULL)
1912 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001913 if (!PyCode_Check(co)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001914 PyErr_Format(PyExc_TypeError,
1915 "frozen object %.200s is not a code object",
1916 name);
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001917 goto err_return;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001918 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001919 if (ispackage) {
1920 /* Set __path__ to the package name */
1921 PyObject *d, *s;
1922 int err;
1923 m = PyImport_AddModule(name);
1924 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001925 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001926 d = PyModule_GetDict(m);
1927 s = PyString_InternFromString(name);
1928 if (s == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001929 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001930 err = PyDict_SetItemString(d, "__path__", s);
1931 Py_DECREF(s);
1932 if (err != 0)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001933 goto err_return;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001934 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001935 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001936 if (m == NULL)
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001937 goto err_return;
1938 Py_DECREF(co);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001939 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001940 return 1;
Neal Norwitzc0cde4d2006-07-16 02:17:36 +00001941err_return:
1942 Py_DECREF(co);
1943 return -1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001944}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001945
1946
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001947/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001948 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001949
Guido van Rossum79f25d91997-04-29 20:08:16 +00001950PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001951PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001952{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001953 PyObject *pname;
1954 PyObject *result;
1955
1956 pname = PyString_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001957 if (pname == NULL)
1958 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001959 result = PyImport_Import(pname);
1960 Py_DECREF(pname);
1961 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001962}
1963
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001964/* Forward declarations for helper routines */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001965static PyObject *get_parent(PyObject *globals, char *buf,
1966 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001967static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001968 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001969static int mark_miss(char *name);
1970static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001971 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001972static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001973
1974/* The Magnum Opus of dotted-name import :-) */
1975
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001976static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001977import_module_level(char *name, PyObject *globals, PyObject *locals,
1978 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001979{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001980 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00001981 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001982 PyObject *parent, *head, *next, *tail;
1983
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001984 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001985 if (parent == NULL)
1986 return NULL;
1987
1988 head = load_next(parent, Py_None, &name, buf, &buflen);
1989 if (head == NULL)
1990 return NULL;
1991
1992 tail = head;
1993 Py_INCREF(tail);
1994 while (name) {
1995 next = load_next(tail, tail, &name, buf, &buflen);
1996 Py_DECREF(tail);
1997 if (next == NULL) {
1998 Py_DECREF(head);
1999 return NULL;
2000 }
2001 tail = next;
2002 }
Thomas Wouters8ddab272006-04-04 16:17:02 +00002003 if (tail == Py_None) {
2004 /* If tail is Py_None, both get_parent and load_next found
2005 an empty module name: someone called __import__("") or
2006 doctored faulty bytecode */
Thomas Wouters4bdaa272006-04-05 13:39:37 +00002007 Py_DECREF(tail);
2008 Py_DECREF(head);
Thomas Wouters8ddab272006-04-04 16:17:02 +00002009 PyErr_SetString(PyExc_ValueError,
2010 "Empty module name");
2011 return NULL;
2012 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002013
2014 if (fromlist != NULL) {
2015 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2016 fromlist = NULL;
2017 }
2018
2019 if (fromlist == NULL) {
2020 Py_DECREF(tail);
2021 return head;
2022 }
2023
2024 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002025 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002026 Py_DECREF(tail);
2027 return NULL;
2028 }
2029
2030 return tail;
2031}
2032
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002033/* For DLL compatibility */
2034#undef PyImport_ImportModuleEx
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002035PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002036PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
2037 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002038{
2039 PyObject *result;
2040 lock_import();
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002041 result = import_module_level(name, globals, locals, fromlist, -1);
2042 if (unlock_import() < 0) {
2043 Py_XDECREF(result);
2044 PyErr_SetString(PyExc_RuntimeError,
2045 "not holding the import lock");
2046 return NULL;
2047 }
2048 return result;
2049}
2050#define PyImport_ImportModuleEx(n, g, l, f) \
2051 PyImport_ImportModuleLevel(n, g, l, f, -1);
2052
2053PyObject *
2054PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2055 PyObject *fromlist, int level)
2056{
2057 PyObject *result;
2058 lock_import();
2059 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002060 if (unlock_import() < 0) {
2061 Py_XDECREF(result);
2062 PyErr_SetString(PyExc_RuntimeError,
2063 "not holding the import lock");
2064 return NULL;
2065 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00002066 return result;
2067}
2068
Fred Drake87590902004-05-28 20:21:36 +00002069/* Return the package that an import is being performed in. If globals comes
2070 from the module foo.bar.bat (not itself a package), this returns the
2071 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
Georg Brandl5f6861d2006-05-28 21:57:35 +00002072 the package's entry in sys.modules is returned, as a borrowed reference.
Fred Drake87590902004-05-28 20:21:36 +00002073
2074 The *name* of the returned package is returned in buf, with the length of
2075 the name in *p_buflen.
2076
2077 If globals doesn't come from a package or a module in a package, or a
2078 corresponding entry is not found in sys.modules, Py_None is returned.
2079*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002080static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002081get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002082{
2083 static PyObject *namestr = NULL;
2084 static PyObject *pathstr = NULL;
2085 PyObject *modname, *modpath, *modules, *parent;
2086
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002087 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002088 return Py_None;
2089
2090 if (namestr == NULL) {
2091 namestr = PyString_InternFromString("__name__");
2092 if (namestr == NULL)
2093 return NULL;
2094 }
2095 if (pathstr == NULL) {
2096 pathstr = PyString_InternFromString("__path__");
2097 if (pathstr == NULL)
2098 return NULL;
2099 }
2100
2101 *buf = '\0';
2102 *p_buflen = 0;
2103 modname = PyDict_GetItem(globals, namestr);
2104 if (modname == NULL || !PyString_Check(modname))
2105 return Py_None;
2106
2107 modpath = PyDict_GetItem(globals, pathstr);
2108 if (modpath != NULL) {
Martin v. Löwis725507b2006-03-07 12:08:51 +00002109 Py_ssize_t len = PyString_GET_SIZE(modname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002110 if (len > MAXPATHLEN) {
2111 PyErr_SetString(PyExc_ValueError,
2112 "Module name too long");
2113 return NULL;
2114 }
2115 strcpy(buf, PyString_AS_STRING(modname));
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002116 }
2117 else {
2118 char *start = PyString_AS_STRING(modname);
2119 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002120 size_t len;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002121 if (lastdot == NULL && level > 0) {
2122 PyErr_SetString(PyExc_ValueError,
2123 "Relative importpath too deep");
2124 return NULL;
2125 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002126 if (lastdot == NULL)
2127 return Py_None;
2128 len = lastdot - start;
2129 if (len >= MAXPATHLEN) {
2130 PyErr_SetString(PyExc_ValueError,
2131 "Module name too long");
2132 return NULL;
2133 }
2134 strncpy(buf, start, len);
2135 buf[len] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002136 }
2137
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002138 while (--level > 0) {
2139 char *dot = strrchr(buf, '.');
2140 if (dot == NULL) {
2141 PyErr_SetString(PyExc_ValueError,
2142 "Relative importpath too deep");
2143 return NULL;
2144 }
2145 *dot = '\0';
2146 }
2147 *p_buflen = strlen(buf);
2148
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002149 modules = PyImport_GetModuleDict();
2150 parent = PyDict_GetItemString(modules, buf);
2151 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002152 PyErr_Format(PyExc_SystemError,
2153 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002154 return parent;
2155 /* We expect, but can't guarantee, if parent != None, that:
2156 - parent.__name__ == buf
2157 - parent.__dict__ is globals
2158 If this is violated... Who cares? */
2159}
2160
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002161/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002162static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002163load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002164 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002165{
2166 char *name = *p_name;
2167 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002168 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002169 char *p;
2170 PyObject *result;
2171
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002172 if (strlen(name) == 0) {
Thomas Wouters8ddab272006-04-04 16:17:02 +00002173 /* completely empty module name should only happen in
2174 'from . import' (or '__import__("")')*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002175 Py_INCREF(mod);
2176 *p_name = NULL;
2177 return mod;
2178 }
2179
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002180 if (dot == NULL) {
2181 *p_name = NULL;
2182 len = strlen(name);
2183 }
2184 else {
2185 *p_name = dot+1;
2186 len = dot-name;
2187 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002188 if (len == 0) {
2189 PyErr_SetString(PyExc_ValueError,
2190 "Empty module name");
2191 return NULL;
2192 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002193
2194 p = buf + *p_buflen;
2195 if (p != buf)
2196 *p++ = '.';
2197 if (p+len-buf >= MAXPATHLEN) {
2198 PyErr_SetString(PyExc_ValueError,
2199 "Module name too long");
2200 return NULL;
2201 }
2202 strncpy(p, name, len);
2203 p[len] = '\0';
2204 *p_buflen = p+len-buf;
2205
2206 result = import_submodule(mod, p, buf);
2207 if (result == Py_None && altmod != mod) {
2208 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002209 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002210 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002211 if (result != NULL && result != Py_None) {
2212 if (mark_miss(buf) != 0) {
2213 Py_DECREF(result);
2214 return NULL;
2215 }
2216 strncpy(buf, name, len);
2217 buf[len] = '\0';
2218 *p_buflen = len;
2219 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002220 }
2221 if (result == NULL)
2222 return NULL;
2223
2224 if (result == Py_None) {
2225 Py_DECREF(result);
2226 PyErr_Format(PyExc_ImportError,
2227 "No module named %.200s", name);
2228 return NULL;
2229 }
2230
2231 return result;
2232}
2233
2234static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002235mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002236{
2237 PyObject *modules = PyImport_GetModuleDict();
2238 return PyDict_SetItemString(modules, name, Py_None);
2239}
2240
2241static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002242ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002243 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002244{
2245 int i;
2246
2247 if (!PyObject_HasAttrString(mod, "__path__"))
2248 return 1;
2249
2250 for (i = 0; ; i++) {
2251 PyObject *item = PySequence_GetItem(fromlist, i);
2252 int hasit;
2253 if (item == NULL) {
2254 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2255 PyErr_Clear();
2256 return 1;
2257 }
2258 return 0;
2259 }
2260 if (!PyString_Check(item)) {
2261 PyErr_SetString(PyExc_TypeError,
2262 "Item in ``from list'' not a string");
2263 Py_DECREF(item);
2264 return 0;
2265 }
2266 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002267 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002268 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002269 /* See if the package defines __all__ */
2270 if (recursive)
2271 continue; /* Avoid endless recursion */
2272 all = PyObject_GetAttrString(mod, "__all__");
2273 if (all == NULL)
2274 PyErr_Clear();
2275 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002276 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002277 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002278 if (!ret)
2279 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002280 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002281 continue;
2282 }
2283 hasit = PyObject_HasAttr(mod, item);
2284 if (!hasit) {
2285 char *subname = PyString_AS_STRING(item);
2286 PyObject *submod;
2287 char *p;
2288 if (buflen + strlen(subname) >= MAXPATHLEN) {
2289 PyErr_SetString(PyExc_ValueError,
2290 "Module name too long");
2291 Py_DECREF(item);
2292 return 0;
2293 }
2294 p = buf + buflen;
2295 *p++ = '.';
2296 strcpy(p, subname);
2297 submod = import_submodule(mod, subname, buf);
2298 Py_XDECREF(submod);
2299 if (submod == NULL) {
2300 Py_DECREF(item);
2301 return 0;
2302 }
2303 }
2304 Py_DECREF(item);
2305 }
2306
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002307 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002308}
2309
Neil Schemenauer00b09662003-06-16 21:03:07 +00002310static int
2311add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2312 PyObject *modules)
2313{
2314 if (mod == Py_None)
2315 return 1;
2316 /* Irrespective of the success of this load, make a
2317 reference to it in the parent package module. A copy gets
2318 saved in the modules dictionary under the full name, so get a
2319 reference from there, if need be. (The exception is when the
2320 load failed with a SyntaxError -- then there's no trace in
2321 sys.modules. In that case, of course, do nothing extra.) */
2322 if (submod == NULL) {
2323 submod = PyDict_GetItemString(modules, fullname);
2324 if (submod == NULL)
2325 return 1;
2326 }
2327 if (PyModule_Check(mod)) {
2328 /* We can't use setattr here since it can give a
2329 * spurious warning if the submodule name shadows a
2330 * builtin name */
2331 PyObject *dict = PyModule_GetDict(mod);
2332 if (!dict)
2333 return 0;
2334 if (PyDict_SetItemString(dict, subname, submod) < 0)
2335 return 0;
2336 }
2337 else {
2338 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2339 return 0;
2340 }
2341 return 1;
2342}
2343
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002344static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002345import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002346{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002347 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002348 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002349
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002350 /* Require:
2351 if mod == None: subname == fullname
2352 else: mod.__name__ + "." + subname == fullname
2353 */
2354
Tim Peters50d8d372001-02-28 05:34:27 +00002355 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002356 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002357 }
2358 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002359 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002360 char buf[MAXPATHLEN+1];
2361 struct filedescr *fdp;
2362 FILE *fp = NULL;
2363
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002364 if (mod == Py_None)
2365 path = NULL;
2366 else {
2367 path = PyObject_GetAttrString(mod, "__path__");
2368 if (path == NULL) {
2369 PyErr_Clear();
2370 Py_INCREF(Py_None);
2371 return Py_None;
2372 }
2373 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002374
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002375 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002376 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2377 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002378 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002379 if (fdp == NULL) {
2380 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2381 return NULL;
2382 PyErr_Clear();
2383 Py_INCREF(Py_None);
2384 return Py_None;
2385 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002386 m = load_module(fullname, fp, buf, fdp->type, loader);
2387 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002388 if (fp)
2389 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002390 if (!add_submodule(mod, m, fullname, subname, modules)) {
2391 Py_XDECREF(m);
2392 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002393 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002394 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002395
2396 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002397}
2398
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002399
2400/* Re-import a module of any kind and return its module object, WITH
2401 INCREMENTED REFERENCE COUNT */
2402
Guido van Rossum79f25d91997-04-29 20:08:16 +00002403PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002404PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002405{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002406 PyObject *modules = PyImport_GetModuleDict();
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002407 PyObject *path = NULL, *loader = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002408 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002409 char buf[MAXPATHLEN+1];
2410 struct filedescr *fdp;
2411 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002412 PyObject *newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002413
Guido van Rossum79f25d91997-04-29 20:08:16 +00002414 if (m == NULL || !PyModule_Check(m)) {
2415 PyErr_SetString(PyExc_TypeError,
2416 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002417 return NULL;
2418 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002419 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002420 if (name == NULL)
2421 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002422 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002423 PyErr_Format(PyExc_ImportError,
2424 "reload(): module %.200s not in sys.modules",
2425 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002426 return NULL;
2427 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002428 subname = strrchr(name, '.');
2429 if (subname == NULL)
2430 subname = name;
2431 else {
2432 PyObject *parentname, *parent;
2433 parentname = PyString_FromStringAndSize(name, (subname-name));
2434 if (parentname == NULL)
2435 return NULL;
2436 parent = PyDict_GetItem(modules, parentname);
2437 if (parent == NULL) {
2438 PyErr_Format(PyExc_ImportError,
2439 "reload(): parent %.200s not in sys.modules",
Georg Brandl0c55f292005-09-14 06:56:20 +00002440 PyString_AS_STRING(parentname));
2441 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002442 return NULL;
2443 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002444 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002445 subname++;
2446 path = PyObject_GetAttrString(parent, "__path__");
2447 if (path == NULL)
2448 PyErr_Clear();
2449 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002450 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002451 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002452 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002453
2454 if (fdp == NULL) {
2455 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002456 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002457 }
2458
2459 newm = load_module(name, fp, buf, fdp->type, loader);
2460 Py_XDECREF(loader);
2461
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002462 if (fp)
2463 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002464 if (newm == NULL) {
2465 /* load_module probably removed name from modules because of
2466 * the error. Put back the original module object. We're
2467 * going to return NULL in this case regardless of whether
2468 * replacing name succeeds, so the return value is ignored.
2469 */
2470 PyDict_SetItemString(modules, name, m);
2471 }
2472 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002473}
2474
2475
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002476/* Higher-level import emulator which emulates the "import" statement
2477 more accurately -- it invokes the __import__() function from the
2478 builtins of the current globals. This means that the import is
2479 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002480 environment, e.g. by "rexec".
2481 A dummy list ["__doc__"] is passed as the 4th argument so that
2482 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2483 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002484
2485PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002486PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002487{
2488 static PyObject *silly_list = NULL;
2489 static PyObject *builtins_str = NULL;
2490 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002491 PyObject *globals = NULL;
2492 PyObject *import = NULL;
2493 PyObject *builtins = NULL;
2494 PyObject *r = NULL;
2495
2496 /* Initialize constant string objects */
2497 if (silly_list == NULL) {
2498 import_str = PyString_InternFromString("__import__");
2499 if (import_str == NULL)
2500 return NULL;
2501 builtins_str = PyString_InternFromString("__builtins__");
2502 if (builtins_str == NULL)
2503 return NULL;
2504 silly_list = Py_BuildValue("[s]", "__doc__");
2505 if (silly_list == NULL)
2506 return NULL;
2507 }
2508
2509 /* Get the builtins from current globals */
2510 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002511 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002512 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002513 builtins = PyObject_GetItem(globals, builtins_str);
2514 if (builtins == NULL)
2515 goto err;
2516 }
2517 else {
2518 /* No globals -- use standard builtins, and fake globals */
2519 PyErr_Clear();
2520
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002521 builtins = PyImport_ImportModuleLevel("__builtin__",
2522 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002523 if (builtins == NULL)
2524 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002525 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2526 if (globals == NULL)
2527 goto err;
2528 }
2529
2530 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002531 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002532 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002533 if (import == NULL)
2534 PyErr_SetObject(PyExc_KeyError, import_str);
2535 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002536 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002537 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002538 if (import == NULL)
2539 goto err;
2540
2541 /* Call the _import__ function with the proper argument list */
Georg Brandl684fd0c2006-05-25 19:15:31 +00002542 r = PyObject_CallFunctionObjArgs(import, module_name, globals,
2543 globals, silly_list, NULL);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002544
2545 err:
2546 Py_XDECREF(globals);
2547 Py_XDECREF(builtins);
2548 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002549
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002550 return r;
2551}
2552
2553
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002554/* Module 'imp' provides Python access to the primitives used for
2555 importing modules.
2556*/
2557
Guido van Rossum79f25d91997-04-29 20:08:16 +00002558static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002559imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002560{
2561 char buf[4];
2562
Guido van Rossum96774c12000-05-01 20:19:08 +00002563 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2564 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2565 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2566 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002567
Guido van Rossum79f25d91997-04-29 20:08:16 +00002568 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002569}
2570
Guido van Rossum79f25d91997-04-29 20:08:16 +00002571static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002572imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002573{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002574 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002575 struct filedescr *fdp;
2576
Guido van Rossum79f25d91997-04-29 20:08:16 +00002577 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002578 if (list == NULL)
2579 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002580 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2581 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002582 fdp->suffix, fdp->mode, fdp->type);
2583 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002584 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002585 return NULL;
2586 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002587 if (PyList_Append(list, item) < 0) {
2588 Py_DECREF(list);
2589 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002590 return NULL;
2591 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002592 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002593 }
2594 return list;
2595}
2596
Guido van Rossum79f25d91997-04-29 20:08:16 +00002597static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002598call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002599{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002600 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002601 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002602 struct filedescr *fdp;
2603 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002604 FILE *fp = NULL;
2605
2606 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002607 if (path == Py_None)
2608 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002609 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002610 if (fdp == NULL)
2611 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002612 if (fp != NULL) {
2613 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2614 if (fob == NULL) {
2615 fclose(fp);
2616 return NULL;
2617 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002618 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002619 else {
2620 fob = Py_None;
2621 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002622 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002623 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002624 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002625 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002626 return ret;
2627}
2628
Guido van Rossum79f25d91997-04-29 20:08:16 +00002629static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002630imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002631{
2632 char *name;
2633 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002634 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002635 return NULL;
2636 return call_find_module(name, path);
2637}
2638
2639static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002640imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002641{
2642 char *name;
2643 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002644 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002645 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002646 return NULL;
2647 ret = init_builtin(name);
2648 if (ret < 0)
2649 return NULL;
2650 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002651 Py_INCREF(Py_None);
2652 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002653 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002654 m = PyImport_AddModule(name);
2655 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002656 return m;
2657}
2658
Guido van Rossum79f25d91997-04-29 20:08:16 +00002659static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002660imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002661{
2662 char *name;
2663 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002664 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002665 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002666 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002667 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002668 if (ret < 0)
2669 return NULL;
2670 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002671 Py_INCREF(Py_None);
2672 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002673 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002674 m = PyImport_AddModule(name);
2675 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002676 return m;
2677}
2678
Guido van Rossum79f25d91997-04-29 20:08:16 +00002679static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002680imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002681{
2682 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002683
Guido van Rossum43713e52000-02-29 13:59:29 +00002684 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002685 return NULL;
2686 return get_frozen_object(name);
2687}
2688
Guido van Rossum79f25d91997-04-29 20:08:16 +00002689static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002690imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002691{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002692 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002693 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002694 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002695 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002696}
2697
Guido van Rossum79f25d91997-04-29 20:08:16 +00002698static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002699imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002700{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002701 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002702 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002703 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002704 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002705 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002706 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002707}
2708
2709static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002710get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002711{
2712 FILE *fp;
2713 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002714 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002715 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002716 fp = fopen(pathname, mode);
2717 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002718 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002719 }
2720 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002721 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002722 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002723 PyErr_SetString(PyExc_ValueError,
2724 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002725 }
2726 return fp;
2727}
2728
Guido van Rossum79f25d91997-04-29 20:08:16 +00002729static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002730imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002731{
2732 char *name;
2733 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002734 PyObject *fob = NULL;
2735 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002736 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002737 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002738 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002739 return NULL;
2740 fp = get_file(pathname, fob, "rb");
2741 if (fp == NULL)
2742 return NULL;
2743 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002744 if (fob == NULL)
2745 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002746 return m;
2747}
2748
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002749#ifdef HAVE_DYNAMIC_LOADING
2750
Guido van Rossum79f25d91997-04-29 20:08:16 +00002751static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002752imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002753{
2754 char *name;
2755 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002756 PyObject *fob = NULL;
2757 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002758 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002759 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002760 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002761 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002762 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002763 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002764 if (fp == NULL)
2765 return NULL;
2766 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002767 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002768 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002769}
2770
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002771#endif /* HAVE_DYNAMIC_LOADING */
2772
Guido van Rossum79f25d91997-04-29 20:08:16 +00002773static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002774imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002775{
2776 char *name;
2777 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002778 PyObject *fob = NULL;
2779 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002780 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002781 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002782 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002783 return NULL;
2784 fp = get_file(pathname, fob, "r");
2785 if (fp == NULL)
2786 return NULL;
2787 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002788 if (fob == NULL)
2789 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002790 return m;
2791}
2792
Guido van Rossum79f25d91997-04-29 20:08:16 +00002793static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002794imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002795{
2796 char *name;
2797 PyObject *fob;
2798 char *pathname;
2799 char *suffix; /* Unused */
2800 char *mode;
2801 int type;
2802 FILE *fp;
2803
Guido van Rossum43713e52000-02-29 13:59:29 +00002804 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002805 &name, &fob, &pathname,
2806 &suffix, &mode, &type))
2807 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002808 if (*mode) {
2809 /* Mode must start with 'r' or 'U' and must not contain '+'.
2810 Implicit in this test is the assumption that the mode
2811 may contain other modifiers like 'b' or 't'. */
2812
2813 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002814 PyErr_Format(PyExc_ValueError,
2815 "invalid file open mode %.200s", mode);
2816 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002817 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002818 }
2819 if (fob == Py_None)
2820 fp = NULL;
2821 else {
2822 if (!PyFile_Check(fob)) {
2823 PyErr_SetString(PyExc_ValueError,
2824 "load_module arg#2 should be a file or None");
2825 return NULL;
2826 }
2827 fp = get_file(pathname, fob, mode);
2828 if (fp == NULL)
2829 return NULL;
2830 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002831 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002832}
2833
2834static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002835imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002836{
2837 char *name;
2838 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002839 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002840 return NULL;
2841 return load_package(name, pathname);
2842}
2843
2844static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002845imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002846{
2847 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002848 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002849 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002850 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002851}
2852
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002853/* Doc strings */
2854
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002855PyDoc_STRVAR(doc_imp,
2856"This module provides the components needed to build your own\n\
2857__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002858
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002859PyDoc_STRVAR(doc_find_module,
2860"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002861Search for a module. If path is omitted or None, search for a\n\
2862built-in, frozen or special module and continue search in sys.path.\n\
2863The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002864package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002865
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002866PyDoc_STRVAR(doc_load_module,
2867"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002868Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002869The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002870
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002871PyDoc_STRVAR(doc_get_magic,
2872"get_magic() -> string\n\
2873Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002874
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002875PyDoc_STRVAR(doc_get_suffixes,
2876"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002877Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002878that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002879
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002880PyDoc_STRVAR(doc_new_module,
2881"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002882Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002883The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002884
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002885PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002886"lock_held() -> boolean\n\
2887Return True if the import lock is currently held, else False.\n\
2888On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002889
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002890PyDoc_STRVAR(doc_acquire_lock,
2891"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002892Acquires the interpreter's import lock for the current thread.\n\
2893This lock should be used by import hooks to ensure thread-safety\n\
2894when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002895On platforms without threads, this function does nothing.");
2896
2897PyDoc_STRVAR(doc_release_lock,
2898"release_lock() -> None\n\
2899Release the interpreter's import lock.\n\
2900On platforms without threads, this function does nothing.");
2901
Guido van Rossum79f25d91997-04-29 20:08:16 +00002902static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002903 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2904 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2905 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2906 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2907 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2908 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2909 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2910 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002911 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00002912 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2913 {"init_builtin", imp_init_builtin, METH_VARARGS},
2914 {"init_frozen", imp_init_frozen, METH_VARARGS},
2915 {"is_builtin", imp_is_builtin, METH_VARARGS},
2916 {"is_frozen", imp_is_frozen, METH_VARARGS},
2917 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002918#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00002919 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002920#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002921 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00002922 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002923 {NULL, NULL} /* sentinel */
2924};
2925
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002926static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002927setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002928{
2929 PyObject *v;
2930 int err;
2931
2932 v = PyInt_FromLong((long)value);
2933 err = PyDict_SetItemString(d, name, v);
2934 Py_XDECREF(v);
2935 return err;
2936}
2937
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002938PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002939initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002940{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002941 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002942
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002943 m = Py_InitModule4("imp", imp_methods, doc_imp,
2944 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00002945 if (m == NULL)
2946 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002947 d = PyModule_GetDict(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002948
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002949 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2950 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2951 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2952 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2953 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2954 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2955 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2956 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00002957 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00002958 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002959
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002960 failure:
2961 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002962}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002963
2964
Guido van Rossumb18618d2000-05-03 23:44:39 +00002965/* API for embedding applications that want to add their own entries
2966 to the table of built-in modules. This should normally be called
2967 *before* Py_Initialize(). When the table resize fails, -1 is
2968 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002969
2970 After a similar function by Just van Rossum. */
2971
2972int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002973PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002974{
2975 static struct _inittab *our_copy = NULL;
2976 struct _inittab *p;
2977 int i, n;
2978
2979 /* Count the number of entries in both tables */
2980 for (n = 0; newtab[n].name != NULL; n++)
2981 ;
2982 if (n == 0)
2983 return 0; /* Nothing to do */
2984 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2985 ;
2986
2987 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00002988 p = our_copy;
2989 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002990 if (p == NULL)
2991 return -1;
2992
2993 /* Copy the tables into the new memory */
2994 if (our_copy != PyImport_Inittab)
2995 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2996 PyImport_Inittab = our_copy = p;
2997 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2998
2999 return 0;
3000}
3001
3002/* Shorthand to add a single entry given a name and a function */
3003
3004int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00003005PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00003006{
3007 struct _inittab newtab[2];
3008
3009 memset(newtab, '\0', sizeof newtab);
3010
3011 newtab[0].name = name;
3012 newtab[0].initfunc = initfunc;
3013
3014 return PyImport_ExtendInittab(newtab);
3015}
Anthony Baxterac6bd462006-04-13 02:06:09 +00003016
3017#ifdef __cplusplus
3018}
3019#endif