blob: e33d32e4c86d749c6b767cc45f2833c157b08db1 [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
20
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000021extern time_t PyOS_GetLastModificationTime(char *, FILE *);
22 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000023
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000024/* Magic word to reject .pyc files generated by other Python versions.
25 It should change for each incompatible change to the bytecode.
26
27 The value of CR and LF is incorporated so if you ever read or write
Guido van Rossum7faeab31995-07-07 22:50:36 +000028 a .pyc file in text mode the magic number will be wrong; also, the
Tim Peters36515e22001-11-18 04:06:29 +000029 Apple MPW compiler swaps their values, botching string constants.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000030
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000031 The magic numbers must be spaced apart atleast 2 values, as the
32 -U interpeter flag will cause MAGIC+1 being used. They have been
33 odd numbers for some time now.
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000034
Jeremy Hyltond4ceb312004-04-01 02:45:22 +000035 There were a variety of old schemes for setting the magic number.
36 The current working scheme is to increment the previous value by
37 10.
Guido van Rossumf6894922002-08-31 15:16:14 +000038
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +000039 Known values:
40 Python 1.5: 20121
41 Python 1.5.1: 20121
42 Python 1.5.2: 20121
43 Python 2.0: 50823
44 Python 2.0.1: 50823
45 Python 2.1: 60202
46 Python 2.1.1: 60202
47 Python 2.1.2: 60202
48 Python 2.2: 60717
Neal Norwitz7fdcb412002-06-14 01:07:39 +000049 Python 2.3a0: 62011
Michael W. Hudsondd32a912002-08-15 14:59:02 +000050 Python 2.3a0: 62021
Guido van Rossumf6894922002-08-31 15:16:14 +000051 Python 2.3a0: 62011 (!)
Martin v. Löwisef82d2f2004-06-27 16:51:46 +000052 Python 2.4a0: 62041
Raymond Hettingerfd2d1f72004-08-23 23:37:48 +000053 Python 2.4a3: 62051
Raymond Hettinger2c31a052004-09-22 18:44:21 +000054 Python 2.4b1: 62061
Michael W. Hudsondf888462005-06-03 14:41:55 +000055 Python 2.5a0: 62071
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000056 Python 2.5a0: 62081 (ast-branch)
Guido van Rossumc2e20742006-02-27 22:32:47 +000057 Python 2.5a0: 62091 (with)
Michael W. Hudsonaee2e282005-10-21 11:32:20 +000058.
Tim Peters36515e22001-11-18 04:06:29 +000059*/
Guido van Rossumc2e20742006-02-27 22:32:47 +000060#define MAGIC (62091 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000061
Guido van Rossum96774c12000-05-01 20:19:08 +000062/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000063 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000064 compiler works which are enabled by command line switches. */
65static long pyc_magic = MAGIC;
66
Guido van Rossum25ce5661997-08-02 03:10:38 +000067/* See _PyImport_FixupExtension() below */
68static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000069
Guido van Rossum771c6c81997-10-31 18:37:24 +000070/* This table is defined in config.c: */
71extern struct _inittab _PyImport_Inittab[];
72
73struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000074
Guido van Rossumed1170e1999-12-20 21:23:41 +000075/* these tables define the module suffixes that Python recognizes */
76struct filedescr * _PyImport_Filetab = NULL;
Guido van Rossum48a680c2001-03-02 06:34:14 +000077
78#ifdef RISCOS
79static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000080 {"/py", "U", PY_SOURCE},
Guido van Rossum48a680c2001-03-02 06:34:14 +000081 {"/pyc", "rb", PY_COMPILED},
82 {0, 0}
83};
84#else
Guido van Rossumed1170e1999-12-20 21:23:41 +000085static const struct filedescr _PyImport_StandardFiletab[] = {
Jack Jansenc88da1f2002-05-28 10:58:19 +000086 {".py", "U", PY_SOURCE},
Martin v. Löwis6238d2b2002-06-30 15:26:10 +000087#ifdef MS_WINDOWS
Jack Jansenc88da1f2002-05-28 10:58:19 +000088 {".pyw", "U", PY_SOURCE},
Tim Peters36515e22001-11-18 04:06:29 +000089#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +000090 {".pyc", "rb", PY_COMPILED},
91 {0, 0}
92};
Guido van Rossum48a680c2001-03-02 06:34:14 +000093#endif
Guido van Rossumed1170e1999-12-20 21:23:41 +000094
Guido van Rossum1ae940a1995-01-02 19:04:15 +000095/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000096
97void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000098_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000099{
Guido van Rossumed1170e1999-12-20 21:23:41 +0000100 const struct filedescr *scan;
101 struct filedescr *filetab;
102 int countD = 0;
103 int countS = 0;
104
105 /* prepare _PyImport_Filetab: copy entries from
106 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
107 */
108 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
109 ++countD;
110 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
111 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000112 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Guido van Rossumed1170e1999-12-20 21:23:41 +0000113 memcpy(filetab, _PyImport_DynLoadFiletab,
114 countD * sizeof(struct filedescr));
115 memcpy(filetab + countD, _PyImport_StandardFiletab,
116 countS * sizeof(struct filedescr));
117 filetab[countD + countS].suffix = NULL;
118
119 _PyImport_Filetab = filetab;
120
Guido van Rossum0824f631997-03-11 18:37:35 +0000121 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +0000122 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
123 for (; filetab->suffix != NULL; filetab++) {
Guido van Rossum48a680c2001-03-02 06:34:14 +0000124#ifndef RISCOS
Guido van Rossumed1170e1999-12-20 21:23:41 +0000125 if (strcmp(filetab->suffix, ".pyc") == 0)
126 filetab->suffix = ".pyo";
Guido van Rossum48a680c2001-03-02 06:34:14 +0000127#else
128 if (strcmp(filetab->suffix, "/pyc") == 0)
129 filetab->suffix = "/pyo";
130#endif
Guido van Rossum0824f631997-03-11 18:37:35 +0000131 }
132 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000133
134 if (Py_UnicodeFlag) {
135 /* Fix the pyc_magic so that byte compiled code created
136 using the all-Unicode method doesn't interfere with
137 code created in normal operation mode. */
138 pyc_magic = MAGIC + 1;
139 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140}
141
Guido van Rossum25ce5661997-08-02 03:10:38 +0000142void
Just van Rossum52e14d62002-12-30 22:08:05 +0000143_PyImportHooks_Init(void)
144{
145 PyObject *v, *path_hooks = NULL, *zimpimport;
146 int err = 0;
147
148 /* adding sys.path_hooks and sys.path_importer_cache, setting up
149 zipimport */
150
151 if (Py_VerboseFlag)
152 PySys_WriteStderr("# installing zipimport hook\n");
153
154 v = PyList_New(0);
155 if (v == NULL)
156 goto error;
157 err = PySys_SetObject("meta_path", v);
158 Py_DECREF(v);
159 if (err)
160 goto error;
161 v = PyDict_New();
162 if (v == NULL)
163 goto error;
164 err = PySys_SetObject("path_importer_cache", v);
165 Py_DECREF(v);
166 if (err)
167 goto error;
168 path_hooks = PyList_New(0);
169 if (path_hooks == NULL)
170 goto error;
171 err = PySys_SetObject("path_hooks", path_hooks);
172 if (err) {
173 error:
174 PyErr_Print();
175 Py_FatalError("initializing sys.meta_path, sys.path_hooks or "
176 "path_importer_cache failed");
177 }
178 zimpimport = PyImport_ImportModule("zipimport");
179 if (zimpimport == NULL) {
180 PyErr_Clear(); /* No zip import module -- okay */
181 if (Py_VerboseFlag)
182 PySys_WriteStderr("# can't import zipimport\n");
183 }
184 else {
185 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
186 "zipimporter");
187 Py_DECREF(zimpimport);
188 if (zipimporter == NULL) {
189 PyErr_Clear(); /* No zipimporter object -- okay */
190 if (Py_VerboseFlag)
191 PySys_WriteStderr(
Fred Drake1e5fc552003-07-11 15:01:02 +0000192 "# can't import zipimport.zipimporter\n");
Just van Rossum52e14d62002-12-30 22:08:05 +0000193 }
194 else {
195 /* sys.path_hooks.append(zipimporter) */
196 err = PyList_Append(path_hooks, zipimporter);
197 Py_DECREF(zipimporter);
198 if (err)
199 goto error;
200 if (Py_VerboseFlag)
201 PySys_WriteStderr(
202 "# installed zipimport hook\n");
203 }
204 }
205 Py_DECREF(path_hooks);
206}
207
208void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000209_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000210{
211 Py_XDECREF(extensions);
212 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000213 PyMem_DEL(_PyImport_Filetab);
214 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000215}
216
217
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000218/* Locking primitives to prevent parallel imports of the same module
219 in different threads to return with a partially loaded module.
220 These calls are serialized by the global interpreter lock. */
221
222#ifdef WITH_THREAD
223
Guido van Rossum49b56061998-10-01 20:42:43 +0000224#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000225
Guido van Rossum65d5b571998-12-21 19:32:43 +0000226static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000227static long import_lock_thread = -1;
228static int import_lock_level = 0;
229
230static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000231lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000232{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000233 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000234 if (me == -1)
235 return; /* Too bad */
236 if (import_lock == NULL)
Guido van Rossum65d5b571998-12-21 19:32:43 +0000237 import_lock = PyThread_allocate_lock();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000238 if (import_lock_thread == me) {
239 import_lock_level++;
240 return;
241 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000242 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
243 {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000244 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000245 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000246 PyEval_RestoreThread(tstate);
247 }
248 import_lock_thread = me;
249 import_lock_level = 1;
250}
251
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000252static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000253unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000254{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000255 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000256 if (me == -1)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000257 return 0; /* Too bad */
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000258 if (import_lock_thread != me)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000259 return -1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000260 import_lock_level--;
261 if (import_lock_level == 0) {
262 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000263 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000264 }
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000265 return 1;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000266}
267
Guido van Rossum8ee3e5a2005-09-14 18:09:42 +0000268/* This function is called from PyOS_AfterFork to ensure that newly
269 created child processes do not share locks with the parent. */
270
271void
272_PyImport_ReInitLock(void)
273{
274#ifdef _AIX
275 if (import_lock != NULL)
276 import_lock = PyThread_allocate_lock();
277#endif
278}
279
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000280#else
281
282#define lock_import()
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000283#define unlock_import() 0
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000284
285#endif
286
Tim Peters69232342001-08-30 05:16:13 +0000287static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000288imp_lock_held(PyObject *self, PyObject *noargs)
Tim Peters69232342001-08-30 05:16:13 +0000289{
Tim Peters69232342001-08-30 05:16:13 +0000290#ifdef WITH_THREAD
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000291 return PyBool_FromLong(import_lock_thread != -1);
Tim Peters69232342001-08-30 05:16:13 +0000292#else
Guido van Rossumb8bff3f2002-04-07 06:34:38 +0000293 return PyBool_FromLong(0);
Tim Peters69232342001-08-30 05:16:13 +0000294#endif
295}
296
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000297static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000298imp_acquire_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000299{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000300#ifdef WITH_THREAD
301 lock_import();
302#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000303 Py_INCREF(Py_None);
304 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000305}
306
307static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +0000308imp_release_lock(PyObject *self, PyObject *noargs)
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000309{
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000310#ifdef WITH_THREAD
311 if (unlock_import() < 0) {
312 PyErr_SetString(PyExc_RuntimeError,
313 "not holding the import lock");
314 return NULL;
315 }
316#endif
Neal Norwitz2294c0d2003-02-12 23:02:21 +0000317 Py_INCREF(Py_None);
318 return Py_None;
Guido van Rossumc4f4ca92003-02-12 21:46:11 +0000319}
320
Guido van Rossum25ce5661997-08-02 03:10:38 +0000321/* Helper for sys */
322
323PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000324PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000325{
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000326 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000327 if (interp->modules == NULL)
328 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
329 return interp->modules;
330}
331
Guido van Rossum3f5da241990-12-20 15:06:42 +0000332
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000333/* List of names to clear in sys */
334static char* sys_deletes[] = {
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000335 "path", "argv", "ps1", "ps2", "exitfunc",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000336 "exc_type", "exc_value", "exc_traceback",
337 "last_type", "last_value", "last_traceback",
Just van Rossum52e14d62002-12-30 22:08:05 +0000338 "path_hooks", "path_importer_cache", "meta_path",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000339 NULL
340};
341
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000342static char* sys_files[] = {
343 "stdin", "__stdin__",
344 "stdout", "__stdout__",
345 "stderr", "__stderr__",
346 NULL
347};
348
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000349
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000350/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000351
Guido van Rossum3f5da241990-12-20 15:06:42 +0000352void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000353PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000354{
Martin v. Löwis18e16552006-02-15 17:27:45 +0000355 Py_ssize_t pos, ndone;
Guido van Rossum758eec01998-01-19 21:58:26 +0000356 char *name;
357 PyObject *key, *value, *dict;
Nicholas Bastine5662ae2004-03-24 22:22:12 +0000358 PyInterpreterState *interp = PyThreadState_GET()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000359 PyObject *modules = interp->modules;
360
361 if (modules == NULL)
362 return; /* Already done */
363
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000364 /* Delete some special variables first. These are common
365 places where user values hide and people complain when their
366 destructors fail. Since the modules containing them are
367 deleted *last* of all, they would come too late in the normal
368 destruction order. Sigh. */
369
370 value = PyDict_GetItemString(modules, "__builtin__");
371 if (value != NULL && PyModule_Check(value)) {
372 dict = PyModule_GetDict(value);
373 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000374 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000375 PyDict_SetItemString(dict, "_", Py_None);
376 }
377 value = PyDict_GetItemString(modules, "sys");
378 if (value != NULL && PyModule_Check(value)) {
379 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000380 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000381 dict = PyModule_GetDict(value);
382 for (p = sys_deletes; *p != NULL; p++) {
383 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000384 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000385 PyDict_SetItemString(dict, *p, Py_None);
386 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000387 for (p = sys_files; *p != NULL; p+=2) {
388 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000389 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000390 v = PyDict_GetItemString(dict, *(p+1));
391 if (v == NULL)
392 v = Py_None;
393 PyDict_SetItemString(dict, *p, v);
394 }
395 }
396
397 /* First, delete __main__ */
398 value = PyDict_GetItemString(modules, "__main__");
399 if (value != NULL && PyModule_Check(value)) {
400 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000401 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000402 _PyModule_Clear(value);
403 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000404 }
405
Guido van Rossum758eec01998-01-19 21:58:26 +0000406 /* The special treatment of __builtin__ here is because even
407 when it's not referenced as a module, its dictionary is
408 referenced by almost every module's __builtins__. Since
409 deleting a module clears its dictionary (even if there are
410 references left to it), we need to delete the __builtin__
411 module last. Likewise, we don't delete sys until the very
412 end because it is implicitly referenced (e.g. by print).
413
414 Also note that we 'delete' modules by replacing their entry
415 in the modules dict with None, rather than really deleting
416 them; this avoids a rehash of the modules dictionary and
417 also marks them as "non existent" so they won't be
418 re-imported. */
419
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000420 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000421 one (skipping __builtin__ and sys) and delete them */
422 do {
423 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000424 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000425 while (PyDict_Next(modules, &pos, &key, &value)) {
426 if (value->ob_refcnt != 1)
427 continue;
Guido van Rossum566373e1998-10-01 15:24:50 +0000428 if (PyString_Check(key) && PyModule_Check(value)) {
429 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000430 if (strcmp(name, "__builtin__") == 0)
431 continue;
432 if (strcmp(name, "sys") == 0)
433 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000434 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000435 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000436 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000437 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000438 PyDict_SetItem(modules, key, Py_None);
439 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000440 }
441 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000442 } while (ndone > 0);
443
Guido van Rossum758eec01998-01-19 21:58:26 +0000444 /* Next, delete all modules (still skipping __builtin__ and sys) */
445 pos = 0;
446 while (PyDict_Next(modules, &pos, &key, &value)) {
Guido van Rossum566373e1998-10-01 15:24:50 +0000447 if (PyString_Check(key) && PyModule_Check(value)) {
448 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000449 if (strcmp(name, "__builtin__") == 0)
450 continue;
451 if (strcmp(name, "sys") == 0)
452 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000453 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000454 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000455 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000456 PyDict_SetItem(modules, key, Py_None);
457 }
458 }
459
460 /* Next, delete sys and __builtin__ (in that order) */
461 value = PyDict_GetItemString(modules, "sys");
462 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000463 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000464 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000465 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000466 PyDict_SetItemString(modules, "sys", Py_None);
467 }
468 value = PyDict_GetItemString(modules, "__builtin__");
469 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000470 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000471 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000472 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000473 PyDict_SetItemString(modules, "__builtin__", Py_None);
474 }
475
476 /* Finally, clear and delete the modules directory */
477 PyDict_Clear(modules);
478 interp->modules = NULL;
479 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000480}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000481
482
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000483/* Helper for pythonrun.c -- return magic number */
484
485long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000486PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000487{
Guido van Rossum96774c12000-05-01 20:19:08 +0000488 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000489}
490
491
Guido van Rossum25ce5661997-08-02 03:10:38 +0000492/* Magic for extension modules (built-in as well as dynamically
493 loaded). To prevent initializing an extension module more than
494 once, we keep a static dictionary 'extensions' keyed by module name
495 (for built-in modules) or by filename (for dynamically loaded
Barry Warsaw92883382001-08-13 23:05:44 +0000496 modules), containing these modules. A copy of the module's
Guido van Rossum25ce5661997-08-02 03:10:38 +0000497 dictionary is stored by calling _PyImport_FixupExtension()
498 immediately after the module initialization function succeeds. A
499 copy can be retrieved from there by calling
500 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000501
Guido van Rossum79f25d91997-04-29 20:08:16 +0000502PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000503_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000504{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000505 PyObject *modules, *mod, *dict, *copy;
506 if (extensions == NULL) {
507 extensions = PyDict_New();
508 if (extensions == NULL)
509 return NULL;
510 }
511 modules = PyImport_GetModuleDict();
512 mod = PyDict_GetItemString(modules, name);
513 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000514 PyErr_Format(PyExc_SystemError,
515 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000516 return NULL;
517 }
518 dict = PyModule_GetDict(mod);
519 if (dict == NULL)
520 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000521 copy = PyDict_Copy(dict);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000522 if (copy == NULL)
523 return NULL;
524 PyDict_SetItemString(extensions, filename, copy);
525 Py_DECREF(copy);
526 return copy;
527}
528
529PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000530_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000531{
Fred Drake9cd0efc2001-10-25 21:38:59 +0000532 PyObject *dict, *mod, *mdict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000533 if (extensions == NULL)
534 return NULL;
535 dict = PyDict_GetItemString(extensions, filename);
536 if (dict == NULL)
537 return NULL;
538 mod = PyImport_AddModule(name);
539 if (mod == NULL)
540 return NULL;
541 mdict = PyModule_GetDict(mod);
542 if (mdict == NULL)
543 return NULL;
Fred Drake9cd0efc2001-10-25 21:38:59 +0000544 if (PyDict_Update(mdict, dict))
Guido van Rossum25ce5661997-08-02 03:10:38 +0000545 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000546 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000547 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000548 name, filename);
549 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000550}
551
552
553/* Get the module object corresponding to a module name.
554 First check the modules dictionary if there's one there,
Walter Dörwaldf0dfc7a2003-10-20 14:01:56 +0000555 if not, create a new one and insert it in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000556 Because the former action is most common, THIS DOES NOT RETURN A
557 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000558
Guido van Rossum79f25d91997-04-29 20:08:16 +0000559PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000560PyImport_AddModule(const char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000561{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000562 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000563 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000564
Guido van Rossum25ce5661997-08-02 03:10:38 +0000565 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000566 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000567 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000568 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000569 if (m == NULL)
570 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000571 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000572 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573 return NULL;
574 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000575 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000576
577 return m;
578}
579
Tim Peters1cd70172004-08-02 03:52:12 +0000580/* Remove name from sys.modules, if it's there. */
581static void
582_RemoveModule(const char *name)
583{
584 PyObject *modules = PyImport_GetModuleDict();
585 if (PyDict_GetItemString(modules, name) == NULL)
586 return;
587 if (PyDict_DelItemString(modules, name) < 0)
588 Py_FatalError("import: deleting existing key in"
589 "sys.modules failed");
590}
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000591
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000592/* Execute a code object in a module and return the module object
Tim Peters1cd70172004-08-02 03:52:12 +0000593 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
594 * removed from sys.modules, to avoid leaving damaged module objects
595 * in sys.modules. The caller may wish to restore the original
596 * module object (if any) in this case; PyImport_ReloadModule is an
597 * example.
598 */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000599PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000600PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000601{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000602 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
603}
604
605PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000606PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000607{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000608 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000609 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000610
Guido van Rossum79f25d91997-04-29 20:08:16 +0000611 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000612 if (m == NULL)
613 return NULL;
Jeremy Hyltonecd91292004-01-02 23:25:32 +0000614 /* If the module is being reloaded, we get the old module back
615 and re-use its dict to exec the new code. */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000616 d = PyModule_GetDict(m);
617 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
618 if (PyDict_SetItemString(d, "__builtins__",
619 PyEval_GetBuiltins()) != 0)
Tim Peters1cd70172004-08-02 03:52:12 +0000620 goto error;
Guido van Rossum6135a871995-01-09 17:53:26 +0000621 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000622 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000623 v = NULL;
624 if (pathname != NULL) {
625 v = PyString_FromString(pathname);
626 if (v == NULL)
627 PyErr_Clear();
628 }
629 if (v == NULL) {
630 v = ((PyCodeObject *)co)->co_filename;
631 Py_INCREF(v);
632 }
633 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000634 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000635 Py_DECREF(v);
636
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000637 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000638 if (v == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000639 goto error;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000640 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000641
Guido van Rossum25ce5661997-08-02 03:10:38 +0000642 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000643 PyErr_Format(PyExc_ImportError,
644 "Loaded module %.200s not found in sys.modules",
645 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000646 return NULL;
647 }
648
Guido van Rossum79f25d91997-04-29 20:08:16 +0000649 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000650
651 return m;
Tim Peters1cd70172004-08-02 03:52:12 +0000652
653 error:
654 _RemoveModule(name);
655 return NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000656}
657
658
659/* Given a pathname for a Python source file, fill a buffer with the
660 pathname for the corresponding compiled file. Return the pathname
661 for the compiled file, or NULL if there's no space in the buffer.
662 Doesn't set an exception. */
663
664static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000665make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000666{
Tim Petersc1731372001-08-04 08:12:36 +0000667 size_t len = strlen(pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000668 if (len+2 > buflen)
669 return NULL;
Tim Petersc1731372001-08-04 08:12:36 +0000670
Martin v. Löwis6238d2b2002-06-30 15:26:10 +0000671#ifdef MS_WINDOWS
Tim Petersc1731372001-08-04 08:12:36 +0000672 /* Treat .pyw as if it were .py. The case of ".pyw" must match
673 that used in _PyImport_StandardFiletab. */
674 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
675 --len; /* pretend 'w' isn't there */
676#endif
677 memcpy(buf, pathname, len);
678 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
679 buf[len+1] = '\0';
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680
681 return buf;
682}
683
684
685/* Given a pathname for a Python source file, its time of last
686 modification, and a pathname for a compiled file, check whether the
687 compiled file represents the same version of the source. If so,
688 return a FILE pointer for the compiled file, positioned just after
689 the header; if not, return NULL.
690 Doesn't set an exception. */
691
692static FILE *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000693check_compiled_module(char *pathname, time_t mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000694{
695 FILE *fp;
696 long magic;
697 long pyc_mtime;
698
699 fp = fopen(cpathname, "rb");
700 if (fp == NULL)
701 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000702 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000703 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000704 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000705 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000706 fclose(fp);
707 return NULL;
708 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000709 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000710 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000711 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000712 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000713 fclose(fp);
714 return NULL;
715 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000716 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000717 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000718 return fp;
719}
720
721
722/* Read a code object from a file and check it for validity */
723
Guido van Rossum79f25d91997-04-29 20:08:16 +0000724static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000725read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000726{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000727 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000728
Tim Petersd9b9ac82001-01-28 00:27:39 +0000729 co = PyMarshal_ReadLastObjectFromFile(fp);
Armin Rigo01ab2792004-03-26 15:09:27 +0000730 if (co == NULL)
731 return NULL;
732 if (!PyCode_Check(co)) {
733 PyErr_Format(PyExc_ImportError,
734 "Non-code object in %.200s", cpathname);
735 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000736 return NULL;
737 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000738 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000739}
740
741
742/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000743 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000744
Guido van Rossum79f25d91997-04-29 20:08:16 +0000745static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000746load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000747{
748 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000749 PyCodeObject *co;
750 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000751
Guido van Rossum79f25d91997-04-29 20:08:16 +0000752 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000753 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000754 PyErr_Format(PyExc_ImportError,
755 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000756 return NULL;
757 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000758 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000759 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000760 if (co == NULL)
761 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000762 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000763 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000764 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000765 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000766 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000767
768 return m;
769}
770
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000771/* Parse a source file and return the corresponding code object */
772
Guido van Rossum79f25d91997-04-29 20:08:16 +0000773static PyCodeObject *
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000774parse_source_module(const char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000775{
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000776 PyCodeObject *co = NULL;
777 mod_ty mod;
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000778 PyArena *arena = PyArena_New();
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000779
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000780 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, 0,
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000781 NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000782 if (mod) {
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000783 co = PyAST_Compile(mod, pathname, NULL, arena);
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000784 }
Neal Norwitzadb69fc2005-12-17 20:54:49 +0000785 PyArena_Free(arena);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000786 return co;
787}
788
789
Guido van Rossum55a83382000-09-20 20:31:38 +0000790/* Helper to open a bytecode file for writing in exclusive mode */
791
792static FILE *
793open_exclusive(char *filename)
794{
795#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
796 /* Use O_EXCL to avoid a race condition when another process tries to
797 write the same file. When that happens, our open() call fails,
798 which is just fine (since it's only a cache).
799 XXX If the file exists and is writable but the directory is not
800 writable, the file will never be written. Oh well.
801 */
802 int fd;
803 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000804 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
805#ifdef O_BINARY
806 |O_BINARY /* necessary for Windows */
807#endif
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000808#ifdef __VMS
Martin v. Löwis18e16552006-02-15 17:27:45 +0000809 , 0666, "ctxt=bin", "shr=nil"
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000810#else
Martin v. Löwis18e16552006-02-15 17:27:45 +0000811 , 0666
Martin v. Löwis79acb9e2002-12-06 12:48:53 +0000812#endif
Martin v. Löwis18e16552006-02-15 17:27:45 +0000813 );
Guido van Rossum55a83382000-09-20 20:31:38 +0000814 if (fd < 0)
815 return NULL;
816 return fdopen(fd, "wb");
817#else
818 /* Best we can do -- on Windows this can't happen anyway */
819 return fopen(filename, "wb");
820#endif
821}
822
823
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000824/* Write a compiled module to a file, placing the time of last
825 modification of its source into the header.
826 Errors are ignored, if a write error occurs an attempt is made to
827 remove the file. */
828
829static void
Martin v. Löwis18e16552006-02-15 17:27:45 +0000830write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000831{
832 FILE *fp;
833
Guido van Rossum55a83382000-09-20 20:31:38 +0000834 fp = open_exclusive(cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000835 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000836 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000837 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000838 "# can't create %s\n", cpathname);
839 return;
840 }
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000841 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000842 /* First write a 0 for mtime */
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000843 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
844 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
Armin Rigo01ab2792004-03-26 15:09:27 +0000845 if (fflush(fp) != 0 || ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000846 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000847 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000848 /* Don't keep partial file */
849 fclose(fp);
850 (void) unlink(cpathname);
851 return;
852 }
853 /* Now write the true mtime */
854 fseek(fp, 4L, 0);
Martin v. Löwis18e16552006-02-15 17:27:45 +0000855 assert(mtime < LONG_MAX);
Martin v. Löwisef82d2f2004-06-27 16:51:46 +0000856 PyMarshal_WriteLongToFile(mtime, fp, Py_MARSHAL_VERSION);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000857 fflush(fp);
858 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000859 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000860 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000861}
862
863
864/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000865 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
866 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000867
Guido van Rossum79f25d91997-04-29 20:08:16 +0000868static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000869load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000870{
Fred Drake4c82b232000-06-30 16:18:57 +0000871 time_t mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000872 FILE *fpc;
873 char buf[MAXPATHLEN+1];
874 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000875 PyCodeObject *co;
876 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000877
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000878 mtime = PyOS_GetLastModificationTime(pathname, fp);
Neal Norwitz708e51a2005-10-03 04:48:15 +0000879 if (mtime == (time_t)(-1)) {
880 PyErr_Format(PyExc_RuntimeError,
881 "unable to get modification time from '%s'",
882 pathname);
Fred Drake4c82b232000-06-30 16:18:57 +0000883 return NULL;
Neal Norwitz708e51a2005-10-03 04:48:15 +0000884 }
Fred Drake4c82b232000-06-30 16:18:57 +0000885#if SIZEOF_TIME_T > 4
886 /* Python's .pyc timestamp handling presumes that the timestamp fits
887 in 4 bytes. This will be fine until sometime in the year 2038,
888 when a 4-byte signed time_t will overflow.
889 */
890 if (mtime >> 32) {
891 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000892 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000893 return NULL;
894 }
895#endif
Tim Peters36515e22001-11-18 04:06:29 +0000896 cpathname = make_compiled_pathname(pathname, buf,
Jeremy Hylton37832f02001-04-13 17:50:20 +0000897 (size_t)MAXPATHLEN + 1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000898 if (cpathname != NULL &&
899 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000900 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000901 fclose(fpc);
902 if (co == NULL)
903 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000904 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000905 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000906 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000907 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000908 }
909 else {
910 co = parse_source_module(pathname, fp);
911 if (co == NULL)
912 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000913 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000914 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000915 name, pathname);
916 write_compiled_module(co, cpathname, mtime);
917 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000918 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000919 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000920
921 return m;
922}
923
924
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000925/* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +0000926static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
927static struct filedescr *find_module(char *, char *, PyObject *,
928 char *, size_t, FILE **, PyObject **);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000929static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000930
931/* Load a package and return its module object WITH INCREMENTED
932 REFERENCE COUNT */
933
934static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000935load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000936{
Tim Peters1cd70172004-08-02 03:52:12 +0000937 PyObject *m, *d;
938 PyObject *file = NULL;
939 PyObject *path = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000940 int err;
941 char buf[MAXPATHLEN+1];
942 FILE *fp = NULL;
943 struct filedescr *fdp;
944
945 m = PyImport_AddModule(name);
946 if (m == NULL)
947 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000948 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000949 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000950 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000951 d = PyModule_GetDict(m);
952 file = PyString_FromString(pathname);
953 if (file == NULL)
Tim Peters1cd70172004-08-02 03:52:12 +0000954 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000955 path = Py_BuildValue("[O]", file);
Tim Peters1cd70172004-08-02 03:52:12 +0000956 if (path == NULL)
957 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000958 err = PyDict_SetItemString(d, "__file__", file);
959 if (err == 0)
960 err = PyDict_SetItemString(d, "__path__", path);
Tim Peters1cd70172004-08-02 03:52:12 +0000961 if (err != 0)
962 goto error;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000963 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +0000964 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000965 if (fdp == NULL) {
966 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
967 PyErr_Clear();
Thomas Heller25653242004-06-07 15:04:10 +0000968 Py_INCREF(m);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000969 }
970 else
971 m = NULL;
972 goto cleanup;
973 }
Just van Rossum52e14d62002-12-30 22:08:05 +0000974 m = load_module(name, fp, buf, fdp->type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000975 if (fp != NULL)
976 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +0000977 goto cleanup;
978
979 error:
980 m = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000981 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000982 Py_XDECREF(path);
983 Py_XDECREF(file);
984 return m;
985}
986
987
988/* Helper to test for built-in module */
989
990static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000991is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000992{
993 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +0000994 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
995 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
996 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000997 return -1;
998 else
999 return 1;
1000 }
1001 }
1002 return 0;
1003}
1004
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001005
Just van Rossum52e14d62002-12-30 22:08:05 +00001006/* Return an importer object for a sys.path/pkg.__path__ item 'p',
1007 possibly by fetching it from the path_importer_cache dict. If it
1008 wasn't yet cached, traverse path_hooks until it a hook is found
1009 that can handle the path item. Return None if no hook could;
1010 this tells our caller it should fall back to the builtin
1011 import mechanism. Cache the result in path_importer_cache.
1012 Returns a borrowed reference. */
1013
1014static PyObject *
1015get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1016 PyObject *p)
1017{
1018 PyObject *importer;
1019 int j, nhooks;
1020
1021 /* These conditions are the caller's responsibility: */
1022 assert(PyList_Check(path_hooks));
1023 assert(PyDict_Check(path_importer_cache));
1024
1025 nhooks = PyList_Size(path_hooks);
1026 if (nhooks < 0)
1027 return NULL; /* Shouldn't happen */
1028
1029 importer = PyDict_GetItem(path_importer_cache, p);
1030 if (importer != NULL)
1031 return importer;
1032
1033 /* set path_importer_cache[p] to None to avoid recursion */
1034 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1035 return NULL;
1036
1037 for (j = 0; j < nhooks; j++) {
1038 PyObject *hook = PyList_GetItem(path_hooks, j);
1039 if (hook == NULL)
1040 return NULL;
1041 importer = PyObject_CallFunction(hook, "O", p);
1042 if (importer != NULL)
1043 break;
1044
1045 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1046 return NULL;
1047 }
1048 PyErr_Clear();
1049 }
1050 if (importer == NULL)
1051 importer = Py_None;
1052 else if (importer != Py_None) {
1053 int err = PyDict_SetItem(path_importer_cache, p, importer);
1054 Py_DECREF(importer);
1055 if (err != 0)
1056 return NULL;
1057 }
1058 return importer;
1059}
1060
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001061/* Search the path (default sys.path) for a module. Return the
1062 corresponding filedescr struct, and (via return arguments) the
1063 pathname and an open file. Return NULL if the module is not found. */
1064
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001065#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +00001066extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001067 char *, Py_ssize_t);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001068#endif
1069
Martin v. Löwis18e16552006-02-15 17:27:45 +00001070static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001071static int find_init_module(char *); /* Forward */
Just van Rossum52e14d62002-12-30 22:08:05 +00001072static struct filedescr importhookdescr = {"", "", IMP_HOOK};
Guido van Rossum197346f1997-10-31 18:38:52 +00001073
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001074static struct filedescr *
Just van Rossum52e14d62002-12-30 22:08:05 +00001075find_module(char *fullname, char *subname, PyObject *path, char *buf,
1076 size_t buflen, FILE **p_fp, PyObject **p_loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001077{
Fred Drake4c82b232000-06-30 16:18:57 +00001078 int i, npath;
1079 size_t len, namelen;
Guido van Rossum80bb9651996-12-05 23:27:02 +00001080 struct filedescr *fdp = NULL;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001081 char *filemode;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001082 FILE *fp = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00001083 PyObject *path_hooks, *path_importer_cache;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001084#ifndef RISCOS
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001085 struct stat statbuf;
Guido van Rossum48a680c2001-03-02 06:34:14 +00001086#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001087 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1088 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1089 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +00001090 char name[MAXPATHLEN+1];
Andrew MacIntyred9400542002-02-26 11:41:34 +00001091#if defined(PYOS_OS2)
1092 size_t saved_len;
1093 size_t saved_namelen;
1094 char *saved_buf = NULL;
1095#endif
Just van Rossum52e14d62002-12-30 22:08:05 +00001096 if (p_loader != NULL)
1097 *p_loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001098
Just van Rossum52e14d62002-12-30 22:08:05 +00001099 if (strlen(subname) > MAXPATHLEN) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001100 PyErr_SetString(PyExc_OverflowError,
1101 "module name is too long");
Fred Drake4c82b232000-06-30 16:18:57 +00001102 return NULL;
1103 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001104 strcpy(name, subname);
1105
1106 /* sys.meta_path import hook */
1107 if (p_loader != NULL) {
1108 PyObject *meta_path;
1109
1110 meta_path = PySys_GetObject("meta_path");
1111 if (meta_path == NULL || !PyList_Check(meta_path)) {
1112 PyErr_SetString(PyExc_ImportError,
1113 "sys.meta_path must be a list of "
1114 "import hooks");
1115 return NULL;
1116 }
1117 Py_INCREF(meta_path); /* zap guard */
1118 npath = PyList_Size(meta_path);
1119 for (i = 0; i < npath; i++) {
1120 PyObject *loader;
1121 PyObject *hook = PyList_GetItem(meta_path, i);
1122 loader = PyObject_CallMethod(hook, "find_module",
1123 "sO", fullname,
1124 path != NULL ?
1125 path : Py_None);
1126 if (loader == NULL) {
1127 Py_DECREF(meta_path);
1128 return NULL; /* true error */
1129 }
1130 if (loader != Py_None) {
1131 /* a loader was found */
1132 *p_loader = loader;
1133 Py_DECREF(meta_path);
1134 return &importhookdescr;
1135 }
1136 Py_DECREF(loader);
1137 }
1138 Py_DECREF(meta_path);
1139 }
Guido van Rossum0506a431998-08-11 15:07:39 +00001140
1141 if (path != NULL && PyString_Check(path)) {
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001142 /* The only type of submodule allowed inside a "frozen"
1143 package are other frozen modules or packages. */
Guido van Rossum0506a431998-08-11 15:07:39 +00001144 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1145 PyErr_SetString(PyExc_ImportError,
1146 "full frozen module name too long");
1147 return NULL;
1148 }
1149 strcpy(buf, PyString_AsString(path));
1150 strcat(buf, ".");
1151 strcat(buf, name);
1152 strcpy(name, buf);
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001153 if (find_frozen(name) != NULL) {
1154 strcpy(buf, name);
1155 return &fd_frozen;
1156 }
1157 PyErr_Format(PyExc_ImportError,
1158 "No frozen submodule named %.200s", name);
1159 return NULL;
Guido van Rossum0506a431998-08-11 15:07:39 +00001160 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001161 if (path == NULL) {
1162 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001163 strcpy(buf, name);
1164 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001165 }
Greg Ward201baee2001-10-04 14:52:06 +00001166 if ((find_frozen(name)) != NULL) {
Guido van Rossuma5568d31998-03-05 03:45:08 +00001167 strcpy(buf, name);
1168 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001169 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001170
Guido van Rossumac279101996-08-22 23:10:58 +00001171#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001172 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1173 if (fp != NULL) {
1174 *p_fp = fp;
1175 return fdp;
1176 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +00001177#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +00001178 path = PySys_GetObject("path");
1179 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001180 if (path == NULL || !PyList_Check(path)) {
1181 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +00001182 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001183 return NULL;
1184 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001185
1186 path_hooks = PySys_GetObject("path_hooks");
1187 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1188 PyErr_SetString(PyExc_ImportError,
1189 "sys.path_hooks must be a list of "
1190 "import hooks");
1191 return NULL;
1192 }
1193 path_importer_cache = PySys_GetObject("path_importer_cache");
1194 if (path_importer_cache == NULL ||
1195 !PyDict_Check(path_importer_cache)) {
1196 PyErr_SetString(PyExc_ImportError,
1197 "sys.path_importer_cache must be a dict");
1198 return NULL;
1199 }
1200
Guido van Rossum79f25d91997-04-29 20:08:16 +00001201 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001202 namelen = strlen(name);
1203 for (i = 0; i < npath; i++) {
Walter Dörwald3430d702002-06-17 10:43:59 +00001204 PyObject *copy = NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001205 PyObject *v = PyList_GetItem(path, i);
Walter Dörwald3430d702002-06-17 10:43:59 +00001206#ifdef Py_USING_UNICODE
1207 if (PyUnicode_Check(v)) {
1208 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1209 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1210 if (copy == NULL)
1211 return NULL;
1212 v = copy;
1213 }
1214 else
1215#endif
Guido van Rossum79f25d91997-04-29 20:08:16 +00001216 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001217 continue;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001218 len = PyString_Size(v);
Walter Dörwald3430d702002-06-17 10:43:59 +00001219 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1220 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001221 continue; /* Too long */
Walter Dörwald3430d702002-06-17 10:43:59 +00001222 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001223 strcpy(buf, PyString_AsString(v));
Walter Dörwald3430d702002-06-17 10:43:59 +00001224 if (strlen(buf) != len) {
1225 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001226 continue; /* v contains '\0' */
Walter Dörwald3430d702002-06-17 10:43:59 +00001227 }
Just van Rossum52e14d62002-12-30 22:08:05 +00001228
1229 /* sys.path_hooks import hook */
1230 if (p_loader != NULL) {
1231 PyObject *importer;
1232
1233 importer = get_path_importer(path_importer_cache,
1234 path_hooks, v);
1235 if (importer == NULL)
1236 return NULL;
1237 /* Note: importer is a borrowed reference */
1238 if (importer != Py_None) {
1239 PyObject *loader;
1240 loader = PyObject_CallMethod(importer,
1241 "find_module",
1242 "s", fullname);
1243 if (loader == NULL)
1244 return NULL; /* error */
1245 if (loader != Py_None) {
1246 /* a loader was found */
1247 *p_loader = loader;
1248 return &importhookdescr;
1249 }
1250 Py_DECREF(loader);
1251 }
1252 /* no hook was successful, use builtin import */
1253 }
1254
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001255 if (len > 0 && buf[len-1] != SEP
1256#ifdef ALTSEP
1257 && buf[len-1] != ALTSEP
1258#endif
1259 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001260 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +00001261 strcpy(buf+len, name);
1262 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +00001263
1264 /* Check for package import (buf holds a directory name,
1265 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001266#ifdef HAVE_STAT
Walter Dörwald3430d702002-06-17 10:43:59 +00001267 if (stat(buf, &statbuf) == 0 && /* it exists */
1268 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1269 find_init_module(buf) && /* it has __init__.py */
1270 case_ok(buf, len, namelen, name)) { /* and case matches */
1271 Py_XDECREF(copy);
Tim Peterscab3f682001-04-29 22:21:25 +00001272 return &fd_package;
Walter Dörwald3430d702002-06-17 10:43:59 +00001273 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001274#else
1275 /* XXX How are you going to test for directories? */
Guido van Rossum48a680c2001-03-02 06:34:14 +00001276#ifdef RISCOS
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001277 if (isdir(buf) &&
1278 find_init_module(buf) &&
Walter Dörwald3430d702002-06-17 10:43:59 +00001279 case_ok(buf, len, namelen, name)) {
1280 Py_XDECREF(copy);
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001281 return &fd_package;
Walter Dörwald3430d702002-06-17 10:43:59 +00001282 }
Guido van Rossum48a680c2001-03-02 06:34:14 +00001283#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001284#endif
Andrew MacIntyred9400542002-02-26 11:41:34 +00001285#if defined(PYOS_OS2)
1286 /* take a snapshot of the module spec for restoration
1287 * after the 8 character DLL hackery
1288 */
1289 saved_buf = strdup(buf);
1290 saved_len = len;
1291 saved_namelen = namelen;
1292#endif /* PYOS_OS2 */
Guido van Rossum79f25d91997-04-29 20:08:16 +00001293 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001294#if defined(PYOS_OS2)
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001295 /* OS/2 limits DLLs to 8 character names (w/o
1296 extension)
Andrew MacIntyred9400542002-02-26 11:41:34 +00001297 * so if the name is longer than that and its a
1298 * dynamically loaded module we're going to try,
1299 * truncate the name before trying
1300 */
Just van Rossum52e14d62002-12-30 22:08:05 +00001301 if (strlen(subname) > 8) {
Andrew MacIntyred9400542002-02-26 11:41:34 +00001302 /* is this an attempt to load a C extension? */
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001303 const struct filedescr *scan;
1304 scan = _PyImport_DynLoadFiletab;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001305 while (scan->suffix != NULL) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001306 if (!strcmp(scan->suffix, fdp->suffix))
Andrew MacIntyred9400542002-02-26 11:41:34 +00001307 break;
1308 else
1309 scan++;
1310 }
1311 if (scan->suffix != NULL) {
1312 /* yes, so truncate the name */
1313 namelen = 8;
Just van Rossum52e14d62002-12-30 22:08:05 +00001314 len -= strlen(subname) - namelen;
Andrew MacIntyred9400542002-02-26 11:41:34 +00001315 buf[len] = '\0';
1316 }
1317 }
1318#endif /* PYOS_OS2 */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001319 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001320 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001321 PySys_WriteStderr("# trying %s\n", buf);
Jack Jansenc88da1f2002-05-28 10:58:19 +00001322 filemode = fdp->mode;
Tim Peters86c7d2f2004-08-01 23:24:21 +00001323 if (filemode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00001324 filemode = "r" PY_STDIOTEXTMODE;
Jack Jansenc88da1f2002-05-28 10:58:19 +00001325 fp = fopen(buf, filemode);
Tim Peters50d8d372001-02-28 05:34:27 +00001326 if (fp != NULL) {
1327 if (case_ok(buf, len, namelen, name))
1328 break;
1329 else { /* continue search */
1330 fclose(fp);
1331 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +00001332 }
Barry Warsaw914a0b12001-02-02 19:12:16 +00001333 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001334#if defined(PYOS_OS2)
1335 /* restore the saved snapshot */
1336 strcpy(buf, saved_buf);
1337 len = saved_len;
1338 namelen = saved_namelen;
1339#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001340 }
Andrew MacIntyred9400542002-02-26 11:41:34 +00001341#if defined(PYOS_OS2)
1342 /* don't need/want the module name snapshot anymore */
1343 if (saved_buf)
1344 {
1345 free(saved_buf);
1346 saved_buf = NULL;
1347 }
1348#endif
Walter Dörwald3430d702002-06-17 10:43:59 +00001349 Py_XDECREF(copy);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001350 if (fp != NULL)
1351 break;
1352 }
1353 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001354 PyErr_Format(PyExc_ImportError,
1355 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001356 return NULL;
1357 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001358 *p_fp = fp;
1359 return fdp;
1360}
1361
Raymond Hettingerdb29e0f2004-10-07 06:46:25 +00001362/* Helpers for main.c
1363 * Find the source file corresponding to a named module
1364 */
1365struct filedescr *
1366_PyImport_FindModule(const char *name, PyObject *path, char *buf,
1367 size_t buflen, FILE **p_fp, PyObject **p_loader)
1368{
1369 return find_module((char *) name, (char *) name, path,
1370 buf, buflen, p_fp, p_loader);
1371}
1372
1373PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1374{
1375 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1376}
1377
Martin v. Löwis18e16552006-02-15 17:27:45 +00001378/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
Tim Petersd1e87a82001-03-01 18:12:00 +00001379 * The arguments here are tricky, best shown by example:
1380 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1381 * ^ ^ ^ ^
1382 * |--------------------- buf ---------------------|
1383 * |------------------- len ------------------|
1384 * |------ name -------|
1385 * |----- namelen -----|
1386 * buf is the full path, but len only counts up to (& exclusive of) the
1387 * extension. name is the module name, also exclusive of extension.
1388 *
1389 * We've already done a successful stat() or fopen() on buf, so know that
1390 * there's some match, possibly case-insensitive.
1391 *
Tim Peters50d8d372001-02-28 05:34:27 +00001392 * case_ok() is to return 1 if there's a case-sensitive match for
1393 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1394 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001395 *
Tim Peters50d8d372001-02-28 05:34:27 +00001396 * case_ok() is used to implement case-sensitive import semantics even
1397 * on platforms with case-insensitive filesystems. It's trivial to implement
1398 * for case-sensitive filesystems. It's pretty much a cross-platform
1399 * nightmare for systems with case-insensitive filesystems.
1400 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001401
Tim Peters50d8d372001-02-28 05:34:27 +00001402/* First we may need a pile of platform-specific header files; the sequence
1403 * of #if's here should match the sequence in the body of case_ok().
1404 */
Jason Tishler7961aa62005-05-20 00:56:54 +00001405#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001406#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001407
Tim Peters50d8d372001-02-28 05:34:27 +00001408#elif defined(DJGPP)
1409#include <dir.h>
1410
Jason Tishler7961aa62005-05-20 00:56:54 +00001411#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001412#include <sys/types.h>
1413#include <dirent.h>
1414
Andrew MacIntyred9400542002-02-26 11:41:34 +00001415#elif defined(PYOS_OS2)
1416#define INCL_DOS
1417#define INCL_DOSERRORS
1418#define INCL_NOPMAPI
1419#include <os2.h>
1420
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001421#elif defined(RISCOS)
1422#include "oslib/osfscontrol.h"
Tim Peters50d8d372001-02-28 05:34:27 +00001423#endif
1424
Guido van Rossum0980bd91998-02-13 17:18:36 +00001425static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001426case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001427{
Tim Peters50d8d372001-02-28 05:34:27 +00001428/* Pick a platform-specific implementation; the sequence of #if's here should
1429 * match the sequence just above.
1430 */
1431
Jason Tishler7961aa62005-05-20 00:56:54 +00001432/* MS_WINDOWS */
1433#if defined(MS_WINDOWS)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001434 WIN32_FIND_DATA data;
1435 HANDLE h;
Tim Peters50d8d372001-02-28 05:34:27 +00001436
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001437 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001438 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001439
Guido van Rossum0980bd91998-02-13 17:18:36 +00001440 h = FindFirstFile(buf, &data);
1441 if (h == INVALID_HANDLE_VALUE) {
1442 PyErr_Format(PyExc_NameError,
1443 "Can't find file for module %.100s\n(filename %.300s)",
1444 name, buf);
1445 return 0;
1446 }
1447 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001448 return strncmp(data.cFileName, name, namelen) == 0;
1449
1450/* DJGPP */
1451#elif defined(DJGPP)
1452 struct ffblk ffblk;
1453 int done;
1454
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001455 if (Py_GETENV("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001456 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001457
1458 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1459 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001460 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001461 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001462 name, buf);
1463 return 0;
1464 }
Tim Peters50d8d372001-02-28 05:34:27 +00001465 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001466
Jason Tishler7961aa62005-05-20 00:56:54 +00001467/* new-fangled macintosh (macosx) or Cygwin */
1468#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001469 DIR *dirp;
1470 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001471 char dirname[MAXPATHLEN + 1];
1472 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001473
Neil Schemenauer7d4bb9f2001-07-23 16:30:27 +00001474 if (Py_GETENV("PYTHONCASEOK") != NULL)
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001475 return 1;
1476
Tim Petersd1e87a82001-03-01 18:12:00 +00001477 /* Copy the dir component into dirname; substitute "." if empty */
1478 if (dirlen <= 0) {
1479 dirname[0] = '.';
1480 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001481 }
1482 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001483 assert(dirlen <= MAXPATHLEN);
1484 memcpy(dirname, buf, dirlen);
1485 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001486 }
1487 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001488 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001489 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001490 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001491 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001492 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001493#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001494 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001495#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001496 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001497#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001498 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001499 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001500 (void)closedir(dirp);
1501 return 1; /* Found */
1502 }
1503 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001504 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001505 }
Tim Peters430f5d42001-03-01 01:30:56 +00001506 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001507
Guido van Rossume2ae77b2001-10-24 20:42:55 +00001508/* RISC OS */
1509#elif defined(RISCOS)
1510 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1511 char buf2[MAXPATHLEN+2];
1512 char *nameWithExt = buf+len-namelen;
1513 int canonlen;
1514 os_error *e;
1515
1516 if (Py_GETENV("PYTHONCASEOK") != NULL)
1517 return 1;
1518
1519 /* workaround:
1520 append wildcard, otherwise case of filename wouldn't be touched */
1521 strcpy(buf2, buf);
1522 strcat(buf2, "*");
1523
1524 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1525 canonlen = MAXPATHLEN+1-canonlen;
1526 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1527 return 0;
1528 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1529 return 1; /* match */
1530
1531 return 0;
1532
Andrew MacIntyred9400542002-02-26 11:41:34 +00001533/* OS/2 */
1534#elif defined(PYOS_OS2)
1535 HDIR hdir = 1;
1536 ULONG srchcnt = 1;
1537 FILEFINDBUF3 ffbuf;
1538 APIRET rc;
1539
1540 if (getenv("PYTHONCASEOK") != NULL)
1541 return 1;
1542
1543 rc = DosFindFirst(buf,
1544 &hdir,
1545 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1546 &ffbuf, sizeof(ffbuf),
1547 &srchcnt,
1548 FIL_STANDARD);
1549 if (rc != NO_ERROR)
1550 return 0;
1551 return strncmp(ffbuf.achName, name, namelen) == 0;
1552
Tim Peters50d8d372001-02-28 05:34:27 +00001553/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1554#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001555 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001556
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001557#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001558}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001559
Guido van Rossum0980bd91998-02-13 17:18:36 +00001560
Guido van Rossum197346f1997-10-31 18:38:52 +00001561#ifdef HAVE_STAT
1562/* Helper to look for __init__.py or __init__.py[co] in potential package */
1563static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001564find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001565{
Tim Peters0f9431f2001-07-05 03:47:53 +00001566 const size_t save_len = strlen(buf);
Fred Drake4c82b232000-06-30 16:18:57 +00001567 size_t i = save_len;
Tim Peters0f9431f2001-07-05 03:47:53 +00001568 char *pname; /* pointer to start of __init__ */
Guido van Rossum197346f1997-10-31 18:38:52 +00001569 struct stat statbuf;
1570
Tim Peters0f9431f2001-07-05 03:47:53 +00001571/* For calling case_ok(buf, len, namelen, name):
1572 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1573 * ^ ^ ^ ^
1574 * |--------------------- buf ---------------------|
1575 * |------------------- len ------------------|
1576 * |------ name -------|
1577 * |----- namelen -----|
1578 */
Guido van Rossum197346f1997-10-31 18:38:52 +00001579 if (save_len + 13 >= MAXPATHLEN)
1580 return 0;
1581 buf[i++] = SEP;
Tim Peters0f9431f2001-07-05 03:47:53 +00001582 pname = buf + i;
1583 strcpy(pname, "__init__.py");
Guido van Rossum197346f1997-10-31 18:38:52 +00001584 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001585 if (case_ok(buf,
1586 save_len + 9, /* len("/__init__") */
1587 8, /* len("__init__") */
1588 pname)) {
1589 buf[save_len] = '\0';
1590 return 1;
1591 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001592 }
Tim Peters0f9431f2001-07-05 03:47:53 +00001593 i += strlen(pname);
1594 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum197346f1997-10-31 18:38:52 +00001595 if (stat(buf, &statbuf) == 0) {
Tim Peters0f9431f2001-07-05 03:47:53 +00001596 if (case_ok(buf,
1597 save_len + 9, /* len("/__init__") */
1598 8, /* len("__init__") */
1599 pname)) {
1600 buf[save_len] = '\0';
1601 return 1;
1602 }
Guido van Rossum197346f1997-10-31 18:38:52 +00001603 }
1604 buf[save_len] = '\0';
1605 return 0;
1606}
Guido van Rossum48a680c2001-03-02 06:34:14 +00001607
1608#else
1609
1610#ifdef RISCOS
1611static int
1612find_init_module(buf)
1613 char *buf;
1614{
1615 int save_len = strlen(buf);
1616 int i = save_len;
1617
1618 if (save_len + 13 >= MAXPATHLEN)
1619 return 0;
1620 buf[i++] = SEP;
1621 strcpy(buf+i, "__init__/py");
1622 if (isfile(buf)) {
1623 buf[save_len] = '\0';
1624 return 1;
1625 }
1626
1627 if (Py_OptimizeFlag)
1628 strcpy(buf+i, "o");
1629 else
1630 strcpy(buf+i, "c");
1631 if (isfile(buf)) {
1632 buf[save_len] = '\0';
1633 return 1;
1634 }
1635 buf[save_len] = '\0';
1636 return 0;
1637}
1638#endif /*RISCOS*/
1639
Guido van Rossum197346f1997-10-31 18:38:52 +00001640#endif /* HAVE_STAT */
1641
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001642
Tim Petersdbd9ba62000-07-09 03:09:57 +00001643static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001644
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001645/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001646 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001647
Guido van Rossum79f25d91997-04-29 20:08:16 +00001648static PyObject *
Just van Rossum52e14d62002-12-30 22:08:05 +00001649load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001650{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001651 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001652 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001653 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001654
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001655 /* First check that there's an open file (if we need one) */
1656 switch (type) {
1657 case PY_SOURCE:
1658 case PY_COMPILED:
1659 if (fp == NULL) {
1660 PyErr_Format(PyExc_ValueError,
1661 "file object required for import (type code %d)",
1662 type);
1663 return NULL;
1664 }
1665 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001666
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001667 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001668
1669 case PY_SOURCE:
1670 m = load_source_module(name, buf, fp);
1671 break;
1672
1673 case PY_COMPILED:
1674 m = load_compiled_module(name, buf, fp);
1675 break;
1676
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001677#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001678 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001679 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001680 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001681#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001682
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001683 case PKG_DIRECTORY:
1684 m = load_package(name, buf);
1685 break;
1686
1687 case C_BUILTIN:
1688 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001689 if (buf != NULL && buf[0] != '\0')
1690 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001691 if (type == C_BUILTIN)
1692 err = init_builtin(name);
1693 else
1694 err = PyImport_ImportFrozenModule(name);
1695 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001696 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001697 if (err == 0) {
1698 PyErr_Format(PyExc_ImportError,
1699 "Purported %s module %.200s not found",
1700 type == C_BUILTIN ?
1701 "builtin" : "frozen",
1702 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001703 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001704 }
1705 modules = PyImport_GetModuleDict();
1706 m = PyDict_GetItemString(modules, name);
1707 if (m == NULL) {
1708 PyErr_Format(
1709 PyExc_ImportError,
1710 "%s module %.200s not properly initialized",
1711 type == C_BUILTIN ?
1712 "builtin" : "frozen",
1713 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001714 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001715 }
1716 Py_INCREF(m);
1717 break;
1718
Just van Rossum52e14d62002-12-30 22:08:05 +00001719 case IMP_HOOK: {
1720 if (loader == NULL) {
1721 PyErr_SetString(PyExc_ImportError,
1722 "import hook without loader");
1723 return NULL;
1724 }
1725 m = PyObject_CallMethod(loader, "load_module", "s", name);
1726 break;
1727 }
1728
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001729 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001730 PyErr_Format(PyExc_ImportError,
1731 "Don't know how to import %.200s (type code %d)",
1732 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001733 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001734
1735 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001736
1737 return m;
1738}
1739
1740
1741/* Initialize a built-in module.
1742 Return 1 for succes, 0 if the module is not found, and -1 with
1743 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001744
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001745static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001746init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001747{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001748 struct _inittab *p;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001749
Greg Ward201baee2001-10-04 14:52:06 +00001750 if (_PyImport_FindExtension(name, name) != NULL)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001751 return 1;
1752
Guido van Rossum771c6c81997-10-31 18:37:24 +00001753 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001754 if (strcmp(name, p->name) == 0) {
1755 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001756 PyErr_Format(PyExc_ImportError,
1757 "Cannot re-init internal module %.200s",
1758 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001759 return -1;
1760 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001761 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001762 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001763 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001764 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001765 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001766 if (_PyImport_FixupExtension(name, name) == NULL)
1767 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001768 return 1;
1769 }
1770 }
1771 return 0;
1772}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001773
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001774
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001775/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001776
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001777static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001778find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001779{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001780 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001781
Guido van Rossum79f25d91997-04-29 20:08:16 +00001782 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001783 if (p->name == NULL)
1784 return NULL;
1785 if (strcmp(p->name, name) == 0)
1786 break;
1787 }
1788 return p;
1789}
1790
Guido van Rossum79f25d91997-04-29 20:08:16 +00001791static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001792get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001793{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001794 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001795 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001796
1797 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001798 PyErr_Format(PyExc_ImportError,
1799 "No such frozen object named %.200s",
1800 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001801 return NULL;
1802 }
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001803 if (p->code == NULL) {
1804 PyErr_Format(PyExc_ImportError,
1805 "Excluded frozen object named %.200s",
1806 name);
1807 return NULL;
1808 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001809 size = p->size;
1810 if (size < 0)
1811 size = -size;
1812 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001813}
1814
1815/* Initialize a frozen module.
1816 Return 1 for succes, 0 if the module is not found, and -1 with
1817 an exception set if the initialization failed.
1818 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001819
1820int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001821PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001822{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001823 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001824 PyObject *co;
1825 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001826 int ispackage;
1827 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001828
1829 if (p == NULL)
1830 return 0;
Guido van Rossum8f4d3312001-10-18 18:54:11 +00001831 if (p->code == NULL) {
1832 PyErr_Format(PyExc_ImportError,
1833 "Excluded frozen object named %.200s",
1834 name);
1835 return -1;
1836 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001837 size = p->size;
1838 ispackage = (size < 0);
1839 if (ispackage)
1840 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001841 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001842 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001843 name, ispackage ? " package" : "");
1844 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001845 if (co == NULL)
1846 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001847 if (!PyCode_Check(co)) {
1848 Py_DECREF(co);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001849 PyErr_Format(PyExc_TypeError,
1850 "frozen object %.200s is not a code object",
1851 name);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001852 return -1;
1853 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001854 if (ispackage) {
1855 /* Set __path__ to the package name */
1856 PyObject *d, *s;
1857 int err;
1858 m = PyImport_AddModule(name);
1859 if (m == NULL)
1860 return -1;
1861 d = PyModule_GetDict(m);
1862 s = PyString_InternFromString(name);
1863 if (s == NULL)
1864 return -1;
1865 err = PyDict_SetItemString(d, "__path__", s);
1866 Py_DECREF(s);
1867 if (err != 0)
1868 return err;
1869 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001870 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum79f25d91997-04-29 20:08:16 +00001871 Py_DECREF(co);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001872 if (m == NULL)
1873 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001874 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001875 return 1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001876}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001877
1878
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001879/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001880 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001881
Guido van Rossum79f25d91997-04-29 20:08:16 +00001882PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +00001883PyImport_ImportModule(const char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001884{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001885 PyObject *pname;
1886 PyObject *result;
1887
1888 pname = PyString_FromString(name);
Neal Norwitza11e4c12003-03-23 14:31:01 +00001889 if (pname == NULL)
1890 return NULL;
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001891 result = PyImport_Import(pname);
1892 Py_DECREF(pname);
1893 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001894}
1895
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001896/* Forward declarations for helper routines */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001897static PyObject *get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001898static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001899 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001900static int mark_miss(char *name);
1901static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001902 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001903static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001904
1905/* The Magnum Opus of dotted-name import :-) */
1906
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001907static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001908import_module_ex(char *name, PyObject *globals, PyObject *locals,
1909 PyObject *fromlist)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001910{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001911 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00001912 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001913 PyObject *parent, *head, *next, *tail;
1914
1915 parent = get_parent(globals, buf, &buflen);
1916 if (parent == NULL)
1917 return NULL;
1918
1919 head = load_next(parent, Py_None, &name, buf, &buflen);
1920 if (head == NULL)
1921 return NULL;
1922
1923 tail = head;
1924 Py_INCREF(tail);
1925 while (name) {
1926 next = load_next(tail, tail, &name, buf, &buflen);
1927 Py_DECREF(tail);
1928 if (next == NULL) {
1929 Py_DECREF(head);
1930 return NULL;
1931 }
1932 tail = next;
1933 }
1934
1935 if (fromlist != NULL) {
1936 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1937 fromlist = NULL;
1938 }
1939
1940 if (fromlist == NULL) {
1941 Py_DECREF(tail);
1942 return head;
1943 }
1944
1945 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001946 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001947 Py_DECREF(tail);
1948 return NULL;
1949 }
1950
1951 return tail;
1952}
1953
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001954PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001955PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1956 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001957{
1958 PyObject *result;
1959 lock_import();
Guido van Rossumd65911b1998-03-03 22:33:27 +00001960 result = import_module_ex(name, globals, locals, fromlist);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00001961 if (unlock_import() < 0) {
1962 Py_XDECREF(result);
1963 PyErr_SetString(PyExc_RuntimeError,
1964 "not holding the import lock");
1965 return NULL;
1966 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001967 return result;
1968}
1969
Fred Drake87590902004-05-28 20:21:36 +00001970/* Return the package that an import is being performed in. If globals comes
1971 from the module foo.bar.bat (not itself a package), this returns the
1972 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
1973 the package's entry in sys.modules is returned.
1974
1975 The *name* of the returned package is returned in buf, with the length of
1976 the name in *p_buflen.
1977
1978 If globals doesn't come from a package or a module in a package, or a
1979 corresponding entry is not found in sys.modules, Py_None is returned.
1980*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001981static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001982get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001983{
1984 static PyObject *namestr = NULL;
1985 static PyObject *pathstr = NULL;
1986 PyObject *modname, *modpath, *modules, *parent;
1987
1988 if (globals == NULL || !PyDict_Check(globals))
1989 return Py_None;
1990
1991 if (namestr == NULL) {
1992 namestr = PyString_InternFromString("__name__");
1993 if (namestr == NULL)
1994 return NULL;
1995 }
1996 if (pathstr == NULL) {
1997 pathstr = PyString_InternFromString("__path__");
1998 if (pathstr == NULL)
1999 return NULL;
2000 }
2001
2002 *buf = '\0';
2003 *p_buflen = 0;
2004 modname = PyDict_GetItem(globals, namestr);
2005 if (modname == NULL || !PyString_Check(modname))
2006 return Py_None;
2007
2008 modpath = PyDict_GetItem(globals, pathstr);
2009 if (modpath != NULL) {
2010 int len = PyString_GET_SIZE(modname);
2011 if (len > MAXPATHLEN) {
2012 PyErr_SetString(PyExc_ValueError,
2013 "Module name too long");
2014 return NULL;
2015 }
2016 strcpy(buf, PyString_AS_STRING(modname));
2017 *p_buflen = len;
2018 }
2019 else {
2020 char *start = PyString_AS_STRING(modname);
2021 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002022 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002023 if (lastdot == NULL)
2024 return Py_None;
2025 len = lastdot - start;
2026 if (len >= MAXPATHLEN) {
2027 PyErr_SetString(PyExc_ValueError,
2028 "Module name too long");
2029 return NULL;
2030 }
2031 strncpy(buf, start, len);
2032 buf[len] = '\0';
2033 *p_buflen = len;
2034 }
2035
2036 modules = PyImport_GetModuleDict();
2037 parent = PyDict_GetItemString(modules, buf);
2038 if (parent == NULL)
2039 parent = Py_None;
2040 return parent;
2041 /* We expect, but can't guarantee, if parent != None, that:
2042 - parent.__name__ == buf
2043 - parent.__dict__ is globals
2044 If this is violated... Who cares? */
2045}
2046
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002047/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002048static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002049load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002050 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002051{
2052 char *name = *p_name;
2053 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002054 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002055 char *p;
2056 PyObject *result;
2057
2058 if (dot == NULL) {
2059 *p_name = NULL;
2060 len = strlen(name);
2061 }
2062 else {
2063 *p_name = dot+1;
2064 len = dot-name;
2065 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002066 if (len == 0) {
2067 PyErr_SetString(PyExc_ValueError,
2068 "Empty module name");
2069 return NULL;
2070 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002071
2072 p = buf + *p_buflen;
2073 if (p != buf)
2074 *p++ = '.';
2075 if (p+len-buf >= MAXPATHLEN) {
2076 PyErr_SetString(PyExc_ValueError,
2077 "Module name too long");
2078 return NULL;
2079 }
2080 strncpy(p, name, len);
2081 p[len] = '\0';
2082 *p_buflen = p+len-buf;
2083
2084 result = import_submodule(mod, p, buf);
2085 if (result == Py_None && altmod != mod) {
2086 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002087 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002088 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002089 if (result != NULL && result != Py_None) {
2090 if (mark_miss(buf) != 0) {
2091 Py_DECREF(result);
2092 return NULL;
2093 }
2094 strncpy(buf, name, len);
2095 buf[len] = '\0';
2096 *p_buflen = len;
2097 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002098 }
2099 if (result == NULL)
2100 return NULL;
2101
2102 if (result == Py_None) {
2103 Py_DECREF(result);
2104 PyErr_Format(PyExc_ImportError,
2105 "No module named %.200s", name);
2106 return NULL;
2107 }
2108
2109 return result;
2110}
2111
2112static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002113mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002114{
2115 PyObject *modules = PyImport_GetModuleDict();
2116 return PyDict_SetItemString(modules, name, Py_None);
2117}
2118
2119static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002120ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002121 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002122{
2123 int i;
2124
2125 if (!PyObject_HasAttrString(mod, "__path__"))
2126 return 1;
2127
2128 for (i = 0; ; i++) {
2129 PyObject *item = PySequence_GetItem(fromlist, i);
2130 int hasit;
2131 if (item == NULL) {
2132 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2133 PyErr_Clear();
2134 return 1;
2135 }
2136 return 0;
2137 }
2138 if (!PyString_Check(item)) {
2139 PyErr_SetString(PyExc_TypeError,
2140 "Item in ``from list'' not a string");
2141 Py_DECREF(item);
2142 return 0;
2143 }
2144 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002145 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002146 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002147 /* See if the package defines __all__ */
2148 if (recursive)
2149 continue; /* Avoid endless recursion */
2150 all = PyObject_GetAttrString(mod, "__all__");
2151 if (all == NULL)
2152 PyErr_Clear();
2153 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002154 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002155 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002156 if (!ret)
2157 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002158 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002159 continue;
2160 }
2161 hasit = PyObject_HasAttr(mod, item);
2162 if (!hasit) {
2163 char *subname = PyString_AS_STRING(item);
2164 PyObject *submod;
2165 char *p;
2166 if (buflen + strlen(subname) >= MAXPATHLEN) {
2167 PyErr_SetString(PyExc_ValueError,
2168 "Module name too long");
2169 Py_DECREF(item);
2170 return 0;
2171 }
2172 p = buf + buflen;
2173 *p++ = '.';
2174 strcpy(p, subname);
2175 submod = import_submodule(mod, subname, buf);
2176 Py_XDECREF(submod);
2177 if (submod == NULL) {
2178 Py_DECREF(item);
2179 return 0;
2180 }
2181 }
2182 Py_DECREF(item);
2183 }
2184
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002185 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002186}
2187
Neil Schemenauer00b09662003-06-16 21:03:07 +00002188static int
2189add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2190 PyObject *modules)
2191{
2192 if (mod == Py_None)
2193 return 1;
2194 /* Irrespective of the success of this load, make a
2195 reference to it in the parent package module. A copy gets
2196 saved in the modules dictionary under the full name, so get a
2197 reference from there, if need be. (The exception is when the
2198 load failed with a SyntaxError -- then there's no trace in
2199 sys.modules. In that case, of course, do nothing extra.) */
2200 if (submod == NULL) {
2201 submod = PyDict_GetItemString(modules, fullname);
2202 if (submod == NULL)
2203 return 1;
2204 }
2205 if (PyModule_Check(mod)) {
2206 /* We can't use setattr here since it can give a
2207 * spurious warning if the submodule name shadows a
2208 * builtin name */
2209 PyObject *dict = PyModule_GetDict(mod);
2210 if (!dict)
2211 return 0;
2212 if (PyDict_SetItemString(dict, subname, submod) < 0)
2213 return 0;
2214 }
2215 else {
2216 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2217 return 0;
2218 }
2219 return 1;
2220}
2221
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002222static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002223import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002224{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002225 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002226 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002227
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002228 /* Require:
2229 if mod == None: subname == fullname
2230 else: mod.__name__ + "." + subname == fullname
2231 */
2232
Tim Peters50d8d372001-02-28 05:34:27 +00002233 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002234 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002235 }
2236 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002237 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002238 char buf[MAXPATHLEN+1];
2239 struct filedescr *fdp;
2240 FILE *fp = NULL;
2241
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002242 if (mod == Py_None)
2243 path = NULL;
2244 else {
2245 path = PyObject_GetAttrString(mod, "__path__");
2246 if (path == NULL) {
2247 PyErr_Clear();
2248 Py_INCREF(Py_None);
2249 return Py_None;
2250 }
2251 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002252
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002253 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002254 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2255 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002256 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002257 if (fdp == NULL) {
2258 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2259 return NULL;
2260 PyErr_Clear();
2261 Py_INCREF(Py_None);
2262 return Py_None;
2263 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002264 m = load_module(fullname, fp, buf, fdp->type, loader);
2265 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002266 if (fp)
2267 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002268 if (!add_submodule(mod, m, fullname, subname, modules)) {
2269 Py_XDECREF(m);
2270 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002271 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002272 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002273
2274 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002275}
2276
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002277
2278/* Re-import a module of any kind and return its module object, WITH
2279 INCREMENTED REFERENCE COUNT */
2280
Guido van Rossum79f25d91997-04-29 20:08:16 +00002281PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002282PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002283{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002284 PyObject *modules = PyImport_GetModuleDict();
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002285 PyObject *path = NULL, *loader = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002286 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002287 char buf[MAXPATHLEN+1];
2288 struct filedescr *fdp;
2289 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002290 PyObject *newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002291
Guido van Rossum79f25d91997-04-29 20:08:16 +00002292 if (m == NULL || !PyModule_Check(m)) {
2293 PyErr_SetString(PyExc_TypeError,
2294 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002295 return NULL;
2296 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002297 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002298 if (name == NULL)
2299 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002300 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002301 PyErr_Format(PyExc_ImportError,
2302 "reload(): module %.200s not in sys.modules",
2303 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002304 return NULL;
2305 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002306 subname = strrchr(name, '.');
2307 if (subname == NULL)
2308 subname = name;
2309 else {
2310 PyObject *parentname, *parent;
2311 parentname = PyString_FromStringAndSize(name, (subname-name));
2312 if (parentname == NULL)
2313 return NULL;
2314 parent = PyDict_GetItem(modules, parentname);
2315 if (parent == NULL) {
2316 PyErr_Format(PyExc_ImportError,
2317 "reload(): parent %.200s not in sys.modules",
Georg Brandl0c55f292005-09-14 06:56:20 +00002318 PyString_AS_STRING(parentname));
2319 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002320 return NULL;
2321 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002322 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002323 subname++;
2324 path = PyObject_GetAttrString(parent, "__path__");
2325 if (path == NULL)
2326 PyErr_Clear();
2327 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002328 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002329 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002330 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002331
2332 if (fdp == NULL) {
2333 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002334 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002335 }
2336
2337 newm = load_module(name, fp, buf, fdp->type, loader);
2338 Py_XDECREF(loader);
2339
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002340 if (fp)
2341 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002342 if (newm == NULL) {
2343 /* load_module probably removed name from modules because of
2344 * the error. Put back the original module object. We're
2345 * going to return NULL in this case regardless of whether
2346 * replacing name succeeds, so the return value is ignored.
2347 */
2348 PyDict_SetItemString(modules, name, m);
2349 }
2350 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002351}
2352
2353
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002354/* Higher-level import emulator which emulates the "import" statement
2355 more accurately -- it invokes the __import__() function from the
2356 builtins of the current globals. This means that the import is
2357 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002358 environment, e.g. by "rexec".
2359 A dummy list ["__doc__"] is passed as the 4th argument so that
2360 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2361 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002362
2363PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002364PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002365{
2366 static PyObject *silly_list = NULL;
2367 static PyObject *builtins_str = NULL;
2368 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002369 PyObject *globals = NULL;
2370 PyObject *import = NULL;
2371 PyObject *builtins = NULL;
2372 PyObject *r = NULL;
2373
2374 /* Initialize constant string objects */
2375 if (silly_list == NULL) {
2376 import_str = PyString_InternFromString("__import__");
2377 if (import_str == NULL)
2378 return NULL;
2379 builtins_str = PyString_InternFromString("__builtins__");
2380 if (builtins_str == NULL)
2381 return NULL;
2382 silly_list = Py_BuildValue("[s]", "__doc__");
2383 if (silly_list == NULL)
2384 return NULL;
2385 }
2386
2387 /* Get the builtins from current globals */
2388 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002389 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002390 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002391 builtins = PyObject_GetItem(globals, builtins_str);
2392 if (builtins == NULL)
2393 goto err;
2394 }
2395 else {
2396 /* No globals -- use standard builtins, and fake globals */
2397 PyErr_Clear();
2398
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002399 builtins = PyImport_ImportModuleEx("__builtin__",
2400 NULL, NULL, NULL);
2401 if (builtins == NULL)
2402 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002403 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2404 if (globals == NULL)
2405 goto err;
2406 }
2407
2408 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002409 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002410 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002411 if (import == NULL)
2412 PyErr_SetObject(PyExc_KeyError, import_str);
2413 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002414 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002415 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002416 if (import == NULL)
2417 goto err;
2418
2419 /* Call the _import__ function with the proper argument list */
2420 r = PyObject_CallFunction(import, "OOOO",
2421 module_name, globals, globals, silly_list);
2422
2423 err:
2424 Py_XDECREF(globals);
2425 Py_XDECREF(builtins);
2426 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002427
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002428 return r;
2429}
2430
2431
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002432/* Module 'imp' provides Python access to the primitives used for
2433 importing modules.
2434*/
2435
Guido van Rossum79f25d91997-04-29 20:08:16 +00002436static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002437imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002438{
2439 char buf[4];
2440
Guido van Rossum96774c12000-05-01 20:19:08 +00002441 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2442 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2443 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2444 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002445
Guido van Rossum79f25d91997-04-29 20:08:16 +00002446 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002447}
2448
Guido van Rossum79f25d91997-04-29 20:08:16 +00002449static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002450imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002451{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002452 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002453 struct filedescr *fdp;
2454
Guido van Rossum79f25d91997-04-29 20:08:16 +00002455 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002456 if (list == NULL)
2457 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002458 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2459 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002460 fdp->suffix, fdp->mode, fdp->type);
2461 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002462 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002463 return NULL;
2464 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002465 if (PyList_Append(list, item) < 0) {
2466 Py_DECREF(list);
2467 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002468 return NULL;
2469 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002470 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002471 }
2472 return list;
2473}
2474
Guido van Rossum79f25d91997-04-29 20:08:16 +00002475static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002476call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002477{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002478 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002479 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002480 struct filedescr *fdp;
2481 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002482 FILE *fp = NULL;
2483
2484 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002485 if (path == Py_None)
2486 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002487 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002488 if (fdp == NULL)
2489 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002490 if (fp != NULL) {
2491 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2492 if (fob == NULL) {
2493 fclose(fp);
2494 return NULL;
2495 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002496 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002497 else {
2498 fob = Py_None;
2499 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002500 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002501 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002502 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002503 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002504 return ret;
2505}
2506
Guido van Rossum79f25d91997-04-29 20:08:16 +00002507static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002508imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002509{
2510 char *name;
2511 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002512 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002513 return NULL;
2514 return call_find_module(name, path);
2515}
2516
2517static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002518imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002519{
2520 char *name;
2521 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002522 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002523 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002524 return NULL;
2525 ret = init_builtin(name);
2526 if (ret < 0)
2527 return NULL;
2528 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002529 Py_INCREF(Py_None);
2530 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002531 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002532 m = PyImport_AddModule(name);
2533 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002534 return m;
2535}
2536
Guido van Rossum79f25d91997-04-29 20:08:16 +00002537static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002538imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002539{
2540 char *name;
2541 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002542 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002543 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002544 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002545 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002546 if (ret < 0)
2547 return NULL;
2548 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002549 Py_INCREF(Py_None);
2550 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002551 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002552 m = PyImport_AddModule(name);
2553 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002554 return m;
2555}
2556
Guido van Rossum79f25d91997-04-29 20:08:16 +00002557static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002558imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002559{
2560 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002561
Guido van Rossum43713e52000-02-29 13:59:29 +00002562 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002563 return NULL;
2564 return get_frozen_object(name);
2565}
2566
Guido van Rossum79f25d91997-04-29 20:08:16 +00002567static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002568imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002569{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002570 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002571 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002572 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002573 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002574}
2575
Guido van Rossum79f25d91997-04-29 20:08:16 +00002576static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002577imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002578{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002579 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002580 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002581 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002582 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002583 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002584 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002585}
2586
2587static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002588get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002589{
2590 FILE *fp;
2591 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002592 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002593 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002594 fp = fopen(pathname, mode);
2595 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002596 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002597 }
2598 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002599 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002600 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002601 PyErr_SetString(PyExc_ValueError,
2602 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002603 }
2604 return fp;
2605}
2606
Guido van Rossum79f25d91997-04-29 20:08:16 +00002607static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002608imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002609{
2610 char *name;
2611 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002612 PyObject *fob = NULL;
2613 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002614 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002615 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002616 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002617 return NULL;
2618 fp = get_file(pathname, fob, "rb");
2619 if (fp == NULL)
2620 return NULL;
2621 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002622 if (fob == NULL)
2623 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002624 return m;
2625}
2626
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002627#ifdef HAVE_DYNAMIC_LOADING
2628
Guido van Rossum79f25d91997-04-29 20:08:16 +00002629static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002630imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002631{
2632 char *name;
2633 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002634 PyObject *fob = NULL;
2635 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002636 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002637 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002638 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002639 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002640 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002641 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002642 if (fp == NULL)
2643 return NULL;
2644 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002645 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002646 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002647}
2648
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002649#endif /* HAVE_DYNAMIC_LOADING */
2650
Guido van Rossum79f25d91997-04-29 20:08:16 +00002651static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002652imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002653{
2654 char *name;
2655 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002656 PyObject *fob = NULL;
2657 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002658 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002659 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002660 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002661 return NULL;
2662 fp = get_file(pathname, fob, "r");
2663 if (fp == NULL)
2664 return NULL;
2665 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002666 if (fob == NULL)
2667 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002668 return m;
2669}
2670
Guido van Rossum79f25d91997-04-29 20:08:16 +00002671static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002672imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002673{
2674 char *name;
2675 PyObject *fob;
2676 char *pathname;
2677 char *suffix; /* Unused */
2678 char *mode;
2679 int type;
2680 FILE *fp;
2681
Guido van Rossum43713e52000-02-29 13:59:29 +00002682 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002683 &name, &fob, &pathname,
2684 &suffix, &mode, &type))
2685 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002686 if (*mode) {
2687 /* Mode must start with 'r' or 'U' and must not contain '+'.
2688 Implicit in this test is the assumption that the mode
2689 may contain other modifiers like 'b' or 't'. */
2690
2691 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002692 PyErr_Format(PyExc_ValueError,
2693 "invalid file open mode %.200s", mode);
2694 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002695 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002696 }
2697 if (fob == Py_None)
2698 fp = NULL;
2699 else {
2700 if (!PyFile_Check(fob)) {
2701 PyErr_SetString(PyExc_ValueError,
2702 "load_module arg#2 should be a file or None");
2703 return NULL;
2704 }
2705 fp = get_file(pathname, fob, mode);
2706 if (fp == NULL)
2707 return NULL;
2708 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002709 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002710}
2711
2712static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002713imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002714{
2715 char *name;
2716 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002717 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002718 return NULL;
2719 return load_package(name, pathname);
2720}
2721
2722static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002723imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002724{
2725 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002726 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002727 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002728 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002729}
2730
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002731/* Doc strings */
2732
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002733PyDoc_STRVAR(doc_imp,
2734"This module provides the components needed to build your own\n\
2735__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002736
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002737PyDoc_STRVAR(doc_find_module,
2738"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002739Search for a module. If path is omitted or None, search for a\n\
2740built-in, frozen or special module and continue search in sys.path.\n\
2741The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002742package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002744PyDoc_STRVAR(doc_load_module,
2745"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002746Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002747The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002748
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002749PyDoc_STRVAR(doc_get_magic,
2750"get_magic() -> string\n\
2751Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002752
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002753PyDoc_STRVAR(doc_get_suffixes,
2754"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002755Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002756that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002758PyDoc_STRVAR(doc_new_module,
2759"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002760Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002761The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002762
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002763PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002764"lock_held() -> boolean\n\
2765Return True if the import lock is currently held, else False.\n\
2766On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002767
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002768PyDoc_STRVAR(doc_acquire_lock,
2769"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002770Acquires the interpreter's import lock for the current thread.\n\
2771This lock should be used by import hooks to ensure thread-safety\n\
2772when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002773On platforms without threads, this function does nothing.");
2774
2775PyDoc_STRVAR(doc_release_lock,
2776"release_lock() -> None\n\
2777Release the interpreter's import lock.\n\
2778On platforms without threads, this function does nothing.");
2779
Guido van Rossum79f25d91997-04-29 20:08:16 +00002780static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002781 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2782 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2783 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2784 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2785 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2786 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2787 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2788 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002789 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00002790 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2791 {"init_builtin", imp_init_builtin, METH_VARARGS},
2792 {"init_frozen", imp_init_frozen, METH_VARARGS},
2793 {"is_builtin", imp_is_builtin, METH_VARARGS},
2794 {"is_frozen", imp_is_frozen, METH_VARARGS},
2795 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002796#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00002797 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002798#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002799 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00002800 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002801 {NULL, NULL} /* sentinel */
2802};
2803
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002804static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002805setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002806{
2807 PyObject *v;
2808 int err;
2809
2810 v = PyInt_FromLong((long)value);
2811 err = PyDict_SetItemString(d, name, v);
2812 Py_XDECREF(v);
2813 return err;
2814}
2815
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002816PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002817initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002818{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002819 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002820
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002821 m = Py_InitModule4("imp", imp_methods, doc_imp,
2822 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00002823 if (m == NULL)
2824 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002825 d = PyModule_GetDict(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002826
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002827 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2828 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2829 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2830 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2831 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2832 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2833 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2834 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00002835 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00002836 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002837
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002838 failure:
2839 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002840}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002841
2842
Guido van Rossumb18618d2000-05-03 23:44:39 +00002843/* API for embedding applications that want to add their own entries
2844 to the table of built-in modules. This should normally be called
2845 *before* Py_Initialize(). When the table resize fails, -1 is
2846 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002847
2848 After a similar function by Just van Rossum. */
2849
2850int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002851PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002852{
2853 static struct _inittab *our_copy = NULL;
2854 struct _inittab *p;
2855 int i, n;
2856
2857 /* Count the number of entries in both tables */
2858 for (n = 0; newtab[n].name != NULL; n++)
2859 ;
2860 if (n == 0)
2861 return 0; /* Nothing to do */
2862 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2863 ;
2864
2865 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00002866 p = our_copy;
2867 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002868 if (p == NULL)
2869 return -1;
2870
2871 /* Copy the tables into the new memory */
2872 if (our_copy != PyImport_Inittab)
2873 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2874 PyImport_Inittab = our_copy = p;
2875 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2876
2877 return 0;
2878}
2879
2880/* Shorthand to add a single entry given a name and a function */
2881
2882int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002883PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002884{
2885 struct _inittab newtab[2];
2886
2887 memset(newtab, '\0', sizeof newtab);
2888
2889 newtab[0].name = name;
2890 newtab[0].initfunc = initfunc;
2891
2892 return PyImport_ExtendInittab(newtab);
2893}