blob: 5daca1f67d2764597a27bc90be4ec8c928334f78 [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
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006#include "node.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00007#include "token.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00008#include "errcode.h"
Guido van Rossumc405b7b1991-06-04 19:39:42 +00009#include "marshal.h"
10#include "compile.h"
Guido van Rossumff4949e1992-08-05 19:58:53 +000011#include "eval.h"
Guido van Rossumd8bac6d1992-02-26 15:19:13 +000012#include "osdefs.h"
Guido van Rossum1ae940a1995-01-02 19:04:15 +000013#include "importdl.h"
Jack Jansen9c96a921995-02-15 22:57:06 +000014#ifdef macintosh
15#include "macglue.h"
16#endif
Guido van Rossumc405b7b1991-06-04 19:39:42 +000017
Guido van Rossum80bb9651996-12-05 23:27:02 +000018#ifdef HAVE_UNISTD_H
19#include <unistd.h>
20#endif
21
Guido van Rossum55a83382000-09-20 20:31:38 +000022#ifdef HAVE_FCNTL_H
23#include <fcntl.h>
24#endif
25
Guido van Rossum595d7ba1997-12-05 21:45:29 +000026#if defined(PYCC_VACPP)
27/* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
28#define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG)
29#endif
30
Guido van Rossumaee0bad1997-09-05 07:33:22 +000031#ifndef S_ISDIR
32#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
33#endif
34
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000035extern time_t PyOS_GetLastModificationTime(char *, FILE *);
36 /* In getmtime.c */
Guido van Rossum21d335e1993-10-15 13:01:11 +000037
Guido van Rossum6c849691994-09-26 15:47:17 +000038/* Magic word to reject .pyc files generated by other Python versions */
Guido van Rossum7faeab31995-07-07 22:50:36 +000039/* Change for each incompatible change */
40/* The value of CR and LF is incorporated so if you ever read or write
41 a .pyc file in text mode the magic number will be wrong; also, the
42 Apple MPW compiler swaps their values, botching string constants */
43/* XXX Perhaps the magic number should be frozen and a version field
44 added to the .pyc file header? */
Guido van Rossumdd5db431997-01-17 21:06:11 +000045/* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */
Jeremy Hyltonb1cbc1e2001-02-02 20:13:24 +000046#define MAGIC (60202 | ((long)'\r'<<16) | ((long)'\n'<<24))
Guido van Rossum3ddee711991-12-16 13:06:34 +000047
Guido van Rossum96774c12000-05-01 20:19:08 +000048/* Magic word as global; note that _PyImport_Init() can change the
Jeremy Hylton9262b8a2000-06-30 04:59:17 +000049 value of this global to accommodate for alterations of how the
Guido van Rossum96774c12000-05-01 20:19:08 +000050 compiler works which are enabled by command line switches. */
51static long pyc_magic = MAGIC;
52
Guido van Rossum25ce5661997-08-02 03:10:38 +000053/* See _PyImport_FixupExtension() below */
54static PyObject *extensions = NULL;
Guido van Rossum3f5da241990-12-20 15:06:42 +000055
Guido van Rossum771c6c81997-10-31 18:37:24 +000056/* This table is defined in config.c: */
57extern struct _inittab _PyImport_Inittab[];
58
59struct _inittab *PyImport_Inittab = _PyImport_Inittab;
Guido van Rossum66f1fa81991-04-03 19:03:52 +000060
Guido van Rossumed1170e1999-12-20 21:23:41 +000061/* these tables define the module suffixes that Python recognizes */
62struct filedescr * _PyImport_Filetab = NULL;
63static const struct filedescr _PyImport_StandardFiletab[] = {
64 {".py", "r", PY_SOURCE},
65 {".pyc", "rb", PY_COMPILED},
66 {0, 0}
67};
68
Guido van Rossum1ae940a1995-01-02 19:04:15 +000069/* Initialize things */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070
71void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +000072_PyImport_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000073{
Guido van Rossumed1170e1999-12-20 21:23:41 +000074 const struct filedescr *scan;
75 struct filedescr *filetab;
76 int countD = 0;
77 int countS = 0;
78
79 /* prepare _PyImport_Filetab: copy entries from
80 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
81 */
82 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
83 ++countD;
84 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
85 ++countS;
Guido van Rossumb18618d2000-05-03 23:44:39 +000086 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
Guido van Rossumed1170e1999-12-20 21:23:41 +000087 memcpy(filetab, _PyImport_DynLoadFiletab,
88 countD * sizeof(struct filedescr));
89 memcpy(filetab + countD, _PyImport_StandardFiletab,
90 countS * sizeof(struct filedescr));
91 filetab[countD + countS].suffix = NULL;
92
93 _PyImport_Filetab = filetab;
94
Guido van Rossum0824f631997-03-11 18:37:35 +000095 if (Py_OptimizeFlag) {
Guido van Rossumed1170e1999-12-20 21:23:41 +000096 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
97 for (; filetab->suffix != NULL; filetab++) {
98 if (strcmp(filetab->suffix, ".pyc") == 0)
99 filetab->suffix = ".pyo";
Guido van Rossum0824f631997-03-11 18:37:35 +0000100 }
101 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000102
103 if (Py_UnicodeFlag) {
104 /* Fix the pyc_magic so that byte compiled code created
105 using the all-Unicode method doesn't interfere with
106 code created in normal operation mode. */
107 pyc_magic = MAGIC + 1;
108 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000109}
110
Guido van Rossum25ce5661997-08-02 03:10:38 +0000111void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000112_PyImport_Fini(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000113{
114 Py_XDECREF(extensions);
115 extensions = NULL;
Barry Warsaw84294482000-10-03 16:02:05 +0000116 PyMem_DEL(_PyImport_Filetab);
117 _PyImport_Filetab = NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000118}
119
120
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000121/* Locking primitives to prevent parallel imports of the same module
122 in different threads to return with a partially loaded module.
123 These calls are serialized by the global interpreter lock. */
124
125#ifdef WITH_THREAD
126
Guido van Rossum49b56061998-10-01 20:42:43 +0000127#include "pythread.h"
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000128
Guido van Rossum65d5b571998-12-21 19:32:43 +0000129static PyThread_type_lock import_lock = 0;
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000130static long import_lock_thread = -1;
131static int import_lock_level = 0;
132
133static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000134lock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000135{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000136 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000137 if (me == -1)
138 return; /* Too bad */
139 if (import_lock == NULL)
Guido van Rossum65d5b571998-12-21 19:32:43 +0000140 import_lock = PyThread_allocate_lock();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000141 if (import_lock_thread == me) {
142 import_lock_level++;
143 return;
144 }
Guido van Rossum65d5b571998-12-21 19:32:43 +0000145 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) {
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000146 PyThreadState *tstate = PyEval_SaveThread();
Guido van Rossum65d5b571998-12-21 19:32:43 +0000147 PyThread_acquire_lock(import_lock, 1);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000148 PyEval_RestoreThread(tstate);
149 }
150 import_lock_thread = me;
151 import_lock_level = 1;
152}
153
154static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000155unlock_import(void)
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000156{
Guido van Rossum65d5b571998-12-21 19:32:43 +0000157 long me = PyThread_get_thread_ident();
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000158 if (me == -1)
159 return; /* Too bad */
160 if (import_lock_thread != me)
161 Py_FatalError("unlock_import: not holding the import lock");
162 import_lock_level--;
163 if (import_lock_level == 0) {
164 import_lock_thread = -1;
Guido van Rossum65d5b571998-12-21 19:32:43 +0000165 PyThread_release_lock(import_lock);
Guido van Rossum75acc9c1998-03-03 22:26:50 +0000166 }
167}
168
169#else
170
171#define lock_import()
172#define unlock_import()
173
174#endif
175
Guido van Rossum25ce5661997-08-02 03:10:38 +0000176/* Helper for sys */
177
178PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000179PyImport_GetModuleDict(void)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000180{
181 PyInterpreterState *interp = PyThreadState_Get()->interp;
182 if (interp->modules == NULL)
183 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
184 return interp->modules;
185}
186
Guido van Rossum3f5da241990-12-20 15:06:42 +0000187
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000188/* List of names to clear in sys */
189static char* sys_deletes[] = {
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000190 "path", "argv", "ps1", "ps2", "exitfunc",
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000191 "exc_type", "exc_value", "exc_traceback",
192 "last_type", "last_value", "last_traceback",
193 NULL
194};
195
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000196static char* sys_files[] = {
197 "stdin", "__stdin__",
198 "stdout", "__stdout__",
199 "stderr", "__stderr__",
200 NULL
201};
202
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000203
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000204/* Un-initialize things, as good as we can */
Guido van Rossum3f5da241990-12-20 15:06:42 +0000205
Guido van Rossum3f5da241990-12-20 15:06:42 +0000206void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000207PyImport_Cleanup(void)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000208{
Guido van Rossum758eec01998-01-19 21:58:26 +0000209 int pos, ndone;
210 char *name;
211 PyObject *key, *value, *dict;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000212 PyInterpreterState *interp = PyThreadState_Get()->interp;
Guido van Rossum758eec01998-01-19 21:58:26 +0000213 PyObject *modules = interp->modules;
214
215 if (modules == NULL)
216 return; /* Already done */
217
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000218 /* Delete some special variables first. These are common
219 places where user values hide and people complain when their
220 destructors fail. Since the modules containing them are
221 deleted *last* of all, they would come too late in the normal
222 destruction order. Sigh. */
223
224 value = PyDict_GetItemString(modules, "__builtin__");
225 if (value != NULL && PyModule_Check(value)) {
226 dict = PyModule_GetDict(value);
227 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000228 PySys_WriteStderr("# clear __builtin__._\n");
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000229 PyDict_SetItemString(dict, "_", Py_None);
230 }
231 value = PyDict_GetItemString(modules, "sys");
232 if (value != NULL && PyModule_Check(value)) {
233 char **p;
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000234 PyObject *v;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000235 dict = PyModule_GetDict(value);
236 for (p = sys_deletes; *p != NULL; p++) {
237 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000238 PySys_WriteStderr("# clear sys.%s\n", *p);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000239 PyDict_SetItemString(dict, *p, Py_None);
240 }
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000241 for (p = sys_files; *p != NULL; p+=2) {
242 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000243 PySys_WriteStderr("# restore sys.%s\n", *p);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000244 v = PyDict_GetItemString(dict, *(p+1));
245 if (v == NULL)
246 v = Py_None;
247 PyDict_SetItemString(dict, *p, v);
248 }
249 }
250
251 /* First, delete __main__ */
252 value = PyDict_GetItemString(modules, "__main__");
253 if (value != NULL && PyModule_Check(value)) {
254 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000255 PySys_WriteStderr("# cleanup __main__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000256 _PyModule_Clear(value);
257 PyDict_SetItemString(modules, "__main__", Py_None);
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000258 }
259
Guido van Rossum758eec01998-01-19 21:58:26 +0000260 /* The special treatment of __builtin__ here is because even
261 when it's not referenced as a module, its dictionary is
262 referenced by almost every module's __builtins__. Since
263 deleting a module clears its dictionary (even if there are
264 references left to it), we need to delete the __builtin__
265 module last. Likewise, we don't delete sys until the very
266 end because it is implicitly referenced (e.g. by print).
267
268 Also note that we 'delete' modules by replacing their entry
269 in the modules dict with None, rather than really deleting
270 them; this avoids a rehash of the modules dictionary and
271 also marks them as "non existent" so they won't be
272 re-imported. */
273
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000274 /* Next, repeatedly delete modules with a reference count of
Guido van Rossum758eec01998-01-19 21:58:26 +0000275 one (skipping __builtin__ and sys) and delete them */
276 do {
277 ndone = 0;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000278 pos = 0;
Guido van Rossum758eec01998-01-19 21:58:26 +0000279 while (PyDict_Next(modules, &pos, &key, &value)) {
280 if (value->ob_refcnt != 1)
281 continue;
Guido van Rossum566373e1998-10-01 15:24:50 +0000282 if (PyString_Check(key) && PyModule_Check(value)) {
283 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000284 if (strcmp(name, "__builtin__") == 0)
285 continue;
286 if (strcmp(name, "sys") == 0)
287 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000288 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000289 PySys_WriteStderr(
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000290 "# cleanup[1] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000291 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000292 PyDict_SetItem(modules, key, Py_None);
293 ndone++;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000294 }
295 }
Guido van Rossum758eec01998-01-19 21:58:26 +0000296 } while (ndone > 0);
297
Guido van Rossum758eec01998-01-19 21:58:26 +0000298 /* Next, delete all modules (still skipping __builtin__ and sys) */
299 pos = 0;
300 while (PyDict_Next(modules, &pos, &key, &value)) {
Guido van Rossum566373e1998-10-01 15:24:50 +0000301 if (PyString_Check(key) && PyModule_Check(value)) {
302 name = PyString_AS_STRING(key);
Guido van Rossum758eec01998-01-19 21:58:26 +0000303 if (strcmp(name, "__builtin__") == 0)
304 continue;
305 if (strcmp(name, "sys") == 0)
306 continue;
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000307 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000308 PySys_WriteStderr("# cleanup[2] %s\n", name);
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000309 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000310 PyDict_SetItem(modules, key, Py_None);
311 }
312 }
313
314 /* Next, delete sys and __builtin__ (in that order) */
315 value = PyDict_GetItemString(modules, "sys");
316 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000317 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000318 PySys_WriteStderr("# cleanup sys\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000319 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000320 PyDict_SetItemString(modules, "sys", Py_None);
321 }
322 value = PyDict_GetItemString(modules, "__builtin__");
323 if (value != NULL && PyModule_Check(value)) {
Guido van Rossuma0fec2b1998-02-06 17:16:02 +0000324 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000325 PySys_WriteStderr("# cleanup __builtin__\n");
Guido van Rossum05f9dce1998-02-19 20:58:44 +0000326 _PyModule_Clear(value);
Guido van Rossum758eec01998-01-19 21:58:26 +0000327 PyDict_SetItemString(modules, "__builtin__", Py_None);
328 }
329
330 /* Finally, clear and delete the modules directory */
331 PyDict_Clear(modules);
332 interp->modules = NULL;
333 Py_DECREF(modules);
Guido van Rossum8d15b5d1990-10-26 14:58:58 +0000334}
Guido van Rossum7f133ed1991-02-19 12:23:57 +0000335
336
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000337/* Helper for pythonrun.c -- return magic number */
338
339long
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000340PyImport_GetMagicNumber(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000341{
Guido van Rossum96774c12000-05-01 20:19:08 +0000342 return pyc_magic;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000343}
344
345
Guido van Rossum25ce5661997-08-02 03:10:38 +0000346/* Magic for extension modules (built-in as well as dynamically
347 loaded). To prevent initializing an extension module more than
348 once, we keep a static dictionary 'extensions' keyed by module name
349 (for built-in modules) or by filename (for dynamically loaded
350 modules), containing these modules. A copy od the module's
351 dictionary is stored by calling _PyImport_FixupExtension()
352 immediately after the module initialization function succeeds. A
353 copy can be retrieved from there by calling
354 _PyImport_FindExtension(). */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000355
Guido van Rossum79f25d91997-04-29 20:08:16 +0000356PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000357_PyImport_FixupExtension(char *name, char *filename)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000358{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000359 PyObject *modules, *mod, *dict, *copy;
360 if (extensions == NULL) {
361 extensions = PyDict_New();
362 if (extensions == NULL)
363 return NULL;
364 }
365 modules = PyImport_GetModuleDict();
366 mod = PyDict_GetItemString(modules, name);
367 if (mod == NULL || !PyModule_Check(mod)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000368 PyErr_Format(PyExc_SystemError,
369 "_PyImport_FixupExtension: module %.200s not loaded", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +0000370 return NULL;
371 }
372 dict = PyModule_GetDict(mod);
373 if (dict == NULL)
374 return NULL;
375 copy = PyObject_CallMethod(dict, "copy", "");
376 if (copy == NULL)
377 return NULL;
378 PyDict_SetItemString(extensions, filename, copy);
379 Py_DECREF(copy);
380 return copy;
381}
382
383PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000384_PyImport_FindExtension(char *name, char *filename)
Guido van Rossum25ce5661997-08-02 03:10:38 +0000385{
386 PyObject *dict, *mod, *mdict, *result;
387 if (extensions == NULL)
388 return NULL;
389 dict = PyDict_GetItemString(extensions, filename);
390 if (dict == NULL)
391 return NULL;
392 mod = PyImport_AddModule(name);
393 if (mod == NULL)
394 return NULL;
395 mdict = PyModule_GetDict(mod);
396 if (mdict == NULL)
397 return NULL;
398 result = PyObject_CallMethod(mdict, "update", "O", dict);
399 if (result == NULL)
400 return NULL;
401 Py_DECREF(result);
402 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000403 PySys_WriteStderr("import %s # previously loaded (%s)\n",
Guido van Rossum25ce5661997-08-02 03:10:38 +0000404 name, filename);
405 return mod;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000406}
407
408
409/* Get the module object corresponding to a module name.
410 First check the modules dictionary if there's one there,
411 if not, create a new one and insert in in the modules dictionary.
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000412 Because the former action is most common, THIS DOES NOT RETURN A
413 'NEW' REFERENCE! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000414
Guido van Rossum79f25d91997-04-29 20:08:16 +0000415PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000416PyImport_AddModule(char *name)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000417{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000418 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000419 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000420
Guido van Rossum25ce5661997-08-02 03:10:38 +0000421 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
Guido van Rossum79f25d91997-04-29 20:08:16 +0000422 PyModule_Check(m))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000423 return m;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000424 m = PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000425 if (m == NULL)
426 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +0000427 if (PyDict_SetItemString(modules, name, m) != 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000428 Py_DECREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000429 return NULL;
430 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000431 Py_DECREF(m); /* Yes, it still exists, in modules! */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000432
433 return m;
434}
435
436
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000437/* Execute a code object in a module and return the module object
438 WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000439
Guido van Rossum79f25d91997-04-29 20:08:16 +0000440PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000441PyImport_ExecCodeModule(char *name, PyObject *co)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000442{
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000443 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
444}
445
446PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000447PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000448{
Guido van Rossum25ce5661997-08-02 03:10:38 +0000449 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +0000450 PyObject *m, *d, *v;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000451
Guido van Rossum79f25d91997-04-29 20:08:16 +0000452 m = PyImport_AddModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000453 if (m == NULL)
454 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000455 d = PyModule_GetDict(m);
456 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
457 if (PyDict_SetItemString(d, "__builtins__",
458 PyEval_GetBuiltins()) != 0)
Guido van Rossum6135a871995-01-09 17:53:26 +0000459 return NULL;
460 }
Guido van Rossum9c9a07c1996-05-16 20:43:40 +0000461 /* Remember the filename as the __file__ attribute */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000462 v = NULL;
463 if (pathname != NULL) {
464 v = PyString_FromString(pathname);
465 if (v == NULL)
466 PyErr_Clear();
467 }
468 if (v == NULL) {
469 v = ((PyCodeObject *)co)->co_filename;
470 Py_INCREF(v);
471 }
472 if (PyDict_SetItemString(d, "__file__", v) != 0)
Guido van Rossum79f25d91997-04-29 20:08:16 +0000473 PyErr_Clear(); /* Not important enough to report */
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000474 Py_DECREF(v);
475
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000476 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000477 if (v == NULL)
478 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000479 Py_DECREF(v);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000480
Guido van Rossum25ce5661997-08-02 03:10:38 +0000481 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000482 PyErr_Format(PyExc_ImportError,
483 "Loaded module %.200s not found in sys.modules",
484 name);
Guido van Rossumb65e85c1997-07-10 18:00:45 +0000485 return NULL;
486 }
487
Guido van Rossum79f25d91997-04-29 20:08:16 +0000488 Py_INCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000489
490 return m;
491}
492
493
494/* Given a pathname for a Python source file, fill a buffer with the
495 pathname for the corresponding compiled file. Return the pathname
496 for the compiled file, or NULL if there's no space in the buffer.
497 Doesn't set an exception. */
498
499static char *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000500make_compiled_pathname(char *pathname, char *buf, size_t buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000501{
Fred Drake4c82b232000-06-30 16:18:57 +0000502 size_t len;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000503
504 len = strlen(pathname);
505 if (len+2 > buflen)
506 return NULL;
507 strcpy(buf, pathname);
Guido van Rossum0824f631997-03-11 18:37:35 +0000508 strcpy(buf+len, Py_OptimizeFlag ? "o" : "c");
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000509
510 return buf;
511}
512
513
514/* Given a pathname for a Python source file, its time of last
515 modification, and a pathname for a compiled file, check whether the
516 compiled file represents the same version of the source. If so,
517 return a FILE pointer for the compiled file, positioned just after
518 the header; if not, return NULL.
519 Doesn't set an exception. */
520
521static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000522check_compiled_module(char *pathname, long mtime, char *cpathname)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000523{
524 FILE *fp;
525 long magic;
526 long pyc_mtime;
527
528 fp = fopen(cpathname, "rb");
529 if (fp == NULL)
530 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000531 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000532 if (magic != pyc_magic) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000533 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000534 PySys_WriteStderr("# %s has bad magic\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000535 fclose(fp);
536 return NULL;
537 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000538 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000539 if (pyc_mtime != mtime) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000540 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000541 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000542 fclose(fp);
543 return NULL;
544 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000545 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000546 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000547 return fp;
548}
549
550
551/* Read a code object from a file and check it for validity */
552
Guido van Rossum79f25d91997-04-29 20:08:16 +0000553static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000554read_compiled_module(char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000555{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000556 PyObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000557
Tim Petersd9b9ac82001-01-28 00:27:39 +0000558 co = PyMarshal_ReadLastObjectFromFile(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000559 /* Ugly: rd_object() may return NULL with or without error */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000560 if (co == NULL || !PyCode_Check(co)) {
561 if (!PyErr_Occurred())
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000562 PyErr_Format(PyExc_ImportError,
563 "Non-code object in %.200s", cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000564 Py_XDECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000565 return NULL;
566 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000567 return (PyCodeObject *)co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000568}
569
570
571/* Load a module from a compiled file, execute it, and return its
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000572 module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000573
Guido van Rossum79f25d91997-04-29 20:08:16 +0000574static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000575load_compiled_module(char *name, char *cpathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000576{
577 long magic;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000578 PyCodeObject *co;
579 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000580
Guido van Rossum79f25d91997-04-29 20:08:16 +0000581 magic = PyMarshal_ReadLongFromFile(fp);
Guido van Rossum96774c12000-05-01 20:19:08 +0000582 if (magic != pyc_magic) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000583 PyErr_Format(PyExc_ImportError,
584 "Bad magic number in %.200s", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000585 return NULL;
586 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000587 (void) PyMarshal_ReadLongFromFile(fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000588 co = read_compiled_module(cpathname, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000589 if (co == NULL)
590 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000591 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000592 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000593 name, cpathname);
Guido van Rossume32bf6e1998-02-11 05:53:02 +0000594 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000595 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000596
597 return m;
598}
599
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000600/* Parse a source file and return the corresponding code object */
601
Guido van Rossum79f25d91997-04-29 20:08:16 +0000602static PyCodeObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000603parse_source_module(char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000604{
Guido van Rossum79f25d91997-04-29 20:08:16 +0000605 PyCodeObject *co;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000606 node *n;
607
Guido van Rossumb05a5c71997-05-07 17:46:13 +0000608 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000609 if (n == NULL)
610 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000611 co = PyNode_Compile(n, pathname);
612 PyNode_Free(n);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000613
614 return co;
615}
616
617
Guido van Rossum55a83382000-09-20 20:31:38 +0000618/* Helper to open a bytecode file for writing in exclusive mode */
619
620static FILE *
621open_exclusive(char *filename)
622{
623#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
624 /* Use O_EXCL to avoid a race condition when another process tries to
625 write the same file. When that happens, our open() call fails,
626 which is just fine (since it's only a cache).
627 XXX If the file exists and is writable but the directory is not
628 writable, the file will never be written. Oh well.
629 */
630 int fd;
631 (void) unlink(filename);
Tim Peters42c83af2000-09-29 04:03:10 +0000632 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
633#ifdef O_BINARY
634 |O_BINARY /* necessary for Windows */
635#endif
Tim Peters50d8d372001-02-28 05:34:27 +0000636
Tim Peters42c83af2000-09-29 04:03:10 +0000637 , 0666);
Guido van Rossum55a83382000-09-20 20:31:38 +0000638 if (fd < 0)
639 return NULL;
640 return fdopen(fd, "wb");
641#else
642 /* Best we can do -- on Windows this can't happen anyway */
643 return fopen(filename, "wb");
644#endif
645}
646
647
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000648/* Write a compiled module to a file, placing the time of last
649 modification of its source into the header.
650 Errors are ignored, if a write error occurs an attempt is made to
651 remove the file. */
652
653static void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000654write_compiled_module(PyCodeObject *co, char *cpathname, long mtime)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000655{
656 FILE *fp;
657
Guido van Rossum55a83382000-09-20 20:31:38 +0000658 fp = open_exclusive(cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000659 if (fp == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000660 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000661 PySys_WriteStderr(
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000662 "# can't create %s\n", cpathname);
663 return;
664 }
Guido van Rossum96774c12000-05-01 20:19:08 +0000665 PyMarshal_WriteLongToFile(pyc_magic, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000666 /* First write a 0 for mtime */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000667 PyMarshal_WriteLongToFile(0L, fp);
668 PyMarshal_WriteObjectToFile((PyObject *)co, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000669 if (ferror(fp)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000670 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000671 PySys_WriteStderr("# can't write %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000672 /* Don't keep partial file */
673 fclose(fp);
674 (void) unlink(cpathname);
675 return;
676 }
677 /* Now write the true mtime */
678 fseek(fp, 4L, 0);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000679 PyMarshal_WriteLongToFile(mtime, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000680 fflush(fp);
681 fclose(fp);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000682 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000683 PySys_WriteStderr("# wrote %s\n", cpathname);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000684#ifdef macintosh
Jack Jansencbf630f2000-07-11 21:59:16 +0000685 PyMac_setfiletype(cpathname, 'Pyth', 'PYC ');
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000686#endif
687}
688
689
690/* Load a source module from a given file and return its module
Guido van Rossum7f9fa971995-01-20 16:53:12 +0000691 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
692 byte-compiled file, use that instead. */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000693
Guido van Rossum79f25d91997-04-29 20:08:16 +0000694static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000695load_source_module(char *name, char *pathname, FILE *fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000696{
Fred Drake4c82b232000-06-30 16:18:57 +0000697 time_t mtime;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000698 FILE *fpc;
699 char buf[MAXPATHLEN+1];
700 char *cpathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000701 PyCodeObject *co;
702 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000703
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000704 mtime = PyOS_GetLastModificationTime(pathname, fp);
Fred Drakec63d3e92001-03-01 06:33:32 +0000705 if (mtime == (time_t)(-1))
Fred Drake4c82b232000-06-30 16:18:57 +0000706 return NULL;
707#if SIZEOF_TIME_T > 4
708 /* Python's .pyc timestamp handling presumes that the timestamp fits
709 in 4 bytes. This will be fine until sometime in the year 2038,
710 when a 4-byte signed time_t will overflow.
711 */
712 if (mtime >> 32) {
713 PyErr_SetString(PyExc_OverflowError,
Fred Drakec63d3e92001-03-01 06:33:32 +0000714 "modification time overflows a 4 byte field");
Fred Drake4c82b232000-06-30 16:18:57 +0000715 return NULL;
716 }
717#endif
718 cpathname = make_compiled_pathname(pathname, buf, (size_t)MAXPATHLEN+1);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000719 if (cpathname != NULL &&
720 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000721 co = read_compiled_module(cpathname, fpc);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000722 fclose(fpc);
723 if (co == NULL)
724 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000725 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000726 PySys_WriteStderr("import %s # precompiled from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000727 name, cpathname);
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000728 pathname = cpathname;
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000729 }
730 else {
731 co = parse_source_module(pathname, fp);
732 if (co == NULL)
733 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000734 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000735 PySys_WriteStderr("import %s # from %s\n",
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000736 name, pathname);
737 write_compiled_module(co, cpathname, mtime);
738 }
Guido van Rossumafd3dae1998-08-25 18:44:34 +0000739 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000740 Py_DECREF(co);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000741
742 return m;
743}
744
745
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000746/* Forward */
Tim Petersdbd9ba62000-07-09 03:09:57 +0000747static PyObject *load_module(char *, FILE *, char *, int);
748static struct filedescr *find_module(char *, PyObject *,
749 char *, size_t, FILE **);
750static struct _frozen *find_frozen(char *name);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000751
752/* Load a package and return its module object WITH INCREMENTED
753 REFERENCE COUNT */
754
755static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000756load_package(char *name, char *pathname)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000757{
758 PyObject *m, *d, *file, *path;
759 int err;
760 char buf[MAXPATHLEN+1];
761 FILE *fp = NULL;
762 struct filedescr *fdp;
763
764 m = PyImport_AddModule(name);
765 if (m == NULL)
766 return NULL;
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000767 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000768 PySys_WriteStderr("import %s # directory %s\n",
Guido van Rossum17fc85f1997-09-06 18:52:03 +0000769 name, pathname);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000770 d = PyModule_GetDict(m);
771 file = PyString_FromString(pathname);
772 if (file == NULL)
773 return NULL;
774 path = Py_BuildValue("[O]", file);
775 if (path == NULL) {
776 Py_DECREF(file);
777 return NULL;
778 }
779 err = PyDict_SetItemString(d, "__file__", file);
780 if (err == 0)
781 err = PyDict_SetItemString(d, "__path__", path);
782 if (err != 0) {
783 m = NULL;
784 goto cleanup;
785 }
786 buf[0] = '\0';
787 fdp = find_module("__init__", path, buf, sizeof(buf), &fp);
788 if (fdp == NULL) {
789 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
790 PyErr_Clear();
791 }
792 else
793 m = NULL;
794 goto cleanup;
795 }
796 m = load_module(name, fp, buf, fdp->type);
797 if (fp != NULL)
798 fclose(fp);
799 cleanup:
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000800 Py_XDECREF(path);
801 Py_XDECREF(file);
802 return m;
803}
804
805
806/* Helper to test for built-in module */
807
808static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000809is_builtin(char *name)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000810{
811 int i;
Guido van Rossum771c6c81997-10-31 18:37:24 +0000812 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
813 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
814 if (PyImport_Inittab[i].initfunc == NULL)
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000815 return -1;
816 else
817 return 1;
818 }
819 }
820 return 0;
821}
822
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000823
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000824/* Search the path (default sys.path) for a module. Return the
825 corresponding filedescr struct, and (via return arguments) the
826 pathname and an open file. Return NULL if the module is not found. */
827
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000828#ifdef MS_COREDLL
Thomas Woutersb4bd21c2000-07-22 23:38:01 +0000829extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
830 char *, int);
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000831#endif
832
Tim Peters50d8d372001-02-28 05:34:27 +0000833static int case_ok(char *, int, int, char *);
Tim Petersdbd9ba62000-07-09 03:09:57 +0000834static int find_init_module(char *); /* Forward */
Guido van Rossum197346f1997-10-31 18:38:52 +0000835
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000836static struct filedescr *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000837find_module(char *realname, PyObject *path, char *buf, size_t buflen,
838 FILE **p_fp)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000839{
Fred Drake4c82b232000-06-30 16:18:57 +0000840 int i, npath;
841 size_t len, namelen;
Guido van Rossuma5568d31998-03-05 03:45:08 +0000842 struct _frozen *f;
Guido van Rossum80bb9651996-12-05 23:27:02 +0000843 struct filedescr *fdp = NULL;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +0000844 FILE *fp = NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000845 struct stat statbuf;
Guido van Rossuma5568d31998-03-05 03:45:08 +0000846 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
847 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
848 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
Guido van Rossum0506a431998-08-11 15:07:39 +0000849 char name[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000850
Fred Drake4c82b232000-06-30 16:18:57 +0000851 if (strlen(realname) > MAXPATHLEN) {
852 PyErr_SetString(PyExc_OverflowError, "module name is too long");
853 return NULL;
854 }
Guido van Rossum0506a431998-08-11 15:07:39 +0000855 strcpy(name, realname);
856
857 if (path != NULL && PyString_Check(path)) {
858 /* Submodule of "frozen" package:
859 Set name to the fullname, path to NULL
860 and continue as "usual" */
861 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
862 PyErr_SetString(PyExc_ImportError,
863 "full frozen module name too long");
864 return NULL;
865 }
866 strcpy(buf, PyString_AsString(path));
867 strcat(buf, ".");
868 strcat(buf, name);
869 strcpy(name, buf);
870 path = NULL;
871 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000872 if (path == NULL) {
873 if (is_builtin(name)) {
Guido van Rossuma5568d31998-03-05 03:45:08 +0000874 strcpy(buf, name);
875 return &fd_builtin;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000876 }
Guido van Rossuma5568d31998-03-05 03:45:08 +0000877 if ((f = find_frozen(name)) != NULL) {
878 strcpy(buf, name);
879 return &fd_frozen;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000880 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000881
Guido van Rossumac279101996-08-22 23:10:58 +0000882#ifdef MS_COREDLL
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000883 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
884 if (fp != NULL) {
885 *p_fp = fp;
886 return fdp;
887 }
Guido van Rossuma5a3db71996-04-09 02:39:59 +0000888#endif
Guido van Rossuma5568d31998-03-05 03:45:08 +0000889 path = PySys_GetObject("path");
890 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000891 if (path == NULL || !PyList_Check(path)) {
892 PyErr_SetString(PyExc_ImportError,
Guido van Rossuma5568d31998-03-05 03:45:08 +0000893 "sys.path must be a list of directory names");
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000894 return NULL;
895 }
Guido van Rossum79f25d91997-04-29 20:08:16 +0000896 npath = PyList_Size(path);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000897 namelen = strlen(name);
898 for (i = 0; i < npath; i++) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000899 PyObject *v = PyList_GetItem(path, i);
900 if (!PyString_Check(v))
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000901 continue;
Guido van Rossum79f25d91997-04-29 20:08:16 +0000902 len = PyString_Size(v);
Guido van Rossumef3d02e1997-07-21 14:54:36 +0000903 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000904 continue; /* Too long */
Guido van Rossum79f25d91997-04-29 20:08:16 +0000905 strcpy(buf, PyString_AsString(v));
Fred Drake4c82b232000-06-30 16:18:57 +0000906 if (strlen(buf) != len)
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000907 continue; /* v contains '\0' */
Jack Jansen9c96a921995-02-15 22:57:06 +0000908#ifdef macintosh
Guido van Rossum741689d1997-08-12 14:53:39 +0000909#ifdef INTERN_STRINGS
Tim Peters50d8d372001-02-28 05:34:27 +0000910 /*
Guido van Rossum741689d1997-08-12 14:53:39 +0000911 ** Speedup: each sys.path item is interned, and
912 ** FindResourceModule remembers which items refer to
913 ** folders (so we don't have to bother trying to look
Tim Peters50d8d372001-02-28 05:34:27 +0000914 ** into them for resources).
Guido van Rossum741689d1997-08-12 14:53:39 +0000915 */
916 PyString_InternInPlace(&PyList_GET_ITEM(path, i));
917 v = PyList_GET_ITEM(path, i);
918#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000919 if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
Guido van Rossum79f25d91997-04-29 20:08:16 +0000920 static struct filedescr resfiledescr =
921 {"", "", PY_RESOURCE};
Tim Peters50d8d372001-02-28 05:34:27 +0000922
Jack Jansen9c96a921995-02-15 22:57:06 +0000923 return &resfiledescr;
924 }
Guido van Rossum0f84a341998-08-06 13:36:01 +0000925 if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
926 static struct filedescr resfiledescr =
927 {"", "", PY_CODERESOURCE};
Tim Peters50d8d372001-02-28 05:34:27 +0000928
Guido van Rossum0f84a341998-08-06 13:36:01 +0000929 return &resfiledescr;
930 }
Jack Jansen9c96a921995-02-15 22:57:06 +0000931#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000932 if (len > 0 && buf[len-1] != SEP
933#ifdef ALTSEP
934 && buf[len-1] != ALTSEP
935#endif
936 )
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000937 buf[len++] = SEP;
Guido van Rossum215c3402000-11-13 17:26:32 +0000938 strcpy(buf+len, name);
939 len += namelen;
Tim Peters50d8d372001-02-28 05:34:27 +0000940
941 /* Check for package import (buf holds a directory name,
942 and there's an __init__ module in that directory */
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000943#ifdef HAVE_STAT
Tim Peters50d8d372001-02-28 05:34:27 +0000944 if (stat(buf, &statbuf) == 0 &&
945 S_ISDIR(statbuf.st_mode) &&
946 find_init_module(buf)) {
947 if (case_ok(buf, len, namelen, name))
948 return &fd_package;
949 else
950 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000951 }
952#else
953 /* XXX How are you going to test for directories? */
954#endif
Guido van Rossum9a61dc91997-10-08 15:25:08 +0000955#ifdef macintosh
956 fdp = PyMac_FindModuleExtension(buf, &len, name);
957 if (fdp)
958 fp = fopen(buf, fdp->mode);
959#else
Guido van Rossum79f25d91997-04-29 20:08:16 +0000960 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000961 strcpy(buf+len, fdp->suffix);
Guido van Rossum79f25d91997-04-29 20:08:16 +0000962 if (Py_VerboseFlag > 1)
Guido van Rossum2f3667a1998-10-12 18:23:55 +0000963 PySys_WriteStderr("# trying %s\n", buf);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000964 fp = fopen(buf, fdp->mode);
Tim Peters50d8d372001-02-28 05:34:27 +0000965 if (fp != NULL) {
966 if (case_ok(buf, len, namelen, name))
967 break;
968 else { /* continue search */
969 fclose(fp);
970 fp = NULL;
Barry Warsaw914a0b12001-02-02 19:12:16 +0000971 }
Barry Warsaw914a0b12001-02-02 19:12:16 +0000972 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000973 }
Guido van Rossum741689d1997-08-12 14:53:39 +0000974#endif /* !macintosh */
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000975 if (fp != NULL)
976 break;
977 }
978 if (fp == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +0000979 PyErr_Format(PyExc_ImportError,
980 "No module named %.200s", name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000981 return NULL;
982 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +0000983 *p_fp = fp;
984 return fdp;
985}
986
Tim Petersd1e87a82001-03-01 18:12:00 +0000987/* case_ok(char* buf, int len, int namelen, char* name)
988 * The arguments here are tricky, best shown by example:
989 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
990 * ^ ^ ^ ^
991 * |--------------------- buf ---------------------|
992 * |------------------- len ------------------|
993 * |------ name -------|
994 * |----- namelen -----|
995 * buf is the full path, but len only counts up to (& exclusive of) the
996 * extension. name is the module name, also exclusive of extension.
997 *
998 * We've already done a successful stat() or fopen() on buf, so know that
999 * there's some match, possibly case-insensitive.
1000 *
Tim Peters50d8d372001-02-28 05:34:27 +00001001 * case_ok() is to return 1 if there's a case-sensitive match for
1002 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1003 * exists.
Tim Petersd1e87a82001-03-01 18:12:00 +00001004 *
Tim Peters50d8d372001-02-28 05:34:27 +00001005 * case_ok() is used to implement case-sensitive import semantics even
1006 * on platforms with case-insensitive filesystems. It's trivial to implement
1007 * for case-sensitive filesystems. It's pretty much a cross-platform
1008 * nightmare for systems with case-insensitive filesystems.
1009 */
Guido van Rossum0980bd91998-02-13 17:18:36 +00001010
Tim Peters50d8d372001-02-28 05:34:27 +00001011/* First we may need a pile of platform-specific header files; the sequence
1012 * of #if's here should match the sequence in the body of case_ok().
1013 */
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001014#if defined(MS_WIN32) || defined(__CYGWIN__)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001015#include <windows.h>
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001016#ifdef __CYGWIN__
1017#include <sys/cygwin.h>
1018#endif
1019
Tim Peters50d8d372001-02-28 05:34:27 +00001020#elif defined(DJGPP)
1021#include <dir.h>
1022
1023#elif defined(macintosh)
1024#include <TextUtils.h>
1025#ifdef USE_GUSI1
1026#include "TFileSpec.h" /* for Path2FSSpec() */
1027#endif
1028
Tim Petersd1e87a82001-03-01 18:12:00 +00001029#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001030#include <sys/types.h>
1031#include <dirent.h>
1032
Tim Peters50d8d372001-02-28 05:34:27 +00001033#endif
1034
Guido van Rossum0980bd91998-02-13 17:18:36 +00001035static int
Tim Peters50d8d372001-02-28 05:34:27 +00001036case_ok(char *buf, int len, int namelen, char *name)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001037{
Tim Peters50d8d372001-02-28 05:34:27 +00001038/* Pick a platform-specific implementation; the sequence of #if's here should
1039 * match the sequence just above.
1040 */
1041
1042/* MS_WIN32 || __CYGWIN__ */
1043#if defined(MS_WIN32) || defined(__CYGWIN__)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001044 WIN32_FIND_DATA data;
1045 HANDLE h;
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001046#ifdef __CYGWIN__
1047 char tempbuf[MAX_PATH];
1048#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001049
Guido van Rossum0980bd91998-02-13 17:18:36 +00001050 if (getenv("PYTHONCASEOK") != NULL)
1051 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001052
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001053#ifdef __CYGWIN__
1054 cygwin32_conv_to_win32_path(buf, tempbuf);
1055 h = FindFirstFile(tempbuf, &data);
1056#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001057 h = FindFirstFile(buf, &data);
Guido van Rossum4c3f57c2001-01-10 20:40:46 +00001058#endif
Guido van Rossum0980bd91998-02-13 17:18:36 +00001059 if (h == INVALID_HANDLE_VALUE) {
1060 PyErr_Format(PyExc_NameError,
1061 "Can't find file for module %.100s\n(filename %.300s)",
1062 name, buf);
1063 return 0;
1064 }
1065 FindClose(h);
Tim Peters50d8d372001-02-28 05:34:27 +00001066 return strncmp(data.cFileName, name, namelen) == 0;
1067
1068/* DJGPP */
1069#elif defined(DJGPP)
1070 struct ffblk ffblk;
1071 int done;
1072
1073 if (getenv("PYTHONCASEOK") != NULL)
Guido van Rossum323bf5e1998-06-24 03:54:06 +00001074 return 1;
Tim Peters50d8d372001-02-28 05:34:27 +00001075
1076 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1077 if (done) {
Guido van Rossum0980bd91998-02-13 17:18:36 +00001078 PyErr_Format(PyExc_NameError,
Tim Peters50d8d372001-02-28 05:34:27 +00001079 "Can't find file for module %.100s\n(filename %.300s)",
Guido van Rossum0980bd91998-02-13 17:18:36 +00001080 name, buf);
1081 return 0;
1082 }
Tim Peters50d8d372001-02-28 05:34:27 +00001083 return strncmp(ffblk.ff_name, name, namelen) == 0;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001084
Tim Peters50d8d372001-02-28 05:34:27 +00001085/* macintosh */
1086#elif defined(macintosh)
Guido van Rossum0980bd91998-02-13 17:18:36 +00001087 FSSpec fss;
1088 OSErr err;
Tim Peters50d8d372001-02-28 05:34:27 +00001089
1090 if (getenv("PYTHONCASEOK") != NULL)
1091 return 1;
1092
Guido van Rossumb33aa1a2000-04-24 15:08:18 +00001093#ifndef USE_GUSI1
Guido van Rossuma0f0a331998-09-14 13:40:53 +00001094 err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
1095#else
1096 /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
1097 the way, which is fine for all directories, but here we need
1098 the original name of the alias file (say, Dlg.ppc.slb, not
1099 toolboxmodules.ppc.slb). */
1100 char *colon;
1101 err = Path2FSSpec(buf, &fss);
1102 if (err == noErr) {
1103 colon = strrchr(buf, ':'); /* find filename */
1104 if (colon != NULL)
1105 err = FSMakeFSSpec(fss.vRefNum, fss.parID,
1106 Pstring(colon+1), &fss);
1107 else
1108 err = FSMakeFSSpec(fss.vRefNum, fss.parID,
1109 fss.name, &fss);
1110 }
1111#endif
Guido van Rossum0980bd91998-02-13 17:18:36 +00001112 if (err) {
1113 PyErr_Format(PyExc_NameError,
Guido van Rossuma0f0a331998-09-14 13:40:53 +00001114 "Can't find file for module %.100s\n(filename %.300s)",
1115 name, buf);
Guido van Rossum0980bd91998-02-13 17:18:36 +00001116 return 0;
1117 }
Tim Peters50d8d372001-02-28 05:34:27 +00001118 return fss.name[0] >= namelen &&
1119 strncmp(name, (char *)fss.name+1, namelen) == 0;
1120
Tim Peters677898a2001-03-02 03:28:03 +00001121/* new-fangled macintosh (macosx) */
Tim Petersd1e87a82001-03-01 18:12:00 +00001122#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001123 DIR *dirp;
1124 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001125 char dirname[MAXPATHLEN + 1];
1126 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001127
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001128 if (getenv("PYTHONCASEOK") != NULL)
1129 return 1;
1130
Tim Petersd1e87a82001-03-01 18:12:00 +00001131 /* Copy the dir component into dirname; substitute "." if empty */
1132 if (dirlen <= 0) {
1133 dirname[0] = '.';
1134 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001135 }
1136 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001137 assert(dirlen <= MAXPATHLEN);
1138 memcpy(dirname, buf, dirlen);
1139 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001140 }
1141 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001142 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001143 if (dirp) {
Tim Peters677898a2001-03-02 03:28:03 +00001144 char *nameWithExt = buf + len - namelen;
Tim Peters430f5d42001-03-01 01:30:56 +00001145 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001146 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001147#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001148 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001149#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001150 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001151#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001152 if (thislen >= namelen &&
Tim Peters677898a2001-03-02 03:28:03 +00001153 strcmp(dp->d_name, nameWithExt) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001154 (void)closedir(dirp);
1155 return 1; /* Found */
1156 }
1157 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001158 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001159 }
Tim Peters430f5d42001-03-01 01:30:56 +00001160 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001161
Tim Peters50d8d372001-02-28 05:34:27 +00001162/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1163#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001164 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001165
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001166#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001167}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001168
Guido van Rossum0980bd91998-02-13 17:18:36 +00001169
Guido van Rossum197346f1997-10-31 18:38:52 +00001170#ifdef HAVE_STAT
1171/* Helper to look for __init__.py or __init__.py[co] in potential package */
1172static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001173find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001174{
Fred Drake4c82b232000-06-30 16:18:57 +00001175 size_t save_len = strlen(buf);
1176 size_t i = save_len;
Guido van Rossum197346f1997-10-31 18:38:52 +00001177 struct stat statbuf;
1178
1179 if (save_len + 13 >= MAXPATHLEN)
1180 return 0;
1181 buf[i++] = SEP;
1182 strcpy(buf+i, "__init__.py");
1183 if (stat(buf, &statbuf) == 0) {
1184 buf[save_len] = '\0';
1185 return 1;
1186 }
1187 i += strlen(buf+i);
1188 if (Py_OptimizeFlag)
1189 strcpy(buf+i, "o");
1190 else
1191 strcpy(buf+i, "c");
1192 if (stat(buf, &statbuf) == 0) {
1193 buf[save_len] = '\0';
1194 return 1;
1195 }
1196 buf[save_len] = '\0';
1197 return 0;
1198}
1199#endif /* HAVE_STAT */
1200
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001201
Tim Petersdbd9ba62000-07-09 03:09:57 +00001202static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001203
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001204/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001205 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001206
Guido van Rossum79f25d91997-04-29 20:08:16 +00001207static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001208load_module(char *name, FILE *fp, char *buf, int type)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001209{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001210 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001211 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001212 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001213
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001214 /* First check that there's an open file (if we need one) */
1215 switch (type) {
1216 case PY_SOURCE:
1217 case PY_COMPILED:
1218 if (fp == NULL) {
1219 PyErr_Format(PyExc_ValueError,
1220 "file object required for import (type code %d)",
1221 type);
1222 return NULL;
1223 }
1224 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001225
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001226 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001227
1228 case PY_SOURCE:
1229 m = load_source_module(name, buf, fp);
1230 break;
1231
1232 case PY_COMPILED:
1233 m = load_compiled_module(name, buf, fp);
1234 break;
1235
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001236#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001237 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001238 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001239 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001240#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001241
Jack Jansen9c96a921995-02-15 22:57:06 +00001242#ifdef macintosh
1243 case PY_RESOURCE:
1244 m = PyMac_LoadResourceModule(name, buf);
1245 break;
Guido van Rossum0f84a341998-08-06 13:36:01 +00001246 case PY_CODERESOURCE:
1247 m = PyMac_LoadCodeResourceModule(name, buf);
1248 break;
Jack Jansen9c96a921995-02-15 22:57:06 +00001249#endif
1250
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001251 case PKG_DIRECTORY:
1252 m = load_package(name, buf);
1253 break;
1254
1255 case C_BUILTIN:
1256 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001257 if (buf != NULL && buf[0] != '\0')
1258 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001259 if (type == C_BUILTIN)
1260 err = init_builtin(name);
1261 else
1262 err = PyImport_ImportFrozenModule(name);
1263 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001264 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001265 if (err == 0) {
1266 PyErr_Format(PyExc_ImportError,
1267 "Purported %s module %.200s not found",
1268 type == C_BUILTIN ?
1269 "builtin" : "frozen",
1270 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001271 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001272 }
1273 modules = PyImport_GetModuleDict();
1274 m = PyDict_GetItemString(modules, name);
1275 if (m == NULL) {
1276 PyErr_Format(
1277 PyExc_ImportError,
1278 "%s module %.200s not properly initialized",
1279 type == C_BUILTIN ?
1280 "builtin" : "frozen",
1281 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001282 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001283 }
1284 Py_INCREF(m);
1285 break;
1286
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001287 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001288 PyErr_Format(PyExc_ImportError,
1289 "Don't know how to import %.200s (type code %d)",
1290 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001291 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001292
1293 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001294
1295 return m;
1296}
1297
1298
1299/* Initialize a built-in module.
1300 Return 1 for succes, 0 if the module is not found, and -1 with
1301 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001302
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001303static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001304init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001305{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001306 struct _inittab *p;
1307 PyObject *mod;
1308
1309 if ((mod = _PyImport_FindExtension(name, name)) != NULL)
1310 return 1;
1311
Guido van Rossum771c6c81997-10-31 18:37:24 +00001312 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001313 if (strcmp(name, p->name) == 0) {
1314 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001315 PyErr_Format(PyExc_ImportError,
1316 "Cannot re-init internal module %.200s",
1317 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001318 return -1;
1319 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001320 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001321 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001322 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001323 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001324 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001325 if (_PyImport_FixupExtension(name, name) == NULL)
1326 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001327 return 1;
1328 }
1329 }
1330 return 0;
1331}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001332
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001333
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001334/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001335
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001336static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001337find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001338{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001339 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001340
Guido van Rossum79f25d91997-04-29 20:08:16 +00001341 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001342 if (p->name == NULL)
1343 return NULL;
1344 if (strcmp(p->name, name) == 0)
1345 break;
1346 }
1347 return p;
1348}
1349
Guido van Rossum79f25d91997-04-29 20:08:16 +00001350static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001351get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001352{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001353 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001354 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001355
1356 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001357 PyErr_Format(PyExc_ImportError,
1358 "No such frozen object named %.200s",
1359 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001360 return NULL;
1361 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001362 size = p->size;
1363 if (size < 0)
1364 size = -size;
1365 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001366}
1367
1368/* Initialize a frozen module.
1369 Return 1 for succes, 0 if the module is not found, and -1 with
1370 an exception set if the initialization failed.
1371 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001372
1373int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001374PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001375{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001376 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001377 PyObject *co;
1378 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001379 int ispackage;
1380 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001381
1382 if (p == NULL)
1383 return 0;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001384 size = p->size;
1385 ispackage = (size < 0);
1386 if (ispackage)
1387 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001388 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001389 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001390 name, ispackage ? " package" : "");
1391 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001392 if (co == NULL)
1393 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001394 if (!PyCode_Check(co)) {
1395 Py_DECREF(co);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001396 PyErr_Format(PyExc_TypeError,
1397 "frozen object %.200s is not a code object",
1398 name);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001399 return -1;
1400 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001401 if (ispackage) {
1402 /* Set __path__ to the package name */
1403 PyObject *d, *s;
1404 int err;
1405 m = PyImport_AddModule(name);
1406 if (m == NULL)
1407 return -1;
1408 d = PyModule_GetDict(m);
1409 s = PyString_InternFromString(name);
1410 if (s == NULL)
1411 return -1;
1412 err = PyDict_SetItemString(d, "__path__", s);
1413 Py_DECREF(s);
1414 if (err != 0)
1415 return err;
1416 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001417 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum79f25d91997-04-29 20:08:16 +00001418 Py_DECREF(co);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001419 if (m == NULL)
1420 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001421 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001422 return 1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001423}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001424
1425
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001426/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001427 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001428
Guido van Rossum79f25d91997-04-29 20:08:16 +00001429PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001430PyImport_ImportModule(char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001431{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001432 PyObject *pname;
1433 PyObject *result;
1434
1435 pname = PyString_FromString(name);
1436 result = PyImport_Import(pname);
1437 Py_DECREF(pname);
1438 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001439}
1440
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001441/* Forward declarations for helper routines */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001442static PyObject *get_parent(PyObject *globals, char *buf, int *p_buflen);
1443static PyObject *load_next(PyObject *mod, PyObject *altmod,
1444 char **p_name, char *buf, int *p_buflen);
1445static int mark_miss(char *name);
1446static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1447 char *buf, int buflen, int recursive);
1448static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001449
1450/* The Magnum Opus of dotted-name import :-) */
1451
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001452static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001453import_module_ex(char *name, PyObject *globals, PyObject *locals,
1454 PyObject *fromlist)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001455{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001456 char buf[MAXPATHLEN+1];
1457 int buflen = 0;
1458 PyObject *parent, *head, *next, *tail;
1459
1460 parent = get_parent(globals, buf, &buflen);
1461 if (parent == NULL)
1462 return NULL;
1463
1464 head = load_next(parent, Py_None, &name, buf, &buflen);
1465 if (head == NULL)
1466 return NULL;
1467
1468 tail = head;
1469 Py_INCREF(tail);
1470 while (name) {
1471 next = load_next(tail, tail, &name, buf, &buflen);
1472 Py_DECREF(tail);
1473 if (next == NULL) {
1474 Py_DECREF(head);
1475 return NULL;
1476 }
1477 tail = next;
1478 }
1479
1480 if (fromlist != NULL) {
1481 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1482 fromlist = NULL;
1483 }
1484
1485 if (fromlist == NULL) {
1486 Py_DECREF(tail);
1487 return head;
1488 }
1489
1490 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001491 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001492 Py_DECREF(tail);
1493 return NULL;
1494 }
1495
1496 return tail;
1497}
1498
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001499PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001500PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1501 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001502{
1503 PyObject *result;
1504 lock_import();
Guido van Rossumd65911b1998-03-03 22:33:27 +00001505 result = import_module_ex(name, globals, locals, fromlist);
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001506 unlock_import();
1507 return result;
1508}
1509
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001510static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001511get_parent(PyObject *globals, char *buf, int *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001512{
1513 static PyObject *namestr = NULL;
1514 static PyObject *pathstr = NULL;
1515 PyObject *modname, *modpath, *modules, *parent;
1516
1517 if (globals == NULL || !PyDict_Check(globals))
1518 return Py_None;
1519
1520 if (namestr == NULL) {
1521 namestr = PyString_InternFromString("__name__");
1522 if (namestr == NULL)
1523 return NULL;
1524 }
1525 if (pathstr == NULL) {
1526 pathstr = PyString_InternFromString("__path__");
1527 if (pathstr == NULL)
1528 return NULL;
1529 }
1530
1531 *buf = '\0';
1532 *p_buflen = 0;
1533 modname = PyDict_GetItem(globals, namestr);
1534 if (modname == NULL || !PyString_Check(modname))
1535 return Py_None;
1536
1537 modpath = PyDict_GetItem(globals, pathstr);
1538 if (modpath != NULL) {
1539 int len = PyString_GET_SIZE(modname);
1540 if (len > MAXPATHLEN) {
1541 PyErr_SetString(PyExc_ValueError,
1542 "Module name too long");
1543 return NULL;
1544 }
1545 strcpy(buf, PyString_AS_STRING(modname));
1546 *p_buflen = len;
1547 }
1548 else {
1549 char *start = PyString_AS_STRING(modname);
1550 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00001551 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001552 if (lastdot == NULL)
1553 return Py_None;
1554 len = lastdot - start;
1555 if (len >= MAXPATHLEN) {
1556 PyErr_SetString(PyExc_ValueError,
1557 "Module name too long");
1558 return NULL;
1559 }
1560 strncpy(buf, start, len);
1561 buf[len] = '\0';
1562 *p_buflen = len;
1563 }
1564
1565 modules = PyImport_GetModuleDict();
1566 parent = PyDict_GetItemString(modules, buf);
1567 if (parent == NULL)
1568 parent = Py_None;
1569 return parent;
1570 /* We expect, but can't guarantee, if parent != None, that:
1571 - parent.__name__ == buf
1572 - parent.__dict__ is globals
1573 If this is violated... Who cares? */
1574}
1575
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001576/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001577static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001578load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
1579 int *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001580{
1581 char *name = *p_name;
1582 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00001583 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001584 char *p;
1585 PyObject *result;
1586
1587 if (dot == NULL) {
1588 *p_name = NULL;
1589 len = strlen(name);
1590 }
1591 else {
1592 *p_name = dot+1;
1593 len = dot-name;
1594 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00001595 if (len == 0) {
1596 PyErr_SetString(PyExc_ValueError,
1597 "Empty module name");
1598 return NULL;
1599 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001600
1601 p = buf + *p_buflen;
1602 if (p != buf)
1603 *p++ = '.';
1604 if (p+len-buf >= MAXPATHLEN) {
1605 PyErr_SetString(PyExc_ValueError,
1606 "Module name too long");
1607 return NULL;
1608 }
1609 strncpy(p, name, len);
1610 p[len] = '\0';
1611 *p_buflen = p+len-buf;
1612
1613 result = import_submodule(mod, p, buf);
1614 if (result == Py_None && altmod != mod) {
1615 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00001616 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00001617 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00001618 if (result != NULL && result != Py_None) {
1619 if (mark_miss(buf) != 0) {
1620 Py_DECREF(result);
1621 return NULL;
1622 }
1623 strncpy(buf, name, len);
1624 buf[len] = '\0';
1625 *p_buflen = len;
1626 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001627 }
1628 if (result == NULL)
1629 return NULL;
1630
1631 if (result == Py_None) {
1632 Py_DECREF(result);
1633 PyErr_Format(PyExc_ImportError,
1634 "No module named %.200s", name);
1635 return NULL;
1636 }
1637
1638 return result;
1639}
1640
1641static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001642mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00001643{
1644 PyObject *modules = PyImport_GetModuleDict();
1645 return PyDict_SetItemString(modules, name, Py_None);
1646}
1647
1648static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001649ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen,
1650 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001651{
1652 int i;
1653
1654 if (!PyObject_HasAttrString(mod, "__path__"))
1655 return 1;
1656
1657 for (i = 0; ; i++) {
1658 PyObject *item = PySequence_GetItem(fromlist, i);
1659 int hasit;
1660 if (item == NULL) {
1661 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1662 PyErr_Clear();
1663 return 1;
1664 }
1665 return 0;
1666 }
1667 if (!PyString_Check(item)) {
1668 PyErr_SetString(PyExc_TypeError,
1669 "Item in ``from list'' not a string");
1670 Py_DECREF(item);
1671 return 0;
1672 }
1673 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00001674 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001675 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001676 /* See if the package defines __all__ */
1677 if (recursive)
1678 continue; /* Avoid endless recursion */
1679 all = PyObject_GetAttrString(mod, "__all__");
1680 if (all == NULL)
1681 PyErr_Clear();
1682 else {
1683 if (!ensure_fromlist(mod, all, buf, buflen, 1))
1684 return 0;
1685 Py_DECREF(all);
1686 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001687 continue;
1688 }
1689 hasit = PyObject_HasAttr(mod, item);
1690 if (!hasit) {
1691 char *subname = PyString_AS_STRING(item);
1692 PyObject *submod;
1693 char *p;
1694 if (buflen + strlen(subname) >= MAXPATHLEN) {
1695 PyErr_SetString(PyExc_ValueError,
1696 "Module name too long");
1697 Py_DECREF(item);
1698 return 0;
1699 }
1700 p = buf + buflen;
1701 *p++ = '.';
1702 strcpy(p, subname);
1703 submod = import_submodule(mod, subname, buf);
1704 Py_XDECREF(submod);
1705 if (submod == NULL) {
1706 Py_DECREF(item);
1707 return 0;
1708 }
1709 }
1710 Py_DECREF(item);
1711 }
1712
Guido van Rossuma7f2e811997-10-03 15:33:32 +00001713 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001714}
1715
1716static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001717import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001718{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001719 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001720 PyObject *m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00001721
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001722 /* Require:
1723 if mod == None: subname == fullname
1724 else: mod.__name__ + "." + subname == fullname
1725 */
1726
Tim Peters50d8d372001-02-28 05:34:27 +00001727 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001728 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001729 }
1730 else {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001731 PyObject *path;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001732 char buf[MAXPATHLEN+1];
1733 struct filedescr *fdp;
1734 FILE *fp = NULL;
1735
Guido van Rossum9c0afe51998-05-19 15:09:05 +00001736 if (mod == Py_None)
1737 path = NULL;
1738 else {
1739 path = PyObject_GetAttrString(mod, "__path__");
1740 if (path == NULL) {
1741 PyErr_Clear();
1742 Py_INCREF(Py_None);
1743 return Py_None;
1744 }
1745 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001746
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001747 buf[0] = '\0';
Guido van Rossumb68cd421998-07-01 17:36:26 +00001748 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1749 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001750 if (fdp == NULL) {
1751 if (!PyErr_ExceptionMatches(PyExc_ImportError))
1752 return NULL;
1753 PyErr_Clear();
1754 Py_INCREF(Py_None);
1755 return Py_None;
1756 }
1757 m = load_module(fullname, fp, buf, fdp->type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001758 if (fp)
1759 fclose(fp);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001760 if (m != NULL && mod != Py_None) {
1761 if (PyObject_SetAttrString(mod, subname, m) < 0) {
1762 Py_DECREF(m);
1763 m = NULL;
1764 }
1765 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00001766 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001767
1768 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00001769}
1770
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001771
1772/* Re-import a module of any kind and return its module object, WITH
1773 INCREMENTED REFERENCE COUNT */
1774
Guido van Rossum79f25d91997-04-29 20:08:16 +00001775PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001776PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001777{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001778 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum222ef561997-09-06 19:41:09 +00001779 PyObject *path = NULL;
1780 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001781 char buf[MAXPATHLEN+1];
1782 struct filedescr *fdp;
1783 FILE *fp = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001784
Guido van Rossum79f25d91997-04-29 20:08:16 +00001785 if (m == NULL || !PyModule_Check(m)) {
1786 PyErr_SetString(PyExc_TypeError,
1787 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001788 return NULL;
1789 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001790 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001791 if (name == NULL)
1792 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001793 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001794 PyErr_Format(PyExc_ImportError,
1795 "reload(): module %.200s not in sys.modules",
1796 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001797 return NULL;
1798 }
Guido van Rossum222ef561997-09-06 19:41:09 +00001799 subname = strrchr(name, '.');
1800 if (subname == NULL)
1801 subname = name;
1802 else {
1803 PyObject *parentname, *parent;
1804 parentname = PyString_FromStringAndSize(name, (subname-name));
1805 if (parentname == NULL)
1806 return NULL;
1807 parent = PyDict_GetItem(modules, parentname);
Barry Warsaw38793331999-01-27 17:54:20 +00001808 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00001809 if (parent == NULL) {
1810 PyErr_Format(PyExc_ImportError,
1811 "reload(): parent %.200s not in sys.modules",
1812 name);
1813 return NULL;
1814 }
1815 subname++;
1816 path = PyObject_GetAttrString(parent, "__path__");
1817 if (path == NULL)
1818 PyErr_Clear();
1819 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001820 buf[0] = '\0';
Guido van Rossum222ef561997-09-06 19:41:09 +00001821 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1822 Py_XDECREF(path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001823 if (fdp == NULL)
1824 return NULL;
1825 m = load_module(name, fp, buf, fdp->type);
1826 if (fp)
1827 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001828 return m;
1829}
1830
1831
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001832/* Higher-level import emulator which emulates the "import" statement
1833 more accurately -- it invokes the __import__() function from the
1834 builtins of the current globals. This means that the import is
1835 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00001836 environment, e.g. by "rexec".
1837 A dummy list ["__doc__"] is passed as the 4th argument so that
1838 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1839 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001840
1841PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001842PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001843{
1844 static PyObject *silly_list = NULL;
1845 static PyObject *builtins_str = NULL;
1846 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001847 PyObject *globals = NULL;
1848 PyObject *import = NULL;
1849 PyObject *builtins = NULL;
1850 PyObject *r = NULL;
1851
1852 /* Initialize constant string objects */
1853 if (silly_list == NULL) {
1854 import_str = PyString_InternFromString("__import__");
1855 if (import_str == NULL)
1856 return NULL;
1857 builtins_str = PyString_InternFromString("__builtins__");
1858 if (builtins_str == NULL)
1859 return NULL;
1860 silly_list = Py_BuildValue("[s]", "__doc__");
1861 if (silly_list == NULL)
1862 return NULL;
1863 }
1864
1865 /* Get the builtins from current globals */
1866 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00001867 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00001868 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001869 builtins = PyObject_GetItem(globals, builtins_str);
1870 if (builtins == NULL)
1871 goto err;
1872 }
1873 else {
1874 /* No globals -- use standard builtins, and fake globals */
1875 PyErr_Clear();
1876
Guido van Rossum85cd1d62001-02-20 21:43:24 +00001877 builtins = PyImport_ImportModuleEx("__builtin__",
1878 NULL, NULL, NULL);
1879 if (builtins == NULL)
1880 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001881 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1882 if (globals == NULL)
1883 goto err;
1884 }
1885
1886 /* Get the __import__ function from the builtins */
1887 if (PyDict_Check(builtins))
1888 import=PyObject_GetItem(builtins, import_str);
1889 else
1890 import=PyObject_GetAttr(builtins, import_str);
1891 if (import == NULL)
1892 goto err;
1893
1894 /* Call the _import__ function with the proper argument list */
1895 r = PyObject_CallFunction(import, "OOOO",
1896 module_name, globals, globals, silly_list);
1897
1898 err:
1899 Py_XDECREF(globals);
1900 Py_XDECREF(builtins);
1901 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001902
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001903 return r;
1904}
1905
1906
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001907/* Module 'imp' provides Python access to the primitives used for
1908 importing modules.
1909*/
1910
Guido van Rossum79f25d91997-04-29 20:08:16 +00001911static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001912imp_get_magic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001913{
1914 char buf[4];
1915
Guido van Rossum43713e52000-02-29 13:59:29 +00001916 if (!PyArg_ParseTuple(args, ":get_magic"))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001917 return NULL;
Guido van Rossum96774c12000-05-01 20:19:08 +00001918 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
1919 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
1920 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
1921 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001922
Guido van Rossum79f25d91997-04-29 20:08:16 +00001923 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001924}
1925
Guido van Rossum79f25d91997-04-29 20:08:16 +00001926static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001927imp_get_suffixes(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001928{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001929 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001930 struct filedescr *fdp;
1931
Guido van Rossum43713e52000-02-29 13:59:29 +00001932 if (!PyArg_ParseTuple(args, ":get_suffixes"))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001933 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001934 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001935 if (list == NULL)
1936 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001937 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1938 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001939 fdp->suffix, fdp->mode, fdp->type);
1940 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001941 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001942 return NULL;
1943 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001944 if (PyList_Append(list, item) < 0) {
1945 Py_DECREF(list);
1946 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001947 return NULL;
1948 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001949 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001950 }
1951 return list;
1952}
1953
Guido van Rossum79f25d91997-04-29 20:08:16 +00001954static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001955call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001956{
Tim Petersdbd9ba62000-07-09 03:09:57 +00001957 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001958 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001959 struct filedescr *fdp;
1960 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001961 FILE *fp = NULL;
1962
1963 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001964 if (path == Py_None)
1965 path = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001966 fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
1967 if (fdp == NULL)
1968 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001969 if (fp != NULL) {
1970 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
1971 if (fob == NULL) {
1972 fclose(fp);
1973 return NULL;
1974 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001975 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001976 else {
1977 fob = Py_None;
1978 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00001979 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001980 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001981 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001982 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001983 return ret;
1984}
1985
Guido van Rossum79f25d91997-04-29 20:08:16 +00001986static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001987imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001988{
1989 char *name;
1990 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00001991 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001992 return NULL;
1993 return call_find_module(name, path);
1994}
1995
1996static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001997imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001998{
1999 char *name;
2000 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002001 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002002 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002003 return NULL;
2004 ret = init_builtin(name);
2005 if (ret < 0)
2006 return NULL;
2007 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002008 Py_INCREF(Py_None);
2009 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002010 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002011 m = PyImport_AddModule(name);
2012 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002013 return m;
2014}
2015
Guido van Rossum79f25d91997-04-29 20:08:16 +00002016static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002017imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002018{
2019 char *name;
2020 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002021 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002022 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002023 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002024 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002025 if (ret < 0)
2026 return NULL;
2027 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002028 Py_INCREF(Py_None);
2029 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002030 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002031 m = PyImport_AddModule(name);
2032 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002033 return m;
2034}
2035
Guido van Rossum79f25d91997-04-29 20:08:16 +00002036static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002037imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002038{
2039 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002040
Guido van Rossum43713e52000-02-29 13:59:29 +00002041 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002042 return NULL;
2043 return get_frozen_object(name);
2044}
2045
Guido van Rossum79f25d91997-04-29 20:08:16 +00002046static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002047imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002048{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002049 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002050 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002051 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002052 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002053}
2054
Guido van Rossum79f25d91997-04-29 20:08:16 +00002055static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002056imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002057{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002058 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002059 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002060 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002061 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002062 p = find_frozen(name);
2063 return PyInt_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002064}
2065
2066static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002067get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002068{
2069 FILE *fp;
2070 if (fob == NULL) {
2071 fp = fopen(pathname, mode);
2072 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002073 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002074 }
2075 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002076 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002077 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002078 PyErr_SetString(PyExc_ValueError,
2079 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002080 }
2081 return fp;
2082}
2083
Guido van Rossum79f25d91997-04-29 20:08:16 +00002084static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002085imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002086{
2087 char *name;
2088 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002089 PyObject *fob = NULL;
2090 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002091 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002092 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002093 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002094 return NULL;
2095 fp = get_file(pathname, fob, "rb");
2096 if (fp == NULL)
2097 return NULL;
2098 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002099 if (fob == NULL)
2100 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002101 return m;
2102}
2103
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002104#ifdef HAVE_DYNAMIC_LOADING
2105
Guido van Rossum79f25d91997-04-29 20:08:16 +00002106static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002107imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002108{
2109 char *name;
2110 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002111 PyObject *fob = NULL;
2112 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002113 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002114 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002115 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002116 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002117 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002118 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002119 if (fp == NULL)
2120 return NULL;
2121 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002122 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002123 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002124}
2125
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002126#endif /* HAVE_DYNAMIC_LOADING */
2127
Guido van Rossum79f25d91997-04-29 20:08:16 +00002128static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002129imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002130{
2131 char *name;
2132 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002133 PyObject *fob = NULL;
2134 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002135 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002136 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002137 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002138 return NULL;
2139 fp = get_file(pathname, fob, "r");
2140 if (fp == NULL)
2141 return NULL;
2142 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002143 if (fob == NULL)
2144 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002145 return m;
2146}
2147
Jack Jansen9c96a921995-02-15 22:57:06 +00002148#ifdef macintosh
Guido van Rossum79f25d91997-04-29 20:08:16 +00002149static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002150imp_load_resource(PyObject *self, PyObject *args)
Jack Jansen9c96a921995-02-15 22:57:06 +00002151{
2152 char *name;
2153 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002154 PyObject *m;
Jack Jansen9c96a921995-02-15 22:57:06 +00002155
Guido van Rossum43713e52000-02-29 13:59:29 +00002156 if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname))
Jack Jansen9c96a921995-02-15 22:57:06 +00002157 return NULL;
2158 m = PyMac_LoadResourceModule(name, pathname);
2159 return m;
2160}
2161#endif /* macintosh */
2162
Guido van Rossum79f25d91997-04-29 20:08:16 +00002163static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002164imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002165{
2166 char *name;
2167 PyObject *fob;
2168 char *pathname;
2169 char *suffix; /* Unused */
2170 char *mode;
2171 int type;
2172 FILE *fp;
2173
Guido van Rossum43713e52000-02-29 13:59:29 +00002174 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002175 &name, &fob, &pathname,
2176 &suffix, &mode, &type))
2177 return NULL;
2178 if (*mode && (*mode != 'r' || strchr(mode, '+') != NULL)) {
2179 PyErr_Format(PyExc_ValueError,
2180 "invalid file open mode %.200s", mode);
2181 return NULL;
2182 }
2183 if (fob == Py_None)
2184 fp = NULL;
2185 else {
2186 if (!PyFile_Check(fob)) {
2187 PyErr_SetString(PyExc_ValueError,
2188 "load_module arg#2 should be a file or None");
2189 return NULL;
2190 }
2191 fp = get_file(pathname, fob, mode);
2192 if (fp == NULL)
2193 return NULL;
2194 }
2195 return load_module(name, fp, pathname, type);
2196}
2197
2198static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002199imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002200{
2201 char *name;
2202 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002203 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002204 return NULL;
2205 return load_package(name, pathname);
2206}
2207
2208static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002209imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002210{
2211 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002212 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002213 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002214 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002215}
2216
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002217/* Doc strings */
2218
2219static char doc_imp[] = "\
2220This module provides the components needed to build your own\n\
2221__import__ function. Undocumented functions are obsolete.\n\
2222";
2223
2224static char doc_find_module[] = "\
2225find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2226Search for a module. If path is omitted or None, search for a\n\
2227built-in, frozen or special module and continue search in sys.path.\n\
2228The module name cannot contain '.'; to search for a submodule of a\n\
2229package, pass the submodule name and the package's __path__.\
2230";
2231
2232static char doc_load_module[] = "\
2233load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2234Load a module, given information returned by find_module().\n\
2235The module name must include the full package name, if any.\
2236";
2237
2238static char doc_get_magic[] = "\
2239get_magic() -> string\n\
2240Return the magic number for .pyc or .pyo files.\
2241";
2242
2243static char doc_get_suffixes[] = "\
2244get_suffixes() -> [(suffix, mode, type), ...]\n\
2245Return a list of (suffix, mode, type) tuples describing the files\n\
2246that find_module() looks for.\
2247";
2248
2249static char doc_new_module[] = "\
2250new_module(name) -> module\n\
2251Create a new module. Do not enter it in sys.modules.\n\
2252The module name must include the full package name, if any.\
2253";
2254
Guido van Rossum79f25d91997-04-29 20:08:16 +00002255static PyMethodDef imp_methods[] = {
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002256 {"find_module", imp_find_module, 1, doc_find_module},
2257 {"get_magic", imp_get_magic, 1, doc_get_magic},
2258 {"get_suffixes", imp_get_suffixes, 1, doc_get_suffixes},
2259 {"load_module", imp_load_module, 1, doc_load_module},
2260 {"new_module", imp_new_module, 1, doc_new_module},
2261 /* The rest are obsolete */
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002262 {"get_frozen_object", imp_get_frozen_object, 1},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002263 {"init_builtin", imp_init_builtin, 1},
2264 {"init_frozen", imp_init_frozen, 1},
2265 {"is_builtin", imp_is_builtin, 1},
2266 {"is_frozen", imp_is_frozen, 1},
2267 {"load_compiled", imp_load_compiled, 1},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002268#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002269 {"load_dynamic", imp_load_dynamic, 1},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002270#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002271 {"load_package", imp_load_package, 1},
Jack Jansen9c96a921995-02-15 22:57:06 +00002272#ifdef macintosh
2273 {"load_resource", imp_load_resource, 1},
2274#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002275 {"load_source", imp_load_source, 1},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002276 {NULL, NULL} /* sentinel */
2277};
2278
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002279static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002280setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002281{
2282 PyObject *v;
2283 int err;
2284
2285 v = PyInt_FromLong((long)value);
2286 err = PyDict_SetItemString(d, name, v);
2287 Py_XDECREF(v);
2288 return err;
2289}
2290
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002291void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002292initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002293{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002294 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002295
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002296 m = Py_InitModule4("imp", imp_methods, doc_imp,
2297 NULL, PYTHON_API_VERSION);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002298 d = PyModule_GetDict(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002299
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002300 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2301 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2302 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2303 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2304 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2305 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2306 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2307 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00002308 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002309
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002310 failure:
2311 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002312}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002313
2314
Guido van Rossumb18618d2000-05-03 23:44:39 +00002315/* API for embedding applications that want to add their own entries
2316 to the table of built-in modules. This should normally be called
2317 *before* Py_Initialize(). When the table resize fails, -1 is
2318 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002319
2320 After a similar function by Just van Rossum. */
2321
2322int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002323PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002324{
2325 static struct _inittab *our_copy = NULL;
2326 struct _inittab *p;
2327 int i, n;
2328
2329 /* Count the number of entries in both tables */
2330 for (n = 0; newtab[n].name != NULL; n++)
2331 ;
2332 if (n == 0)
2333 return 0; /* Nothing to do */
2334 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2335 ;
2336
2337 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00002338 p = our_copy;
2339 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002340 if (p == NULL)
2341 return -1;
2342
2343 /* Copy the tables into the new memory */
2344 if (our_copy != PyImport_Inittab)
2345 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2346 PyImport_Inittab = our_copy = p;
2347 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2348
2349 return 0;
2350}
2351
2352/* Shorthand to add a single entry given a name and a function */
2353
2354int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002355PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002356{
2357 struct _inittab newtab[2];
2358
2359 memset(newtab, '\0', sizeof newtab);
2360
2361 newtab[0].name = name;
2362 newtab[0].initfunc = initfunc;
2363
2364 return PyImport_ExtendInittab(newtab);
2365}