blob: 86dd1345d34660c831b9a052dbec5bab25fc7524 [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 Petersd1e87a82001-03-01 18:12:00 +00001121/* new-fangled macintosh (macosx)
1122 *
1123 * XXX This seems prone to obscure errors, like suppose someone does
1124 * XXX "import xyz", and in some directory there's both "XYZ.py" and
1125 * XXX "xyz.txt". fopen("xyz.py") will open XYZ.py, but when marching thru
1126 * XXX the directory we'll eventually "succeed" on "xyz.txt" because the
1127 * XXX extension is never checked.
1128 */
1129#elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
Tim Peters430f5d42001-03-01 01:30:56 +00001130 DIR *dirp;
1131 struct dirent *dp;
Tim Petersd1e87a82001-03-01 18:12:00 +00001132 char dirname[MAXPATHLEN + 1];
1133 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
Tim Peters430f5d42001-03-01 01:30:56 +00001134
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001135 if (getenv("PYTHONCASEOK") != NULL)
1136 return 1;
1137
Tim Petersd1e87a82001-03-01 18:12:00 +00001138 /* Copy the dir component into dirname; substitute "." if empty */
1139 if (dirlen <= 0) {
1140 dirname[0] = '.';
1141 dirname[1] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001142 }
1143 else {
Tim Petersd1e87a82001-03-01 18:12:00 +00001144 assert(dirlen <= MAXPATHLEN);
1145 memcpy(dirname, buf, dirlen);
1146 dirname[dirlen] = '\0';
Tim Peters430f5d42001-03-01 01:30:56 +00001147 }
1148 /* Open the directory and search the entries for an exact match. */
Tim Petersd1e87a82001-03-01 18:12:00 +00001149 dirp = opendir(dirname);
Tim Peters430f5d42001-03-01 01:30:56 +00001150 if (dirp) {
1151 while ((dp = readdir(dirp)) != NULL) {
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001152 const int thislen =
Tim Peters430f5d42001-03-01 01:30:56 +00001153#ifdef _DIRENT_HAVE_D_NAMELEN
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001154 dp->d_namlen;
Tim Peters430f5d42001-03-01 01:30:56 +00001155#else
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001156 strlen(dp->d_name);
Tim Peters430f5d42001-03-01 01:30:56 +00001157#endif
Tim Petersd1e87a82001-03-01 18:12:00 +00001158 if (thislen >= namelen &&
1159 strncmp(dp->d_name, name, namelen) == 0) {
Tim Peters430f5d42001-03-01 01:30:56 +00001160 (void)closedir(dirp);
1161 return 1; /* Found */
1162 }
1163 }
Tim Petersdbe6ebb2001-03-01 08:47:29 +00001164 (void)closedir(dirp);
Tim Peters430f5d42001-03-01 01:30:56 +00001165 }
Tim Peters430f5d42001-03-01 01:30:56 +00001166 return 0 ; /* Not found */
Tim Peters430f5d42001-03-01 01:30:56 +00001167
Tim Peters50d8d372001-02-28 05:34:27 +00001168/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1169#else
Guido van Rossum0980bd91998-02-13 17:18:36 +00001170 return 1;
Guido van Rossum0980bd91998-02-13 17:18:36 +00001171
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001172#endif
Tim Peters50d8d372001-02-28 05:34:27 +00001173}
Guido van Rossum4d1b3b91998-02-13 23:27:59 +00001174
Guido van Rossum0980bd91998-02-13 17:18:36 +00001175
Guido van Rossum197346f1997-10-31 18:38:52 +00001176#ifdef HAVE_STAT
1177/* Helper to look for __init__.py or __init__.py[co] in potential package */
1178static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001179find_init_module(char *buf)
Guido van Rossum197346f1997-10-31 18:38:52 +00001180{
Fred Drake4c82b232000-06-30 16:18:57 +00001181 size_t save_len = strlen(buf);
1182 size_t i = save_len;
Guido van Rossum197346f1997-10-31 18:38:52 +00001183 struct stat statbuf;
1184
1185 if (save_len + 13 >= MAXPATHLEN)
1186 return 0;
1187 buf[i++] = SEP;
1188 strcpy(buf+i, "__init__.py");
1189 if (stat(buf, &statbuf) == 0) {
1190 buf[save_len] = '\0';
1191 return 1;
1192 }
1193 i += strlen(buf+i);
1194 if (Py_OptimizeFlag)
1195 strcpy(buf+i, "o");
1196 else
1197 strcpy(buf+i, "c");
1198 if (stat(buf, &statbuf) == 0) {
1199 buf[save_len] = '\0';
1200 return 1;
1201 }
1202 buf[save_len] = '\0';
1203 return 0;
1204}
1205#endif /* HAVE_STAT */
1206
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001207
Tim Petersdbd9ba62000-07-09 03:09:57 +00001208static int init_builtin(char *); /* Forward */
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001209
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001210/* Load an external module using the default search path and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001211 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001212
Guido van Rossum79f25d91997-04-29 20:08:16 +00001213static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001214load_module(char *name, FILE *fp, char *buf, int type)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001215{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001216 PyObject *modules;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001217 PyObject *m;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001218 int err;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001219
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001220 /* First check that there's an open file (if we need one) */
1221 switch (type) {
1222 case PY_SOURCE:
1223 case PY_COMPILED:
1224 if (fp == NULL) {
1225 PyErr_Format(PyExc_ValueError,
1226 "file object required for import (type code %d)",
1227 type);
1228 return NULL;
1229 }
1230 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001231
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001232 switch (type) {
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001233
1234 case PY_SOURCE:
1235 m = load_source_module(name, buf, fp);
1236 break;
1237
1238 case PY_COMPILED:
1239 m = load_compiled_module(name, buf, fp);
1240 break;
1241
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001242#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001243 case C_EXTENSION:
Guido van Rossum79f25d91997-04-29 20:08:16 +00001244 m = _PyImport_LoadDynamicModule(name, buf, fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001245 break;
Guido van Rossum96a8fb71999-12-22 14:09:35 +00001246#endif
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001247
Jack Jansen9c96a921995-02-15 22:57:06 +00001248#ifdef macintosh
1249 case PY_RESOURCE:
1250 m = PyMac_LoadResourceModule(name, buf);
1251 break;
Guido van Rossum0f84a341998-08-06 13:36:01 +00001252 case PY_CODERESOURCE:
1253 m = PyMac_LoadCodeResourceModule(name, buf);
1254 break;
Jack Jansen9c96a921995-02-15 22:57:06 +00001255#endif
1256
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001257 case PKG_DIRECTORY:
1258 m = load_package(name, buf);
1259 break;
1260
1261 case C_BUILTIN:
1262 case PY_FROZEN:
Guido van Rossuma5568d31998-03-05 03:45:08 +00001263 if (buf != NULL && buf[0] != '\0')
1264 name = buf;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001265 if (type == C_BUILTIN)
1266 err = init_builtin(name);
1267 else
1268 err = PyImport_ImportFrozenModule(name);
1269 if (err < 0)
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001270 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001271 if (err == 0) {
1272 PyErr_Format(PyExc_ImportError,
1273 "Purported %s module %.200s not found",
1274 type == C_BUILTIN ?
1275 "builtin" : "frozen",
1276 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001277 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001278 }
1279 modules = PyImport_GetModuleDict();
1280 m = PyDict_GetItemString(modules, name);
1281 if (m == NULL) {
1282 PyErr_Format(
1283 PyExc_ImportError,
1284 "%s module %.200s not properly initialized",
1285 type == C_BUILTIN ?
1286 "builtin" : "frozen",
1287 name);
Guido van Rossuma86f77d1997-09-09 18:53:47 +00001288 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001289 }
1290 Py_INCREF(m);
1291 break;
1292
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001293 default:
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001294 PyErr_Format(PyExc_ImportError,
1295 "Don't know how to import %.200s (type code %d)",
1296 name, type);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001297 m = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001298
1299 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001300
1301 return m;
1302}
1303
1304
1305/* Initialize a built-in module.
1306 Return 1 for succes, 0 if the module is not found, and -1 with
1307 an exception set if the initialization failed. */
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001308
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001309static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001310init_builtin(char *name)
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001311{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001312 struct _inittab *p;
1313 PyObject *mod;
1314
1315 if ((mod = _PyImport_FindExtension(name, name)) != NULL)
1316 return 1;
1317
Guido van Rossum771c6c81997-10-31 18:37:24 +00001318 for (p = PyImport_Inittab; p->name != NULL; p++) {
Guido van Rossum25ce5661997-08-02 03:10:38 +00001319 if (strcmp(name, p->name) == 0) {
1320 if (p->initfunc == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001321 PyErr_Format(PyExc_ImportError,
1322 "Cannot re-init internal module %.200s",
1323 name);
Guido van Rossum74e6a111994-08-29 12:54:38 +00001324 return -1;
1325 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001326 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001327 PySys_WriteStderr("import %s # builtin\n", name);
Guido van Rossum25ce5661997-08-02 03:10:38 +00001328 (*p->initfunc)();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001329 if (PyErr_Occurred())
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001330 return -1;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001331 if (_PyImport_FixupExtension(name, name) == NULL)
1332 return -1;
Guido van Rossum7f133ed1991-02-19 12:23:57 +00001333 return 1;
1334 }
1335 }
1336 return 0;
1337}
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001338
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001339
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001340/* Frozen modules */
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001341
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001342static struct _frozen *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001343find_frozen(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001344{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001345 struct _frozen *p;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001346
Guido van Rossum79f25d91997-04-29 20:08:16 +00001347 for (p = PyImport_FrozenModules; ; p++) {
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001348 if (p->name == NULL)
1349 return NULL;
1350 if (strcmp(p->name, name) == 0)
1351 break;
1352 }
1353 return p;
1354}
1355
Guido van Rossum79f25d91997-04-29 20:08:16 +00001356static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001357get_frozen_object(char *name)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001358{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001359 struct _frozen *p = find_frozen(name);
Guido van Rossuma5568d31998-03-05 03:45:08 +00001360 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001361
1362 if (p == NULL) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001363 PyErr_Format(PyExc_ImportError,
1364 "No such frozen object named %.200s",
1365 name);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001366 return NULL;
1367 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001368 size = p->size;
1369 if (size < 0)
1370 size = -size;
1371 return PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001372}
1373
1374/* Initialize a frozen module.
1375 Return 1 for succes, 0 if the module is not found, and -1 with
1376 an exception set if the initialization failed.
1377 This function is also used from frozenmain.c */
Guido van Rossum0b344901995-02-07 15:35:27 +00001378
1379int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001380PyImport_ImportFrozenModule(char *name)
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001381{
Guido van Rossumcfd0a221996-06-17 17:06:34 +00001382 struct _frozen *p = find_frozen(name);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001383 PyObject *co;
1384 PyObject *m;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001385 int ispackage;
1386 int size;
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00001387
1388 if (p == NULL)
1389 return 0;
Guido van Rossuma5568d31998-03-05 03:45:08 +00001390 size = p->size;
1391 ispackage = (size < 0);
1392 if (ispackage)
1393 size = -size;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001394 if (Py_VerboseFlag)
Guido van Rossum2f3667a1998-10-12 18:23:55 +00001395 PySys_WriteStderr("import %s # frozen%s\n",
Guido van Rossuma5568d31998-03-05 03:45:08 +00001396 name, ispackage ? " package" : "");
1397 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001398 if (co == NULL)
1399 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001400 if (!PyCode_Check(co)) {
1401 Py_DECREF(co);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001402 PyErr_Format(PyExc_TypeError,
1403 "frozen object %.200s is not a code object",
1404 name);
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001405 return -1;
1406 }
Guido van Rossuma5568d31998-03-05 03:45:08 +00001407 if (ispackage) {
1408 /* Set __path__ to the package name */
1409 PyObject *d, *s;
1410 int err;
1411 m = PyImport_AddModule(name);
1412 if (m == NULL)
1413 return -1;
1414 d = PyModule_GetDict(m);
1415 s = PyString_InternFromString(name);
1416 if (s == NULL)
1417 return -1;
1418 err = PyDict_SetItemString(d, "__path__", s);
1419 Py_DECREF(s);
1420 if (err != 0)
1421 return err;
1422 }
Guido van Rossume32bf6e1998-02-11 05:53:02 +00001423 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
Guido van Rossum79f25d91997-04-29 20:08:16 +00001424 Py_DECREF(co);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001425 if (m == NULL)
1426 return -1;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001427 Py_DECREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001428 return 1;
Guido van Rossumf56e3db1993-04-01 20:59:32 +00001429}
Guido van Rossum74e6a111994-08-29 12:54:38 +00001430
1431
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001432/* Import a module, either built-in, frozen, or external, and return
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001433 its module object WITH INCREMENTED REFERENCE COUNT */
Guido van Rossum74e6a111994-08-29 12:54:38 +00001434
Guido van Rossum79f25d91997-04-29 20:08:16 +00001435PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001436PyImport_ImportModule(char *name)
Guido van Rossum74e6a111994-08-29 12:54:38 +00001437{
Marc-André Lemburg3c61c352001-02-09 19:40:15 +00001438 PyObject *pname;
1439 PyObject *result;
1440
1441 pname = PyString_FromString(name);
1442 result = PyImport_Import(pname);
1443 Py_DECREF(pname);
1444 return result;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001445}
1446
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001447/* Forward declarations for helper routines */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001448static PyObject *get_parent(PyObject *globals, char *buf, int *p_buflen);
1449static PyObject *load_next(PyObject *mod, PyObject *altmod,
1450 char **p_name, char *buf, int *p_buflen);
1451static int mark_miss(char *name);
1452static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1453 char *buf, int buflen, int recursive);
1454static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001455
1456/* The Magnum Opus of dotted-name import :-) */
1457
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001458static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001459import_module_ex(char *name, PyObject *globals, PyObject *locals,
1460 PyObject *fromlist)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001461{
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001462 char buf[MAXPATHLEN+1];
1463 int buflen = 0;
1464 PyObject *parent, *head, *next, *tail;
1465
1466 parent = get_parent(globals, buf, &buflen);
1467 if (parent == NULL)
1468 return NULL;
1469
1470 head = load_next(parent, Py_None, &name, buf, &buflen);
1471 if (head == NULL)
1472 return NULL;
1473
1474 tail = head;
1475 Py_INCREF(tail);
1476 while (name) {
1477 next = load_next(tail, tail, &name, buf, &buflen);
1478 Py_DECREF(tail);
1479 if (next == NULL) {
1480 Py_DECREF(head);
1481 return NULL;
1482 }
1483 tail = next;
1484 }
1485
1486 if (fromlist != NULL) {
1487 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1488 fromlist = NULL;
1489 }
1490
1491 if (fromlist == NULL) {
1492 Py_DECREF(tail);
1493 return head;
1494 }
1495
1496 Py_DECREF(head);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001497 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001498 Py_DECREF(tail);
1499 return NULL;
1500 }
1501
1502 return tail;
1503}
1504
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001505PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001506PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1507 PyObject *fromlist)
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001508{
1509 PyObject *result;
1510 lock_import();
Guido van Rossumd65911b1998-03-03 22:33:27 +00001511 result = import_module_ex(name, globals, locals, fromlist);
Guido van Rossum75acc9c1998-03-03 22:26:50 +00001512 unlock_import();
1513 return result;
1514}
1515
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001516static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001517get_parent(PyObject *globals, char *buf, int *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001518{
1519 static PyObject *namestr = NULL;
1520 static PyObject *pathstr = NULL;
1521 PyObject *modname, *modpath, *modules, *parent;
1522
1523 if (globals == NULL || !PyDict_Check(globals))
1524 return Py_None;
1525
1526 if (namestr == NULL) {
1527 namestr = PyString_InternFromString("__name__");
1528 if (namestr == NULL)
1529 return NULL;
1530 }
1531 if (pathstr == NULL) {
1532 pathstr = PyString_InternFromString("__path__");
1533 if (pathstr == NULL)
1534 return NULL;
1535 }
1536
1537 *buf = '\0';
1538 *p_buflen = 0;
1539 modname = PyDict_GetItem(globals, namestr);
1540 if (modname == NULL || !PyString_Check(modname))
1541 return Py_None;
1542
1543 modpath = PyDict_GetItem(globals, pathstr);
1544 if (modpath != NULL) {
1545 int len = PyString_GET_SIZE(modname);
1546 if (len > MAXPATHLEN) {
1547 PyErr_SetString(PyExc_ValueError,
1548 "Module name too long");
1549 return NULL;
1550 }
1551 strcpy(buf, PyString_AS_STRING(modname));
1552 *p_buflen = len;
1553 }
1554 else {
1555 char *start = PyString_AS_STRING(modname);
1556 char *lastdot = strrchr(start, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00001557 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001558 if (lastdot == NULL)
1559 return Py_None;
1560 len = lastdot - start;
1561 if (len >= MAXPATHLEN) {
1562 PyErr_SetString(PyExc_ValueError,
1563 "Module name too long");
1564 return NULL;
1565 }
1566 strncpy(buf, start, len);
1567 buf[len] = '\0';
1568 *p_buflen = len;
1569 }
1570
1571 modules = PyImport_GetModuleDict();
1572 parent = PyDict_GetItemString(modules, buf);
1573 if (parent == NULL)
1574 parent = Py_None;
1575 return parent;
1576 /* We expect, but can't guarantee, if parent != None, that:
1577 - parent.__name__ == buf
1578 - parent.__dict__ is globals
1579 If this is violated... Who cares? */
1580}
1581
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001582/* altmod is either None or same as mod */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001583static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001584load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
1585 int *p_buflen)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001586{
1587 char *name = *p_name;
1588 char *dot = strchr(name, '.');
Fred Drake4c82b232000-06-30 16:18:57 +00001589 size_t len;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001590 char *p;
1591 PyObject *result;
1592
1593 if (dot == NULL) {
1594 *p_name = NULL;
1595 len = strlen(name);
1596 }
1597 else {
1598 *p_name = dot+1;
1599 len = dot-name;
1600 }
Guido van Rossum111c20b1998-04-11 17:38:22 +00001601 if (len == 0) {
1602 PyErr_SetString(PyExc_ValueError,
1603 "Empty module name");
1604 return NULL;
1605 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001606
1607 p = buf + *p_buflen;
1608 if (p != buf)
1609 *p++ = '.';
1610 if (p+len-buf >= MAXPATHLEN) {
1611 PyErr_SetString(PyExc_ValueError,
1612 "Module name too long");
1613 return NULL;
1614 }
1615 strncpy(p, name, len);
1616 p[len] = '\0';
1617 *p_buflen = p+len-buf;
1618
1619 result = import_submodule(mod, p, buf);
1620 if (result == Py_None && altmod != mod) {
1621 Py_DECREF(result);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00001622 /* Here, altmod must be None and mod must not be None */
Guido van Rossum0c819451997-09-07 06:16:57 +00001623 result = import_submodule(altmod, p, p);
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00001624 if (result != NULL && result != Py_None) {
1625 if (mark_miss(buf) != 0) {
1626 Py_DECREF(result);
1627 return NULL;
1628 }
1629 strncpy(buf, name, len);
1630 buf[len] = '\0';
1631 *p_buflen = len;
1632 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001633 }
1634 if (result == NULL)
1635 return NULL;
1636
1637 if (result == Py_None) {
1638 Py_DECREF(result);
1639 PyErr_Format(PyExc_ImportError,
1640 "No module named %.200s", name);
1641 return NULL;
1642 }
1643
1644 return result;
1645}
1646
1647static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001648mark_miss(char *name)
Guido van Rossumf5f5fdb1997-09-06 20:29:52 +00001649{
1650 PyObject *modules = PyImport_GetModuleDict();
1651 return PyDict_SetItemString(modules, name, Py_None);
1652}
1653
1654static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001655ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen,
1656 int recursive)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001657{
1658 int i;
1659
1660 if (!PyObject_HasAttrString(mod, "__path__"))
1661 return 1;
1662
1663 for (i = 0; ; i++) {
1664 PyObject *item = PySequence_GetItem(fromlist, i);
1665 int hasit;
1666 if (item == NULL) {
1667 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1668 PyErr_Clear();
1669 return 1;
1670 }
1671 return 0;
1672 }
1673 if (!PyString_Check(item)) {
1674 PyErr_SetString(PyExc_TypeError,
1675 "Item in ``from list'' not a string");
1676 Py_DECREF(item);
1677 return 0;
1678 }
1679 if (PyString_AS_STRING(item)[0] == '*') {
Guido van Rossum9905ef91997-09-08 16:07:11 +00001680 PyObject *all;
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001681 Py_DECREF(item);
Guido van Rossum9905ef91997-09-08 16:07:11 +00001682 /* See if the package defines __all__ */
1683 if (recursive)
1684 continue; /* Avoid endless recursion */
1685 all = PyObject_GetAttrString(mod, "__all__");
1686 if (all == NULL)
1687 PyErr_Clear();
1688 else {
1689 if (!ensure_fromlist(mod, all, buf, buflen, 1))
1690 return 0;
1691 Py_DECREF(all);
1692 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001693 continue;
1694 }
1695 hasit = PyObject_HasAttr(mod, item);
1696 if (!hasit) {
1697 char *subname = PyString_AS_STRING(item);
1698 PyObject *submod;
1699 char *p;
1700 if (buflen + strlen(subname) >= MAXPATHLEN) {
1701 PyErr_SetString(PyExc_ValueError,
1702 "Module name too long");
1703 Py_DECREF(item);
1704 return 0;
1705 }
1706 p = buf + buflen;
1707 *p++ = '.';
1708 strcpy(p, subname);
1709 submod = import_submodule(mod, subname, buf);
1710 Py_XDECREF(submod);
1711 if (submod == NULL) {
1712 Py_DECREF(item);
1713 return 0;
1714 }
1715 }
1716 Py_DECREF(item);
1717 }
1718
Guido van Rossuma7f2e811997-10-03 15:33:32 +00001719 /* NOTREACHED */
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001720}
1721
1722static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001723import_submodule(PyObject *mod, char *subname, char *fullname)
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001724{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001725 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum79f25d91997-04-29 20:08:16 +00001726 PyObject *m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00001727
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001728 /* Require:
1729 if mod == None: subname == fullname
1730 else: mod.__name__ + "." + subname == fullname
1731 */
1732
Tim Peters50d8d372001-02-28 05:34:27 +00001733 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001734 Py_INCREF(m);
Guido van Rossum7f9fa971995-01-20 16:53:12 +00001735 }
1736 else {
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001737 PyObject *path;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001738 char buf[MAXPATHLEN+1];
1739 struct filedescr *fdp;
1740 FILE *fp = NULL;
1741
Guido van Rossum9c0afe51998-05-19 15:09:05 +00001742 if (mod == Py_None)
1743 path = NULL;
1744 else {
1745 path = PyObject_GetAttrString(mod, "__path__");
1746 if (path == NULL) {
1747 PyErr_Clear();
1748 Py_INCREF(Py_None);
1749 return Py_None;
1750 }
1751 }
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001752
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001753 buf[0] = '\0';
Guido van Rossumb68cd421998-07-01 17:36:26 +00001754 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1755 Py_XDECREF(path);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001756 if (fdp == NULL) {
1757 if (!PyErr_ExceptionMatches(PyExc_ImportError))
1758 return NULL;
1759 PyErr_Clear();
1760 Py_INCREF(Py_None);
1761 return Py_None;
1762 }
1763 m = load_module(fullname, fp, buf, fdp->type);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001764 if (fp)
1765 fclose(fp);
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001766 if (m != NULL && mod != Py_None) {
1767 if (PyObject_SetAttrString(mod, subname, m) < 0) {
1768 Py_DECREF(m);
1769 m = NULL;
1770 }
1771 }
Guido van Rossum74e6a111994-08-29 12:54:38 +00001772 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001773
1774 return m;
Guido van Rossum74e6a111994-08-29 12:54:38 +00001775}
1776
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001777
1778/* Re-import a module of any kind and return its module object, WITH
1779 INCREMENTED REFERENCE COUNT */
1780
Guido van Rossum79f25d91997-04-29 20:08:16 +00001781PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001782PyImport_ReloadModule(PyObject *m)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001783{
Guido van Rossum25ce5661997-08-02 03:10:38 +00001784 PyObject *modules = PyImport_GetModuleDict();
Guido van Rossum222ef561997-09-06 19:41:09 +00001785 PyObject *path = NULL;
1786 char *name, *subname;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001787 char buf[MAXPATHLEN+1];
1788 struct filedescr *fdp;
1789 FILE *fp = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001790
Guido van Rossum79f25d91997-04-29 20:08:16 +00001791 if (m == NULL || !PyModule_Check(m)) {
1792 PyErr_SetString(PyExc_TypeError,
1793 "reload() argument must be module");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001794 return NULL;
1795 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001796 name = PyModule_GetName(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001797 if (name == NULL)
1798 return NULL;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001799 if (m != PyDict_GetItemString(modules, name)) {
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001800 PyErr_Format(PyExc_ImportError,
1801 "reload(): module %.200s not in sys.modules",
1802 name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001803 return NULL;
1804 }
Guido van Rossum222ef561997-09-06 19:41:09 +00001805 subname = strrchr(name, '.');
1806 if (subname == NULL)
1807 subname = name;
1808 else {
1809 PyObject *parentname, *parent;
1810 parentname = PyString_FromStringAndSize(name, (subname-name));
1811 if (parentname == NULL)
1812 return NULL;
1813 parent = PyDict_GetItem(modules, parentname);
Barry Warsaw38793331999-01-27 17:54:20 +00001814 Py_DECREF(parentname);
Guido van Rossum222ef561997-09-06 19:41:09 +00001815 if (parent == NULL) {
1816 PyErr_Format(PyExc_ImportError,
1817 "reload(): parent %.200s not in sys.modules",
1818 name);
1819 return NULL;
1820 }
1821 subname++;
1822 path = PyObject_GetAttrString(parent, "__path__");
1823 if (path == NULL)
1824 PyErr_Clear();
1825 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001826 buf[0] = '\0';
Guido van Rossum222ef561997-09-06 19:41:09 +00001827 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1828 Py_XDECREF(path);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001829 if (fdp == NULL)
1830 return NULL;
1831 m = load_module(name, fp, buf, fdp->type);
1832 if (fp)
1833 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001834 return m;
1835}
1836
1837
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001838/* Higher-level import emulator which emulates the "import" statement
1839 more accurately -- it invokes the __import__() function from the
1840 builtins of the current globals. This means that the import is
1841 done using whatever import hooks are installed in the current
Guido van Rossum6058eb41998-12-21 19:51:00 +00001842 environment, e.g. by "rexec".
1843 A dummy list ["__doc__"] is passed as the 4th argument so that
1844 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1845 will return <module "gencache"> instead of <module "win32com">. */
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001846
1847PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001848PyImport_Import(PyObject *module_name)
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001849{
1850 static PyObject *silly_list = NULL;
1851 static PyObject *builtins_str = NULL;
1852 static PyObject *import_str = NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001853 PyObject *globals = NULL;
1854 PyObject *import = NULL;
1855 PyObject *builtins = NULL;
1856 PyObject *r = NULL;
1857
1858 /* Initialize constant string objects */
1859 if (silly_list == NULL) {
1860 import_str = PyString_InternFromString("__import__");
1861 if (import_str == NULL)
1862 return NULL;
1863 builtins_str = PyString_InternFromString("__builtins__");
1864 if (builtins_str == NULL)
1865 return NULL;
1866 silly_list = Py_BuildValue("[s]", "__doc__");
1867 if (silly_list == NULL)
1868 return NULL;
1869 }
1870
1871 /* Get the builtins from current globals */
1872 globals = PyEval_GetGlobals();
Guido van Rossum85cd1d62001-02-20 21:43:24 +00001873 if (globals != NULL) {
Guido van Rossum66468561998-10-22 15:46:50 +00001874 Py_INCREF(globals);
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001875 builtins = PyObject_GetItem(globals, builtins_str);
1876 if (builtins == NULL)
1877 goto err;
1878 }
1879 else {
1880 /* No globals -- use standard builtins, and fake globals */
1881 PyErr_Clear();
1882
Guido van Rossum85cd1d62001-02-20 21:43:24 +00001883 builtins = PyImport_ImportModuleEx("__builtin__",
1884 NULL, NULL, NULL);
1885 if (builtins == NULL)
1886 return NULL;
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001887 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1888 if (globals == NULL)
1889 goto err;
1890 }
1891
1892 /* Get the __import__ function from the builtins */
1893 if (PyDict_Check(builtins))
1894 import=PyObject_GetItem(builtins, import_str);
1895 else
1896 import=PyObject_GetAttr(builtins, import_str);
1897 if (import == NULL)
1898 goto err;
1899
1900 /* Call the _import__ function with the proper argument list */
1901 r = PyObject_CallFunction(import, "OOOO",
1902 module_name, globals, globals, silly_list);
1903
1904 err:
1905 Py_XDECREF(globals);
1906 Py_XDECREF(builtins);
1907 Py_XDECREF(import);
Tim Peters50d8d372001-02-28 05:34:27 +00001908
Guido van Rossumd47a0a81997-08-14 20:11:26 +00001909 return r;
1910}
1911
1912
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001913/* Module 'imp' provides Python access to the primitives used for
1914 importing modules.
1915*/
1916
Guido van Rossum79f25d91997-04-29 20:08:16 +00001917static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001918imp_get_magic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001919{
1920 char buf[4];
1921
Guido van Rossum43713e52000-02-29 13:59:29 +00001922 if (!PyArg_ParseTuple(args, ":get_magic"))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001923 return NULL;
Guido van Rossum96774c12000-05-01 20:19:08 +00001924 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
1925 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
1926 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
1927 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001928
Guido van Rossum79f25d91997-04-29 20:08:16 +00001929 return PyString_FromStringAndSize(buf, 4);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001930}
1931
Guido van Rossum79f25d91997-04-29 20:08:16 +00001932static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001933imp_get_suffixes(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001934{
Guido van Rossum79f25d91997-04-29 20:08:16 +00001935 PyObject *list;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001936 struct filedescr *fdp;
1937
Guido van Rossum43713e52000-02-29 13:59:29 +00001938 if (!PyArg_ParseTuple(args, ":get_suffixes"))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001939 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001940 list = PyList_New(0);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001941 if (list == NULL)
1942 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00001943 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1944 PyObject *item = Py_BuildValue("ssi",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001945 fdp->suffix, fdp->mode, fdp->type);
1946 if (item == NULL) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00001947 Py_DECREF(list);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001948 return NULL;
1949 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001950 if (PyList_Append(list, item) < 0) {
1951 Py_DECREF(list);
1952 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001953 return NULL;
1954 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001955 Py_DECREF(item);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001956 }
1957 return list;
1958}
1959
Guido van Rossum79f25d91997-04-29 20:08:16 +00001960static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001961call_find_module(char *name, PyObject *path)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001962{
Tim Petersdbd9ba62000-07-09 03:09:57 +00001963 extern int fclose(FILE *);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001964 PyObject *fob, *ret;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001965 struct filedescr *fdp;
1966 char pathname[MAXPATHLEN+1];
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001967 FILE *fp = NULL;
1968
1969 pathname[0] = '\0';
Guido van Rossum17fc85f1997-09-06 18:52:03 +00001970 if (path == Py_None)
1971 path = NULL;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001972 fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
1973 if (fdp == NULL)
1974 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001975 if (fp != NULL) {
1976 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
1977 if (fob == NULL) {
1978 fclose(fp);
1979 return NULL;
1980 }
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001981 }
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001982 else {
1983 fob = Py_None;
1984 Py_INCREF(fob);
Tim Peters50d8d372001-02-28 05:34:27 +00001985 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00001986 ret = Py_BuildValue("Os(ssi)",
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001987 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
Guido van Rossum79f25d91997-04-29 20:08:16 +00001988 Py_DECREF(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00001989 return ret;
1990}
1991
Guido van Rossum79f25d91997-04-29 20:08:16 +00001992static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001993imp_find_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001994{
1995 char *name;
1996 PyObject *path = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00001997 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00001998 return NULL;
1999 return call_find_module(name, path);
2000}
2001
2002static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002003imp_init_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002004{
2005 char *name;
2006 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002007 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002008 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002009 return NULL;
2010 ret = init_builtin(name);
2011 if (ret < 0)
2012 return NULL;
2013 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002014 Py_INCREF(Py_None);
2015 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002016 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002017 m = PyImport_AddModule(name);
2018 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002019 return m;
2020}
2021
Guido van Rossum79f25d91997-04-29 20:08:16 +00002022static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002023imp_init_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002024{
2025 char *name;
2026 int ret;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002027 PyObject *m;
Guido van Rossum43713e52000-02-29 13:59:29 +00002028 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002029 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002030 ret = PyImport_ImportFrozenModule(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002031 if (ret < 0)
2032 return NULL;
2033 if (ret == 0) {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002034 Py_INCREF(Py_None);
2035 return Py_None;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002036 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002037 m = PyImport_AddModule(name);
2038 Py_XINCREF(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002039 return m;
2040}
2041
Guido van Rossum79f25d91997-04-29 20:08:16 +00002042static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002043imp_get_frozen_object(PyObject *self, PyObject *args)
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002044{
2045 char *name;
Jack Jansen95ffa231995-10-03 14:38:41 +00002046
Guido van Rossum43713e52000-02-29 13:59:29 +00002047 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002048 return NULL;
2049 return get_frozen_object(name);
2050}
2051
Guido van Rossum79f25d91997-04-29 20:08:16 +00002052static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002053imp_is_builtin(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002054{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002055 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002056 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002057 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002058 return PyInt_FromLong(is_builtin(name));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002059}
2060
Guido van Rossum79f25d91997-04-29 20:08:16 +00002061static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002062imp_is_frozen(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002063{
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002064 char *name;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002065 struct _frozen *p;
Guido van Rossum43713e52000-02-29 13:59:29 +00002066 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002067 return NULL;
Guido van Rossum323bf5e1998-06-24 03:54:06 +00002068 p = find_frozen(name);
2069 return PyInt_FromLong((long) (p == NULL ? 0 : p->size));
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002070}
2071
2072static FILE *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002073get_file(char *pathname, PyObject *fob, char *mode)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002074{
2075 FILE *fp;
2076 if (fob == NULL) {
2077 fp = fopen(pathname, mode);
2078 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002079 PyErr_SetFromErrno(PyExc_IOError);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002080 }
2081 else {
Guido van Rossum79f25d91997-04-29 20:08:16 +00002082 fp = PyFile_AsFile(fob);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002083 if (fp == NULL)
Guido van Rossum79f25d91997-04-29 20:08:16 +00002084 PyErr_SetString(PyExc_ValueError,
2085 "bad/closed file object");
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002086 }
2087 return fp;
2088}
2089
Guido van Rossum79f25d91997-04-29 20:08:16 +00002090static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002091imp_load_compiled(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002092{
2093 char *name;
2094 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002095 PyObject *fob = NULL;
2096 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002097 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002098 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002099 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002100 return NULL;
2101 fp = get_file(pathname, fob, "rb");
2102 if (fp == NULL)
2103 return NULL;
2104 m = load_compiled_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002105 if (fob == NULL)
2106 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002107 return m;
2108}
2109
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002110#ifdef HAVE_DYNAMIC_LOADING
2111
Guido van Rossum79f25d91997-04-29 20:08:16 +00002112static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002113imp_load_dynamic(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002114{
2115 char *name;
2116 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002117 PyObject *fob = NULL;
2118 PyObject *m;
Guido van Rossum7faeab31995-07-07 22:50:36 +00002119 FILE *fp = NULL;
Guido van Rossum43713e52000-02-29 13:59:29 +00002120 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002121 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002122 return NULL;
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002123 if (fob) {
Guido van Rossum7faeab31995-07-07 22:50:36 +00002124 fp = get_file(pathname, fob, "r");
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002125 if (fp == NULL)
2126 return NULL;
2127 }
Guido van Rossum79f25d91997-04-29 20:08:16 +00002128 m = _PyImport_LoadDynamicModule(name, pathname, fp);
Guido van Rossum7faeab31995-07-07 22:50:36 +00002129 return m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002130}
2131
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002132#endif /* HAVE_DYNAMIC_LOADING */
2133
Guido van Rossum79f25d91997-04-29 20:08:16 +00002134static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002135imp_load_source(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002136{
2137 char *name;
2138 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002139 PyObject *fob = NULL;
2140 PyObject *m;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002141 FILE *fp;
Guido van Rossum43713e52000-02-29 13:59:29 +00002142 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
Guido van Rossum79f25d91997-04-29 20:08:16 +00002143 &PyFile_Type, &fob))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002144 return NULL;
2145 fp = get_file(pathname, fob, "r");
2146 if (fp == NULL)
2147 return NULL;
2148 m = load_source_module(name, pathname, fp);
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002149 if (fob == NULL)
2150 fclose(fp);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002151 return m;
2152}
2153
Jack Jansen9c96a921995-02-15 22:57:06 +00002154#ifdef macintosh
Guido van Rossum79f25d91997-04-29 20:08:16 +00002155static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002156imp_load_resource(PyObject *self, PyObject *args)
Jack Jansen9c96a921995-02-15 22:57:06 +00002157{
2158 char *name;
2159 char *pathname;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002160 PyObject *m;
Jack Jansen9c96a921995-02-15 22:57:06 +00002161
Guido van Rossum43713e52000-02-29 13:59:29 +00002162 if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname))
Jack Jansen9c96a921995-02-15 22:57:06 +00002163 return NULL;
2164 m = PyMac_LoadResourceModule(name, pathname);
2165 return m;
2166}
2167#endif /* macintosh */
2168
Guido van Rossum79f25d91997-04-29 20:08:16 +00002169static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002170imp_load_module(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002171{
2172 char *name;
2173 PyObject *fob;
2174 char *pathname;
2175 char *suffix; /* Unused */
2176 char *mode;
2177 int type;
2178 FILE *fp;
2179
Guido van Rossum43713e52000-02-29 13:59:29 +00002180 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002181 &name, &fob, &pathname,
2182 &suffix, &mode, &type))
2183 return NULL;
2184 if (*mode && (*mode != 'r' || strchr(mode, '+') != NULL)) {
2185 PyErr_Format(PyExc_ValueError,
2186 "invalid file open mode %.200s", mode);
2187 return NULL;
2188 }
2189 if (fob == Py_None)
2190 fp = NULL;
2191 else {
2192 if (!PyFile_Check(fob)) {
2193 PyErr_SetString(PyExc_ValueError,
2194 "load_module arg#2 should be a file or None");
2195 return NULL;
2196 }
2197 fp = get_file(pathname, fob, mode);
2198 if (fp == NULL)
2199 return NULL;
2200 }
2201 return load_module(name, fp, pathname, type);
2202}
2203
2204static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002205imp_load_package(PyObject *self, PyObject *args)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002206{
2207 char *name;
2208 char *pathname;
Guido van Rossum43713e52000-02-29 13:59:29 +00002209 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002210 return NULL;
2211 return load_package(name, pathname);
2212}
2213
2214static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002215imp_new_module(PyObject *self, PyObject *args)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002216{
2217 char *name;
Guido van Rossum43713e52000-02-29 13:59:29 +00002218 if (!PyArg_ParseTuple(args, "s:new_module", &name))
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002219 return NULL;
Guido van Rossum79f25d91997-04-29 20:08:16 +00002220 return PyModule_New(name);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002221}
2222
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002223/* Doc strings */
2224
2225static char doc_imp[] = "\
2226This module provides the components needed to build your own\n\
2227__import__ function. Undocumented functions are obsolete.\n\
2228";
2229
2230static char doc_find_module[] = "\
2231find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2232Search for a module. If path is omitted or None, search for a\n\
2233built-in, frozen or special module and continue search in sys.path.\n\
2234The module name cannot contain '.'; to search for a submodule of a\n\
2235package, pass the submodule name and the package's __path__.\
2236";
2237
2238static char doc_load_module[] = "\
2239load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2240Load a module, given information returned by find_module().\n\
2241The module name must include the full package name, if any.\
2242";
2243
2244static char doc_get_magic[] = "\
2245get_magic() -> string\n\
2246Return the magic number for .pyc or .pyo files.\
2247";
2248
2249static char doc_get_suffixes[] = "\
2250get_suffixes() -> [(suffix, mode, type), ...]\n\
2251Return a list of (suffix, mode, type) tuples describing the files\n\
2252that find_module() looks for.\
2253";
2254
2255static char doc_new_module[] = "\
2256new_module(name) -> module\n\
2257Create a new module. Do not enter it in sys.modules.\n\
2258The module name must include the full package name, if any.\
2259";
2260
Guido van Rossum79f25d91997-04-29 20:08:16 +00002261static PyMethodDef imp_methods[] = {
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002262 {"find_module", imp_find_module, 1, doc_find_module},
2263 {"get_magic", imp_get_magic, 1, doc_get_magic},
2264 {"get_suffixes", imp_get_suffixes, 1, doc_get_suffixes},
2265 {"load_module", imp_load_module, 1, doc_load_module},
2266 {"new_module", imp_new_module, 1, doc_new_module},
2267 /* The rest are obsolete */
Guido van Rossum6ec1efb1995-08-04 04:08:57 +00002268 {"get_frozen_object", imp_get_frozen_object, 1},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002269 {"init_builtin", imp_init_builtin, 1},
2270 {"init_frozen", imp_init_frozen, 1},
2271 {"is_builtin", imp_is_builtin, 1},
2272 {"is_frozen", imp_is_frozen, 1},
2273 {"load_compiled", imp_load_compiled, 1},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002274#ifdef HAVE_DYNAMIC_LOADING
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002275 {"load_dynamic", imp_load_dynamic, 1},
Guido van Rossum96a8fb71999-12-22 14:09:35 +00002276#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002277 {"load_package", imp_load_package, 1},
Jack Jansen9c96a921995-02-15 22:57:06 +00002278#ifdef macintosh
2279 {"load_resource", imp_load_resource, 1},
2280#endif
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002281 {"load_source", imp_load_source, 1},
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002282 {NULL, NULL} /* sentinel */
2283};
2284
Guido van Rossum1a8791e1998-08-04 22:46:29 +00002285static int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002286setint(PyObject *d, char *name, int value)
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002287{
2288 PyObject *v;
2289 int err;
2290
2291 v = PyInt_FromLong((long)value);
2292 err = PyDict_SetItemString(d, name, v);
2293 Py_XDECREF(v);
2294 return err;
2295}
2296
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002297void
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002298initimp(void)
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002299{
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002300 PyObject *m, *d;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002301
Guido van Rossum0207e6d1997-09-09 22:04:42 +00002302 m = Py_InitModule4("imp", imp_methods, doc_imp,
2303 NULL, PYTHON_API_VERSION);
Guido van Rossum79f25d91997-04-29 20:08:16 +00002304 d = PyModule_GetDict(m);
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002305
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002306 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2307 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2308 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2309 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2310 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2311 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2312 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2313 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
Guido van Rossum0f84a341998-08-06 13:36:01 +00002314 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002315
Guido van Rossumaee0bad1997-09-05 07:33:22 +00002316 failure:
2317 ;
Guido van Rossum1ae940a1995-01-02 19:04:15 +00002318}
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002319
2320
Guido van Rossumb18618d2000-05-03 23:44:39 +00002321/* API for embedding applications that want to add their own entries
2322 to the table of built-in modules. This should normally be called
2323 *before* Py_Initialize(). When the table resize fails, -1 is
2324 returned and the existing table is unchanged.
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002325
2326 After a similar function by Just van Rossum. */
2327
2328int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002329PyImport_ExtendInittab(struct _inittab *newtab)
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002330{
2331 static struct _inittab *our_copy = NULL;
2332 struct _inittab *p;
2333 int i, n;
2334
2335 /* Count the number of entries in both tables */
2336 for (n = 0; newtab[n].name != NULL; n++)
2337 ;
2338 if (n == 0)
2339 return 0; /* Nothing to do */
2340 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2341 ;
2342
2343 /* Allocate new memory for the combined table */
Guido van Rossumb18618d2000-05-03 23:44:39 +00002344 p = our_copy;
2345 PyMem_RESIZE(p, struct _inittab, i+n+1);
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002346 if (p == NULL)
2347 return -1;
2348
2349 /* Copy the tables into the new memory */
2350 if (our_copy != PyImport_Inittab)
2351 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2352 PyImport_Inittab = our_copy = p;
2353 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2354
2355 return 0;
2356}
2357
2358/* Shorthand to add a single entry given a name and a function */
2359
2360int
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002361PyImport_AppendInittab(char *name, void (*initfunc)(void))
Guido van Rossum09cae1f1998-05-14 02:32:54 +00002362{
2363 struct _inittab newtab[2];
2364
2365 memset(newtab, '\0', sizeof newtab);
2366
2367 newtab[0].name = name;
2368 newtab[0].initfunc = initfunc;
2369
2370 return PyImport_ExtendInittab(newtab);
2371}