blob: 4aeeb3a8b7fa8d570fff1c1f286a52c60d6bb60d [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*/
Thomas Woutersf7f438b2006-02-28 16:09:29 +000060#define MAGIC (62092 | ((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 */
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001897static PyObject *get_parent(PyObject *globals, char *buf,
1898 Py_ssize_t *p_buflen, int level);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001899static PyObject *load_next(PyObject *mod, PyObject *altmod,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001900 char **p_name, char *buf, Py_ssize_t *p_buflen);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001901static int mark_miss(char *name);
1902static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
Martin v. Löwis18e16552006-02-15 17:27:45 +00001903 char *buf, Py_ssize_t buflen, int recursive);
Tim Petersdbd9ba62000-07-09 03:09:57 +00001904static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001905
1906/* The Magnum Opus of dotted-name import :-) */
1907
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001908static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001909import_module_level(char *name, PyObject *globals, PyObject *locals,
1910 PyObject *fromlist, int level)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001911{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001912 char buf[MAXPATHLEN+1];
Martin v. Löwis18e16552006-02-15 17:27:45 +00001913 Py_ssize_t buflen = 0;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001914 PyObject *parent, *head, *next, *tail;
1915
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001916 parent = get_parent(globals, buf, &buflen, level);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001917 if (parent == NULL)
1918 return NULL;
1919
1920 head = load_next(parent, Py_None, &name, buf, &buflen);
1921 if (head == NULL)
1922 return NULL;
1923
1924 tail = head;
1925 Py_INCREF(tail);
1926 while (name) {
1927 next = load_next(tail, tail, &name, buf, &buflen);
1928 Py_DECREF(tail);
1929 if (next == NULL) {
1930 Py_DECREF(head);
1931 return NULL;
1932 }
1933 tail = next;
1934 }
1935
1936 if (fromlist != NULL) {
1937 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1938 fromlist = NULL;
1939 }
1940
1941 if (fromlist == NULL) {
1942 Py_DECREF(tail);
1943 return head;
1944 }
1945
1946 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001947 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001948 Py_DECREF(tail);
1949 return NULL;
1950 }
1951
1952 return tail;
1953}
1954
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001955/* For DLL compatibility */
1956#undef PyImport_ImportModuleEx
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001957PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001958PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1959 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001960{
1961 PyObject *result;
1962 lock_import();
Thomas Woutersf7f438b2006-02-28 16:09:29 +00001963 result = import_module_level(name, globals, locals, fromlist, -1);
1964 if (unlock_import() < 0) {
1965 Py_XDECREF(result);
1966 PyErr_SetString(PyExc_RuntimeError,
1967 "not holding the import lock");
1968 return NULL;
1969 }
1970 return result;
1971}
1972#define PyImport_ImportModuleEx(n, g, l, f) \
1973 PyImport_ImportModuleLevel(n, g, l, f, -1);
1974
1975PyObject *
1976PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
1977 PyObject *fromlist, int level)
1978{
1979 PyObject *result;
1980 lock_import();
1981 result = import_module_level(name, globals, locals, fromlist, level);
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00001982 if (unlock_import() < 0) {
1983 Py_XDECREF(result);
1984 PyErr_SetString(PyExc_RuntimeError,
1985 "not holding the import lock");
1986 return NULL;
1987 }
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001988 return result;
1989}
1990
Fred Drake87590902004-05-28 20:21:36 +00001991/* Return the package that an import is being performed in. If globals comes
1992 from the module foo.bar.bat (not itself a package), this returns the
1993 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
1994 the package's entry in sys.modules is returned.
1995
1996 The *name* of the returned package is returned in buf, with the length of
1997 the name in *p_buflen.
1998
1999 If globals doesn't come from a package or a module in a package, or a
2000 corresponding entry is not found in sys.modules, Py_None is returned.
2001*/
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002002static PyObject *
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002003get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002004{
2005 static PyObject *namestr = NULL;
2006 static PyObject *pathstr = NULL;
2007 PyObject *modname, *modpath, *modules, *parent;
2008
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002009 if (globals == NULL || !PyDict_Check(globals) || !level)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002010 return Py_None;
2011
2012 if (namestr == NULL) {
2013 namestr = PyString_InternFromString("__name__");
2014 if (namestr == NULL)
2015 return NULL;
2016 }
2017 if (pathstr == NULL) {
2018 pathstr = PyString_InternFromString("__path__");
2019 if (pathstr == NULL)
2020 return NULL;
2021 }
2022
2023 *buf = '\0';
2024 *p_buflen = 0;
2025 modname = PyDict_GetItem(globals, namestr);
2026 if (modname == NULL || !PyString_Check(modname))
2027 return Py_None;
2028
2029 modpath = PyDict_GetItem(globals, pathstr);
2030 if (modpath != NULL) {
2031 int len = PyString_GET_SIZE(modname);
2032 if (len > MAXPATHLEN) {
2033 PyErr_SetString(PyExc_ValueError,
2034 "Module name too long");
2035 return NULL;
2036 }
2037 strcpy(buf, PyString_AS_STRING(modname));
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002038 }
2039 else {
2040 char *start = PyString_AS_STRING(modname);
2041 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002042 size_t len;
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002043 if (lastdot == NULL && level > 0) {
2044 PyErr_SetString(PyExc_ValueError,
2045 "Relative importpath too deep");
2046 return NULL;
2047 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002048 if (lastdot == NULL)
2049 return Py_None;
2050 len = lastdot - start;
2051 if (len >= MAXPATHLEN) {
2052 PyErr_SetString(PyExc_ValueError,
2053 "Module name too long");
2054 return NULL;
2055 }
2056 strncpy(buf, start, len);
2057 buf[len] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002058 }
2059
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002060 while (--level > 0) {
2061 char *dot = strrchr(buf, '.');
2062 if (dot == NULL) {
2063 PyErr_SetString(PyExc_ValueError,
2064 "Relative importpath too deep");
2065 return NULL;
2066 }
2067 *dot = '\0';
2068 }
2069 *p_buflen = strlen(buf);
2070
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002071 modules = PyImport_GetModuleDict();
2072 parent = PyDict_GetItemString(modules, buf);
2073 if (parent == NULL)
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002074 PyErr_Format(PyExc_SystemError,
2075 "Parent module '%.200s' not loaded", buf);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002076 return parent;
2077 /* We expect, but can't guarantee, if parent != None, that:
2078 - parent.__name__ == buf
2079 - parent.__dict__ is globals
2080 If this is violated... Who cares? */
2081}
2082
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002083/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002084static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002085load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
Martin v. Löwis18e16552006-02-15 17:27:45 +00002086 Py_ssize_t *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002087{
2088 char *name = *p_name;
2089 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00002090 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002091 char *p;
2092 PyObject *result;
2093
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002094 if (strlen(name) == 0) {
2095 /* empty module name only happens in 'from . import' */
2096 Py_INCREF(mod);
2097 *p_name = NULL;
2098 return mod;
2099 }
2100
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002101 if (dot == NULL) {
2102 *p_name = NULL;
2103 len = strlen(name);
2104 }
2105 else {
2106 *p_name = dot+1;
2107 len = dot-name;
2108 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00002109 if (len == 0) {
2110 PyErr_SetString(PyExc_ValueError,
2111 "Empty module name");
2112 return NULL;
2113 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002114
2115 p = buf + *p_buflen;
2116 if (p != buf)
2117 *p++ = '.';
2118 if (p+len-buf >= MAXPATHLEN) {
2119 PyErr_SetString(PyExc_ValueError,
2120 "Module name too long");
2121 return NULL;
2122 }
2123 strncpy(p, name, len);
2124 p[len] = '\0';
2125 *p_buflen = p+len-buf;
2126
2127 result = import_submodule(mod, p, buf);
2128 if (result == Py_None && altmod != mod) {
2129 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002130 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00002131 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002132 if (result != NULL && result != Py_None) {
2133 if (mark_miss(buf) != 0) {
2134 Py_DECREF(result);
2135 return NULL;
2136 }
2137 strncpy(buf, name, len);
2138 buf[len] = '\0';
2139 *p_buflen = len;
2140 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002141 }
2142 if (result == NULL)
2143 return NULL;
2144
2145 if (result == Py_None) {
2146 Py_DECREF(result);
2147 PyErr_Format(PyExc_ImportError,
2148 "No module named %.200s", name);
2149 return NULL;
2150 }
2151
2152 return result;
2153}
2154
2155static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002156mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00002157{
2158 PyObject *modules = PyImport_GetModuleDict();
2159 return PyDict_SetItemString(modules, name, Py_None);
2160}
2161
2162static int
Martin v. Löwis18e16552006-02-15 17:27:45 +00002163ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002164 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002165{
2166 int i;
2167
2168 if (!PyObject_HasAttrString(mod, "__path__"))
2169 return 1;
2170
2171 for (i = 0; ; i++) {
2172 PyObject *item = PySequence_GetItem(fromlist, i);
2173 int hasit;
2174 if (item == NULL) {
2175 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2176 PyErr_Clear();
2177 return 1;
2178 }
2179 return 0;
2180 }
2181 if (!PyString_Check(item)) {
2182 PyErr_SetString(PyExc_TypeError,
2183 "Item in ``from list'' not a string");
2184 Py_DECREF(item);
2185 return 0;
2186 }
2187 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00002188 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002189 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002190 /* See if the package defines __all__ */
2191 if (recursive)
2192 continue; /* Avoid endless recursion */
2193 all = PyObject_GetAttrString(mod, "__all__");
2194 if (all == NULL)
2195 PyErr_Clear();
2196 else {
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002197 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
Guido van Rossum9905ef91997-09-08 16:07:11 +00002198 Py_DECREF(all);
Martin v. Löwis83969ee2004-03-23 16:28:13 +00002199 if (!ret)
2200 return 0;
Guido van Rossum9905ef91997-09-08 16:07:11 +00002201 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002202 continue;
2203 }
2204 hasit = PyObject_HasAttr(mod, item);
2205 if (!hasit) {
2206 char *subname = PyString_AS_STRING(item);
2207 PyObject *submod;
2208 char *p;
2209 if (buflen + strlen(subname) >= MAXPATHLEN) {
2210 PyErr_SetString(PyExc_ValueError,
2211 "Module name too long");
2212 Py_DECREF(item);
2213 return 0;
2214 }
2215 p = buf + buflen;
2216 *p++ = '.';
2217 strcpy(p, subname);
2218 submod = import_submodule(mod, subname, buf);
2219 Py_XDECREF(submod);
2220 if (submod == NULL) {
2221 Py_DECREF(item);
2222 return 0;
2223 }
2224 }
2225 Py_DECREF(item);
2226 }
2227
Guido van Rossuma7f2e811997-10-03 15:33:32 +00002228 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002229}
2230
Neil Schemenauer00b09662003-06-16 21:03:07 +00002231static int
2232add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2233 PyObject *modules)
2234{
2235 if (mod == Py_None)
2236 return 1;
2237 /* Irrespective of the success of this load, make a
2238 reference to it in the parent package module. A copy gets
2239 saved in the modules dictionary under the full name, so get a
2240 reference from there, if need be. (The exception is when the
2241 load failed with a SyntaxError -- then there's no trace in
2242 sys.modules. In that case, of course, do nothing extra.) */
2243 if (submod == NULL) {
2244 submod = PyDict_GetItemString(modules, fullname);
2245 if (submod == NULL)
2246 return 1;
2247 }
2248 if (PyModule_Check(mod)) {
2249 /* We can't use setattr here since it can give a
2250 * spurious warning if the submodule name shadows a
2251 * builtin name */
2252 PyObject *dict = PyModule_GetDict(mod);
2253 if (!dict)
2254 return 0;
2255 if (PyDict_SetItemString(dict, subname, submod) < 0)
2256 return 0;
2257 }
2258 else {
2259 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2260 return 0;
2261 }
2262 return 1;
2263}
2264
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002265static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002266import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002267{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002268 PyObject *modules = PyImport_GetModuleDict();
Neil Schemenauer00b09662003-06-16 21:03:07 +00002269 PyObject *m = NULL;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002270
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002271 /* Require:
2272 if mod == None: subname == fullname
2273 else: mod.__name__ + "." + subname == fullname
2274 */
2275
Tim Peters50d8d372001-02-28 05:34:27 +00002276 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002277 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00002278 }
2279 else {
Just van Rossum52e14d62002-12-30 22:08:05 +00002280 PyObject *path, *loader = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002281 char buf[MAXPATHLEN+1];
2282 struct filedescr *fdp;
2283 FILE *fp = NULL;
2284
Guido van Rossum9c0afe51998-05-19 15:09:05 +00002285 if (mod == Py_None)
2286 path = NULL;
2287 else {
2288 path = PyObject_GetAttrString(mod, "__path__");
2289 if (path == NULL) {
2290 PyErr_Clear();
2291 Py_INCREF(Py_None);
2292 return Py_None;
2293 }
2294 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002295
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002296 buf[0] = '\0';
Just van Rossum52e14d62002-12-30 22:08:05 +00002297 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2298 &fp, &loader);
Guido van Rossumb68cd421998-07-01 17:36:26 +00002299 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002300 if (fdp == NULL) {
2301 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2302 return NULL;
2303 PyErr_Clear();
2304 Py_INCREF(Py_None);
2305 return Py_None;
2306 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002307 m = load_module(fullname, fp, buf, fdp->type, loader);
2308 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002309 if (fp)
2310 fclose(fp);
Neil Schemenauer00b09662003-06-16 21:03:07 +00002311 if (!add_submodule(mod, m, fullname, subname, modules)) {
2312 Py_XDECREF(m);
2313 m = NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002314 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00002315 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002316
2317 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00002318}
2319
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002320
2321/* Re-import a module of any kind and return its module object, WITH
2322 INCREMENTED REFERENCE COUNT */
2323
Guido van Rossum79f25d91997-04-29 20:08:16 +00002324PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002325PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002326{
Guido van Rossum25ce5661997-08-02 03:10:38 +00002327 PyObject *modules = PyImport_GetModuleDict();
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002328 PyObject *path = NULL, *loader = NULL;
Guido van Rossum222ef561997-09-06 19:41:09 +00002329 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002330 char buf[MAXPATHLEN+1];
2331 struct filedescr *fdp;
2332 FILE *fp = NULL;
Tim Peters1cd70172004-08-02 03:52:12 +00002333 PyObject *newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002334
Guido van Rossum79f25d91997-04-29 20:08:16 +00002335 if (m == NULL || !PyModule_Check(m)) {
2336 PyErr_SetString(PyExc_TypeError,
2337 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002338 return NULL;
2339 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002340 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002341 if (name == NULL)
2342 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00002343 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002344 PyErr_Format(PyExc_ImportError,
2345 "reload(): module %.200s not in sys.modules",
2346 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002347 return NULL;
2348 }
Guido van Rossum222ef561997-09-06 19:41:09 +00002349 subname = strrchr(name, '.');
2350 if (subname == NULL)
2351 subname = name;
2352 else {
2353 PyObject *parentname, *parent;
2354 parentname = PyString_FromStringAndSize(name, (subname-name));
2355 if (parentname == NULL)
2356 return NULL;
2357 parent = PyDict_GetItem(modules, parentname);
2358 if (parent == NULL) {
2359 PyErr_Format(PyExc_ImportError,
2360 "reload(): parent %.200s not in sys.modules",
Georg Brandl0c55f292005-09-14 06:56:20 +00002361 PyString_AS_STRING(parentname));
2362 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002363 return NULL;
2364 }
Georg Brandl0c55f292005-09-14 06:56:20 +00002365 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00002366 subname++;
2367 path = PyObject_GetAttrString(parent, "__path__");
2368 if (path == NULL)
2369 PyErr_Clear();
2370 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002371 buf[0] = '\0';
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002372 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
Guido van Rossum222ef561997-09-06 19:41:09 +00002373 Py_XDECREF(path);
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002374
2375 if (fdp == NULL) {
2376 Py_XDECREF(loader);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002377 return NULL;
Phillip J. Eby7ec642a2004-09-23 04:37:36 +00002378 }
2379
2380 newm = load_module(name, fp, buf, fdp->type, loader);
2381 Py_XDECREF(loader);
2382
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002383 if (fp)
2384 fclose(fp);
Tim Peters1cd70172004-08-02 03:52:12 +00002385 if (newm == NULL) {
2386 /* load_module probably removed name from modules because of
2387 * the error. Put back the original module object. We're
2388 * going to return NULL in this case regardless of whether
2389 * replacing name succeeds, so the return value is ignored.
2390 */
2391 PyDict_SetItemString(modules, name, m);
2392 }
2393 return newm;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002394}
2395
2396
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002397/* Higher-level import emulator which emulates the "import" statement
2398 more accurately -- it invokes the __import__() function from the
2399 builtins of the current globals. This means that the import is
2400 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00002401 environment, e.g. by "rexec".
2402 A dummy list ["__doc__"] is passed as the 4th argument so that
2403 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2404 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002405
2406PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002407PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002408{
2409 static PyObject *silly_list = NULL;
2410 static PyObject *builtins_str = NULL;
2411 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002412 PyObject *globals = NULL;
2413 PyObject *import = NULL;
2414 PyObject *builtins = NULL;
2415 PyObject *r = NULL;
2416
2417 /* Initialize constant string objects */
2418 if (silly_list == NULL) {
2419 import_str = PyString_InternFromString("__import__");
2420 if (import_str == NULL)
2421 return NULL;
2422 builtins_str = PyString_InternFromString("__builtins__");
2423 if (builtins_str == NULL)
2424 return NULL;
2425 silly_list = Py_BuildValue("[s]", "__doc__");
2426 if (silly_list == NULL)
2427 return NULL;
2428 }
2429
2430 /* Get the builtins from current globals */
2431 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002432 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00002433 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002434 builtins = PyObject_GetItem(globals, builtins_str);
2435 if (builtins == NULL)
2436 goto err;
2437 }
2438 else {
2439 /* No globals -- use standard builtins, and fake globals */
2440 PyErr_Clear();
2441
Thomas Woutersf7f438b2006-02-28 16:09:29 +00002442 builtins = PyImport_ImportModuleLevel("__builtin__",
2443 NULL, NULL, NULL, 0);
Guido van Rossum85cd1d62001-02-20 21:43:24 +00002444 if (builtins == NULL)
2445 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002446 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2447 if (globals == NULL)
2448 goto err;
2449 }
2450
2451 /* Get the __import__ function from the builtins */
Tim Peters6d6c1a32001-08-02 04:15:00 +00002452 if (PyDict_Check(builtins)) {
Fred Drakea76ba6e2001-03-06 06:31:15 +00002453 import = PyObject_GetItem(builtins, import_str);
Tim Peters6d6c1a32001-08-02 04:15:00 +00002454 if (import == NULL)
2455 PyErr_SetObject(PyExc_KeyError, import_str);
2456 }
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002457 else
Fred Drakea76ba6e2001-03-06 06:31:15 +00002458 import = PyObject_GetAttr(builtins, import_str);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002459 if (import == NULL)
2460 goto err;
2461
2462 /* Call the _import__ function with the proper argument list */
2463 r = PyObject_CallFunction(import, "OOOO",
2464 module_name, globals, globals, silly_list);
2465
2466 err:
2467 Py_XDECREF(globals);
2468 Py_XDECREF(builtins);
2469 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00002470
Guido van Rossumd47a0a81997-08-14 20:11:26 +00002471 return r;
2472}
2473
2474
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002475/* Module 'imp' provides Python access to the primitives used for
2476 importing modules.
2477*/
2478
Guido van Rossum79f25d91997-04-29 20:08:16 +00002479static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002480imp_get_magic(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002481{
2482 char buf[4];
2483
Guido van Rossum96774c12000-05-01 20:19:08 +00002484 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2485 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2486 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2487 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002488
Guido van Rossum79f25d91997-04-29 20:08:16 +00002489 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002490}
2491
Guido van Rossum79f25d91997-04-29 20:08:16 +00002492static PyObject *
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002493imp_get_suffixes(PyObject *self, PyObject *noargs)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002494{
Guido van Rossum79f25d91997-04-29 20:08:16 +00002495 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002496 struct filedescr *fdp;
2497
Guido van Rossum79f25d91997-04-29 20:08:16 +00002498 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002499 if (list == NULL)
2500 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002501 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2502 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002503 fdp->suffix, fdp->mode, fdp->type);
2504 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002505 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002506 return NULL;
2507 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002508 if (PyList_Append(list, item) < 0) {
2509 Py_DECREF(list);
2510 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002511 return NULL;
2512 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002513 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002514 }
2515 return list;
2516}
2517
Guido van Rossum79f25d91997-04-29 20:08:16 +00002518static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002519call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002520{
Tim Petersdbd9ba62000-07-09 03:09:57 +00002521 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002522 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002523 struct filedescr *fdp;
2524 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002525 FILE *fp = NULL;
2526
2527 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00002528 if (path == Py_None)
2529 path = NULL;
Just van Rossum52e14d62002-12-30 22:08:05 +00002530 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002531 if (fdp == NULL)
2532 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002533 if (fp != NULL) {
2534 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2535 if (fob == NULL) {
2536 fclose(fp);
2537 return NULL;
2538 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002539 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002540 else {
2541 fob = Py_None;
2542 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00002543 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002544 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002545 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002546 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002547 return ret;
2548}
2549
Guido van Rossum79f25d91997-04-29 20:08:16 +00002550static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002551imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002552{
2553 char *name;
2554 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002555 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002556 return NULL;
2557 return call_find_module(name, path);
2558}
2559
2560static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002561imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002562{
2563 char *name;
2564 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002565 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002566 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002567 return NULL;
2568 ret = init_builtin(name);
2569 if (ret < 0)
2570 return NULL;
2571 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002572 Py_INCREF(Py_None);
2573 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002574 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002575 m = PyImport_AddModule(name);
2576 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002577 return m;
2578}
2579
Guido van Rossum79f25d91997-04-29 20:08:16 +00002580static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002581imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002582{
2583 char *name;
2584 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002585 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002586 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002587 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002588 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002589 if (ret < 0)
2590 return NULL;
2591 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002592 Py_INCREF(Py_None);
2593 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002594 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002595 m = PyImport_AddModule(name);
2596 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002597 return m;
2598}
2599
Guido van Rossum79f25d91997-04-29 20:08:16 +00002600static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002601imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002602{
2603 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002604
Guido van Rossum43713e52000-02-29 13:59:29 +00002605 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002606 return NULL;
2607 return get_frozen_object(name);
2608}
2609
Guido van Rossum79f25d91997-04-29 20:08:16 +00002610static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002611imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002612{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002613 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002614 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002615 return NULL;
Guido van Rossum50ee94f2002-04-09 18:00:58 +00002616 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002617}
2618
Guido van Rossum79f25d91997-04-29 20:08:16 +00002619static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002620imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002621{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002622 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002623 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002624 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002625 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002626 p = find_frozen(name);
Guido van Rossumb8bff3f2002-04-07 06:34:38 +00002627 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002628}
2629
2630static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002631get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002632{
2633 FILE *fp;
2634 if (fob == NULL) {
Tim Peters86c7d2f2004-08-01 23:24:21 +00002635 if (mode[0] == 'U')
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002636 mode = "r" PY_STDIOTEXTMODE;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002637 fp = fopen(pathname, mode);
2638 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002639 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002640 }
2641 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002642 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002643 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002644 PyErr_SetString(PyExc_ValueError,
2645 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002646 }
2647 return fp;
2648}
2649
Guido van Rossum79f25d91997-04-29 20:08:16 +00002650static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002651imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002652{
2653 char *name;
2654 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002655 PyObject *fob = NULL;
2656 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002657 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002658 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002659 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002660 return NULL;
2661 fp = get_file(pathname, fob, "rb");
2662 if (fp == NULL)
2663 return NULL;
2664 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002665 if (fob == NULL)
2666 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002667 return m;
2668}
2669
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002670#ifdef HAVE_DYNAMIC_LOADING
2671
Guido van Rossum79f25d91997-04-29 20:08:16 +00002672static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002673imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002674{
2675 char *name;
2676 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002677 PyObject *fob = NULL;
2678 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002679 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002680 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002681 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002682 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002683 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002684 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002685 if (fp == NULL)
2686 return NULL;
2687 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002688 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002689 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002690}
2691
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002692#endif /* HAVE_DYNAMIC_LOADING */
2693
Guido van Rossum79f25d91997-04-29 20:08:16 +00002694static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002695imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002696{
2697 char *name;
2698 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002699 PyObject *fob = NULL;
2700 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002701 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002702 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002703 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002704 return NULL;
2705 fp = get_file(pathname, fob, "r");
2706 if (fp == NULL)
2707 return NULL;
2708 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002709 if (fob == NULL)
2710 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002711 return m;
2712}
2713
Guido van Rossum79f25d91997-04-29 20:08:16 +00002714static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002715imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002716{
2717 char *name;
2718 PyObject *fob;
2719 char *pathname;
2720 char *suffix; /* Unused */
2721 char *mode;
2722 int type;
2723 FILE *fp;
2724
Guido van Rossum43713e52000-02-29 13:59:29 +00002725 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002726 &name, &fob, &pathname,
2727 &suffix, &mode, &type))
2728 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002729 if (*mode) {
2730 /* Mode must start with 'r' or 'U' and must not contain '+'.
2731 Implicit in this test is the assumption that the mode
2732 may contain other modifiers like 'b' or 't'. */
2733
2734 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
Jeremy Hylton4ae6fae2002-05-30 17:15:25 +00002735 PyErr_Format(PyExc_ValueError,
2736 "invalid file open mode %.200s", mode);
2737 return NULL;
Guido van Rossum5e2c5fa2002-05-30 17:33:07 +00002738 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002739 }
2740 if (fob == Py_None)
2741 fp = NULL;
2742 else {
2743 if (!PyFile_Check(fob)) {
2744 PyErr_SetString(PyExc_ValueError,
2745 "load_module arg#2 should be a file or None");
2746 return NULL;
2747 }
2748 fp = get_file(pathname, fob, mode);
2749 if (fp == NULL)
2750 return NULL;
2751 }
Just van Rossum52e14d62002-12-30 22:08:05 +00002752 return load_module(name, fp, pathname, type, NULL);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002753}
2754
2755static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002756imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002757{
2758 char *name;
2759 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002760 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002761 return NULL;
2762 return load_package(name, pathname);
2763}
2764
2765static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002766imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002767{
2768 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002769 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002770 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002771 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002772}
2773
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002774/* Doc strings */
2775
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002776PyDoc_STRVAR(doc_imp,
2777"This module provides the components needed to build your own\n\
2778__import__ function. Undocumented functions are obsolete.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002779
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002780PyDoc_STRVAR(doc_find_module,
2781"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002782Search for a module. If path is omitted or None, search for a\n\
2783built-in, frozen or special module and continue search in sys.path.\n\
2784The module name cannot contain '.'; to search for a submodule of a\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002785package, pass the submodule name and the package's __path__.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002786
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002787PyDoc_STRVAR(doc_load_module,
2788"load_module(name, file, filename, (suffix, mode, type)) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002789Load a module, given information returned by find_module().\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002790The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002791
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002792PyDoc_STRVAR(doc_get_magic,
2793"get_magic() -> string\n\
2794Return the magic number for .pyc or .pyo files.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002795
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002796PyDoc_STRVAR(doc_get_suffixes,
2797"get_suffixes() -> [(suffix, mode, type), ...]\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002798Return a list of (suffix, mode, type) tuples describing the files\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002799that find_module() looks for.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002800
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002801PyDoc_STRVAR(doc_new_module,
2802"new_module(name) -> module\n\
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002803Create a new module. Do not enter it in sys.modules.\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002804The module name must include the full package name, if any.");
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002805
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00002806PyDoc_STRVAR(doc_lock_held,
Tim Petersa7c65092004-08-01 23:26:05 +00002807"lock_held() -> boolean\n\
2808Return True if the import lock is currently held, else False.\n\
2809On platforms without threads, return False.");
Tim Peters69232342001-08-30 05:16:13 +00002810
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002811PyDoc_STRVAR(doc_acquire_lock,
2812"acquire_lock() -> None\n\
Neal Norwitz2294c0d2003-02-12 23:02:21 +00002813Acquires the interpreter's import lock for the current thread.\n\
2814This lock should be used by import hooks to ensure thread-safety\n\
2815when importing modules.\n\
Guido van Rossumc4f4ca92003-02-12 21:46:11 +00002816On platforms without threads, this function does nothing.");
2817
2818PyDoc_STRVAR(doc_release_lock,
2819"release_lock() -> None\n\
2820Release the interpreter's import lock.\n\
2821On platforms without threads, this function does nothing.");
2822
Guido van Rossum79f25d91997-04-29 20:08:16 +00002823static PyMethodDef imp_methods[] = {
Neal Norwitz08ea61a2003-02-17 18:18:00 +00002824 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2825 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2826 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2827 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2828 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2829 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2830 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2831 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002832 /* The rest are obsolete */
Neal Norwitz031829d2002-03-31 14:37:44 +00002833 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2834 {"init_builtin", imp_init_builtin, METH_VARARGS},
2835 {"init_frozen", imp_init_frozen, METH_VARARGS},
2836 {"is_builtin", imp_is_builtin, METH_VARARGS},
2837 {"is_frozen", imp_is_frozen, METH_VARARGS},
2838 {"load_compiled", imp_load_compiled, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002839#ifdef HAVE_DYNAMIC_LOADING
Neal Norwitz031829d2002-03-31 14:37:44 +00002840 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002841#endif
Neal Norwitz031829d2002-03-31 14:37:44 +00002842 {"load_package", imp_load_package, METH_VARARGS},
Neal Norwitz031829d2002-03-31 14:37:44 +00002843 {"load_source", imp_load_source, METH_VARARGS},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002844 {NULL, NULL} /* sentinel */
2845};
2846
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002847static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002848setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002849{
2850 PyObject *v;
2851 int err;
2852
2853 v = PyInt_FromLong((long)value);
2854 err = PyDict_SetItemString(d, name, v);
2855 Py_XDECREF(v);
2856 return err;
2857}
2858
Jason Tishler6bc06ec2003-09-04 11:59:50 +00002859PyMODINIT_FUNC
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002860initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002861{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002862 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002863
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002864 m = Py_InitModule4("imp", imp_methods, doc_imp,
2865 NULL, PYTHON_API_VERSION);
Neal Norwitz1ac754f2006-01-19 06:09:39 +00002866 if (m == NULL)
2867 goto failure;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002868 d = PyModule_GetDict(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002869
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002870 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2871 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2872 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2873 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2874 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2875 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2876 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2877 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00002878 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Just van Rossum52e14d62002-12-30 22:08:05 +00002879 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002880
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002881 failure:
2882 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002883}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002884
2885
Guido van Rossumb18618d2000-05-03 23:44:39 +00002886/* API for embedding applications that want to add their own entries
2887 to the table of built-in modules. This should normally be called
2888 *before* Py_Initialize(). When the table resize fails, -1 is
2889 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002890
2891 After a similar function by Just van Rossum. */
2892
2893int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002894PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002895{
2896 static struct _inittab *our_copy = NULL;
2897 struct _inittab *p;
2898 int i, n;
2899
2900 /* Count the number of entries in both tables */
2901 for (n = 0; newtab[n].name != NULL; n++)
2902 ;
2903 if (n == 0)
2904 return 0; /* Nothing to do */
2905 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2906 ;
2907
2908 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00002909 p = our_copy;
2910 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002911 if (p == NULL)
2912 return -1;
2913
2914 /* Copy the tables into the new memory */
2915 if (our_copy != PyImport_Inittab)
2916 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2917 PyImport_Inittab = our_copy = p;
2918 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2919
2920 return 0;
2921}
2922
2923/* Shorthand to add a single entry given a name and a function */
2924
2925int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002926PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002927{
2928 struct _inittab newtab[2];
2929
2930 memset(newtab, '\0', sizeof newtab);
2931
2932 newtab[0].name = name;
2933 newtab[0].initfunc = initfunc;
2934
2935 return PyImport_ExtendInittab(newtab);
2936}