Added 'list_only' option (and modified 'run()' to respect it).
[python/dscho.git] / Python / import.c
blob851fd069306aec0eb940af6c5e2c0cb13cf35840
1 /***********************************************************
2 Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
3 The Netherlands.
5 All Rights Reserved
7 Permission to use, copy, modify, and distribute this software and its
8 documentation for any purpose and without fee is hereby granted,
9 provided that the above copyright notice appear in all copies and that
10 both that copyright notice and this permission notice appear in
11 supporting documentation, and that the names of Stichting Mathematisch
12 Centrum or CWI or Corporation for National Research Initiatives or
13 CNRI not be used in advertising or publicity pertaining to
14 distribution of the software without specific, written prior
15 permission.
17 While CWI is the initial source for this software, a modified version
18 is made available by the Corporation for National Research Initiatives
19 (CNRI) at the Internet address ftp://ftp.python.org.
21 STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
22 REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
23 MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
24 CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
25 DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
26 PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
27 TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
28 PERFORMANCE OF THIS SOFTWARE.
30 ******************************************************************/
32 /* Module definition and import implementation */
34 #include "Python.h"
36 #include "node.h"
37 #include "token.h"
38 #include "errcode.h"
39 #include "marshal.h"
40 #include "compile.h"
41 #include "eval.h"
42 #include "osdefs.h"
43 #include "importdl.h"
44 #ifdef macintosh
45 #include "macglue.h"
46 #endif
48 #ifdef HAVE_UNISTD_H
49 #include <unistd.h>
50 #endif
52 /* We expect that stat exists on most systems.
53 It's confirmed on Unix, Mac and Windows.
54 If you don't have it, add #define DONT_HAVE_STAT to your config.h. */
55 #ifndef DONT_HAVE_STAT
56 #define HAVE_STAT
58 #ifndef DONT_HAVE_SYS_TYPES_H
59 #include <sys/types.h>
60 #endif
61 #ifndef DONT_HAVE_SYS_STAT_H
62 #include <sys/stat.h>
63 #endif
65 #if defined(PYCC_VACPP)
66 /* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
67 #define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG)
68 #endif
70 #ifndef S_ISDIR
71 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
72 #endif
74 #endif
77 extern long PyOS_GetLastModificationTime(); /* In getmtime.c */
79 /* Magic word to reject .pyc files generated by other Python versions */
80 /* Change for each incompatible change */
81 /* The value of CR and LF is incorporated so if you ever read or write
82 a .pyc file in text mode the magic number will be wrong; also, the
83 Apple MPW compiler swaps their values, botching string constants */
84 /* XXX Perhaps the magic number should be frozen and a version field
85 added to the .pyc file header? */
86 /* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */
87 #define MAGIC (20121 | ((long)'\r'<<16) | ((long)'\n'<<24))
89 /* See _PyImport_FixupExtension() below */
90 static PyObject *extensions = NULL;
92 /* This table is defined in config.c: */
93 extern struct _inittab _PyImport_Inittab[];
95 struct _inittab *PyImport_Inittab = _PyImport_Inittab;
97 /* Initialize things */
99 void
100 _PyImport_Init()
102 if (Py_OptimizeFlag) {
103 /* Replace ".pyc" with ".pyo" in import_filetab */
104 struct filedescr *p;
105 for (p = _PyImport_Filetab; p->suffix != NULL; p++) {
106 if (strcmp(p->suffix, ".pyc") == 0)
107 p->suffix = ".pyo";
112 void
113 _PyImport_Fini()
115 Py_XDECREF(extensions);
116 extensions = NULL;
120 /* Locking primitives to prevent parallel imports of the same module
121 in different threads to return with a partially loaded module.
122 These calls are serialized by the global interpreter lock. */
124 #ifdef WITH_THREAD
126 #include "pythread.h"
128 static PyThread_type_lock import_lock = 0;
129 static long import_lock_thread = -1;
130 static int import_lock_level = 0;
132 static void
133 lock_import()
135 long me = PyThread_get_thread_ident();
136 if (me == -1)
137 return; /* Too bad */
138 if (import_lock == NULL)
139 import_lock = PyThread_allocate_lock();
140 if (import_lock_thread == me) {
141 import_lock_level++;
142 return;
144 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) {
145 PyThreadState *tstate = PyEval_SaveThread();
146 PyThread_acquire_lock(import_lock, 1);
147 PyEval_RestoreThread(tstate);
149 import_lock_thread = me;
150 import_lock_level = 1;
153 static void
154 unlock_import()
156 long me = PyThread_get_thread_ident();
157 if (me == -1)
158 return; /* Too bad */
159 if (import_lock_thread != me)
160 Py_FatalError("unlock_import: not holding the import lock");
161 import_lock_level--;
162 if (import_lock_level == 0) {
163 import_lock_thread = -1;
164 PyThread_release_lock(import_lock);
168 #else
170 #define lock_import()
171 #define unlock_import()
173 #endif
175 /* Helper for sys */
177 PyObject *
178 PyImport_GetModuleDict()
180 PyInterpreterState *interp = PyThreadState_Get()->interp;
181 if (interp->modules == NULL)
182 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
183 return interp->modules;
187 /* List of names to clear in sys */
188 static char* sys_deletes[] = {
189 "path", "argv", "ps1", "ps2", "exitfunc",
190 "exc_type", "exc_value", "exc_traceback",
191 "last_type", "last_value", "last_traceback",
192 NULL
195 static char* sys_files[] = {
196 "stdin", "__stdin__",
197 "stdout", "__stdout__",
198 "stderr", "__stderr__",
199 NULL
203 /* Un-initialize things, as good as we can */
205 void
206 PyImport_Cleanup()
208 int pos, ndone;
209 char *name;
210 PyObject *key, *value, *dict;
211 PyInterpreterState *interp = PyThreadState_Get()->interp;
212 PyObject *modules = interp->modules;
214 if (modules == NULL)
215 return; /* Already done */
217 /* Delete some special variables first. These are common
218 places where user values hide and people complain when their
219 destructors fail. Since the modules containing them are
220 deleted *last* of all, they would come too late in the normal
221 destruction order. Sigh. */
223 value = PyDict_GetItemString(modules, "__builtin__");
224 if (value != NULL && PyModule_Check(value)) {
225 dict = PyModule_GetDict(value);
226 if (Py_VerboseFlag)
227 PySys_WriteStderr("# clear __builtin__._\n");
228 PyDict_SetItemString(dict, "_", Py_None);
230 value = PyDict_GetItemString(modules, "sys");
231 if (value != NULL && PyModule_Check(value)) {
232 char **p;
233 PyObject *v;
234 dict = PyModule_GetDict(value);
235 for (p = sys_deletes; *p != NULL; p++) {
236 if (Py_VerboseFlag)
237 PySys_WriteStderr("# clear sys.%s\n", *p);
238 PyDict_SetItemString(dict, *p, Py_None);
240 for (p = sys_files; *p != NULL; p+=2) {
241 if (Py_VerboseFlag)
242 PySys_WriteStderr("# restore sys.%s\n", *p);
243 v = PyDict_GetItemString(dict, *(p+1));
244 if (v == NULL)
245 v = Py_None;
246 PyDict_SetItemString(dict, *p, v);
250 /* First, delete __main__ */
251 value = PyDict_GetItemString(modules, "__main__");
252 if (value != NULL && PyModule_Check(value)) {
253 if (Py_VerboseFlag)
254 PySys_WriteStderr("# cleanup __main__\n");
255 _PyModule_Clear(value);
256 PyDict_SetItemString(modules, "__main__", Py_None);
259 /* The special treatment of __builtin__ here is because even
260 when it's not referenced as a module, its dictionary is
261 referenced by almost every module's __builtins__. Since
262 deleting a module clears its dictionary (even if there are
263 references left to it), we need to delete the __builtin__
264 module last. Likewise, we don't delete sys until the very
265 end because it is implicitly referenced (e.g. by print).
267 Also note that we 'delete' modules by replacing their entry
268 in the modules dict with None, rather than really deleting
269 them; this avoids a rehash of the modules dictionary and
270 also marks them as "non existent" so they won't be
271 re-imported. */
273 /* Next, repeatedly delete modules with a reference count of
274 one (skipping __builtin__ and sys) and delete them */
275 do {
276 ndone = 0;
277 pos = 0;
278 while (PyDict_Next(modules, &pos, &key, &value)) {
279 if (value->ob_refcnt != 1)
280 continue;
281 if (PyString_Check(key) && PyModule_Check(value)) {
282 name = PyString_AS_STRING(key);
283 if (strcmp(name, "__builtin__") == 0)
284 continue;
285 if (strcmp(name, "sys") == 0)
286 continue;
287 if (Py_VerboseFlag)
288 PySys_WriteStderr(
289 "# cleanup[1] %s\n", name);
290 _PyModule_Clear(value);
291 PyDict_SetItem(modules, key, Py_None);
292 ndone++;
295 } while (ndone > 0);
297 /* Next, delete all modules (still skipping __builtin__ and sys) */
298 pos = 0;
299 while (PyDict_Next(modules, &pos, &key, &value)) {
300 if (PyString_Check(key) && PyModule_Check(value)) {
301 name = PyString_AS_STRING(key);
302 if (strcmp(name, "__builtin__") == 0)
303 continue;
304 if (strcmp(name, "sys") == 0)
305 continue;
306 if (Py_VerboseFlag)
307 PySys_WriteStderr("# cleanup[2] %s\n", name);
308 _PyModule_Clear(value);
309 PyDict_SetItem(modules, key, Py_None);
313 /* Next, delete sys and __builtin__ (in that order) */
314 value = PyDict_GetItemString(modules, "sys");
315 if (value != NULL && PyModule_Check(value)) {
316 if (Py_VerboseFlag)
317 PySys_WriteStderr("# cleanup sys\n");
318 _PyModule_Clear(value);
319 PyDict_SetItemString(modules, "sys", Py_None);
321 value = PyDict_GetItemString(modules, "__builtin__");
322 if (value != NULL && PyModule_Check(value)) {
323 if (Py_VerboseFlag)
324 PySys_WriteStderr("# cleanup __builtin__\n");
325 _PyModule_Clear(value);
326 PyDict_SetItemString(modules, "__builtin__", Py_None);
329 /* Finally, clear and delete the modules directory */
330 PyDict_Clear(modules);
331 interp->modules = NULL;
332 Py_DECREF(modules);
336 /* Helper for pythonrun.c -- return magic number */
338 long
339 PyImport_GetMagicNumber()
341 return MAGIC;
345 /* Magic for extension modules (built-in as well as dynamically
346 loaded). To prevent initializing an extension module more than
347 once, we keep a static dictionary 'extensions' keyed by module name
348 (for built-in modules) or by filename (for dynamically loaded
349 modules), containing these modules. A copy od the module's
350 dictionary is stored by calling _PyImport_FixupExtension()
351 immediately after the module initialization function succeeds. A
352 copy can be retrieved from there by calling
353 _PyImport_FindExtension(). */
355 PyObject *
356 _PyImport_FixupExtension(name, filename)
357 char *name;
358 char *filename;
360 PyObject *modules, *mod, *dict, *copy;
361 if (extensions == NULL) {
362 extensions = PyDict_New();
363 if (extensions == NULL)
364 return NULL;
366 modules = PyImport_GetModuleDict();
367 mod = PyDict_GetItemString(modules, name);
368 if (mod == NULL || !PyModule_Check(mod)) {
369 PyErr_Format(PyExc_SystemError,
370 "_PyImport_FixupExtension: module %.200s not loaded", name);
371 return NULL;
373 dict = PyModule_GetDict(mod);
374 if (dict == NULL)
375 return NULL;
376 copy = PyObject_CallMethod(dict, "copy", "");
377 if (copy == NULL)
378 return NULL;
379 PyDict_SetItemString(extensions, filename, copy);
380 Py_DECREF(copy);
381 return copy;
384 PyObject *
385 _PyImport_FindExtension(name, filename)
386 char *name;
387 char *filename;
389 PyObject *dict, *mod, *mdict, *result;
390 if (extensions == NULL)
391 return NULL;
392 dict = PyDict_GetItemString(extensions, filename);
393 if (dict == NULL)
394 return NULL;
395 mod = PyImport_AddModule(name);
396 if (mod == NULL)
397 return NULL;
398 mdict = PyModule_GetDict(mod);
399 if (mdict == NULL)
400 return NULL;
401 result = PyObject_CallMethod(mdict, "update", "O", dict);
402 if (result == NULL)
403 return NULL;
404 Py_DECREF(result);
405 if (Py_VerboseFlag)
406 PySys_WriteStderr("import %s # previously loaded (%s)\n",
407 name, filename);
408 return mod;
412 /* Get the module object corresponding to a module name.
413 First check the modules dictionary if there's one there,
414 if not, create a new one and insert in in the modules dictionary.
415 Because the former action is most common, THIS DOES NOT RETURN A
416 'NEW' REFERENCE! */
418 PyObject *
419 PyImport_AddModule(name)
420 char *name;
422 PyObject *modules = PyImport_GetModuleDict();
423 PyObject *m;
425 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
426 PyModule_Check(m))
427 return m;
428 m = PyModule_New(name);
429 if (m == NULL)
430 return NULL;
431 if (PyDict_SetItemString(modules, name, m) != 0) {
432 Py_DECREF(m);
433 return NULL;
435 Py_DECREF(m); /* Yes, it still exists, in modules! */
437 return m;
441 /* Execute a code object in a module and return the module object
442 WITH INCREMENTED REFERENCE COUNT */
444 PyObject *
445 PyImport_ExecCodeModule(name, co)
446 char *name;
447 PyObject *co;
449 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
452 PyObject *
453 PyImport_ExecCodeModuleEx(name, co, pathname)
454 char *name;
455 PyObject *co;
456 char *pathname;
458 PyObject *modules = PyImport_GetModuleDict();
459 PyObject *m, *d, *v;
461 m = PyImport_AddModule(name);
462 if (m == NULL)
463 return NULL;
464 d = PyModule_GetDict(m);
465 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
466 if (PyDict_SetItemString(d, "__builtins__",
467 PyEval_GetBuiltins()) != 0)
468 return NULL;
470 /* Remember the filename as the __file__ attribute */
471 v = NULL;
472 if (pathname != NULL) {
473 v = PyString_FromString(pathname);
474 if (v == NULL)
475 PyErr_Clear();
477 if (v == NULL) {
478 v = ((PyCodeObject *)co)->co_filename;
479 Py_INCREF(v);
481 if (PyDict_SetItemString(d, "__file__", v) != 0)
482 PyErr_Clear(); /* Not important enough to report */
483 Py_DECREF(v);
485 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
486 if (v == NULL)
487 return NULL;
488 Py_DECREF(v);
490 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
491 PyErr_Format(PyExc_ImportError,
492 "Loaded module %.200s not found in sys.modules",
493 name);
494 return NULL;
497 Py_INCREF(m);
499 return m;
503 /* Given a pathname for a Python source file, fill a buffer with the
504 pathname for the corresponding compiled file. Return the pathname
505 for the compiled file, or NULL if there's no space in the buffer.
506 Doesn't set an exception. */
508 static char *
509 make_compiled_pathname(pathname, buf, buflen)
510 char *pathname;
511 char *buf;
512 int buflen;
514 int len;
516 len = strlen(pathname);
517 if (len+2 > buflen)
518 return NULL;
519 strcpy(buf, pathname);
520 strcpy(buf+len, Py_OptimizeFlag ? "o" : "c");
522 return buf;
526 /* Given a pathname for a Python source file, its time of last
527 modification, and a pathname for a compiled file, check whether the
528 compiled file represents the same version of the source. If so,
529 return a FILE pointer for the compiled file, positioned just after
530 the header; if not, return NULL.
531 Doesn't set an exception. */
533 static FILE *
534 check_compiled_module(pathname, mtime, cpathname)
535 char *pathname;
536 long mtime;
537 char *cpathname;
539 FILE *fp;
540 long magic;
541 long pyc_mtime;
543 fp = fopen(cpathname, "rb");
544 if (fp == NULL)
545 return NULL;
546 magic = PyMarshal_ReadLongFromFile(fp);
547 if (magic != MAGIC) {
548 if (Py_VerboseFlag)
549 PySys_WriteStderr("# %s has bad magic\n", cpathname);
550 fclose(fp);
551 return NULL;
553 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
554 if (pyc_mtime != mtime) {
555 if (Py_VerboseFlag)
556 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
557 fclose(fp);
558 return NULL;
560 if (Py_VerboseFlag)
561 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
562 return fp;
566 /* Read a code object from a file and check it for validity */
568 static PyCodeObject *
569 read_compiled_module(cpathname, fp)
570 char *cpathname;
571 FILE *fp;
573 PyObject *co;
575 co = PyMarshal_ReadObjectFromFile(fp);
576 /* Ugly: rd_object() may return NULL with or without error */
577 if (co == NULL || !PyCode_Check(co)) {
578 if (!PyErr_Occurred())
579 PyErr_Format(PyExc_ImportError,
580 "Non-code object in %.200s", cpathname);
581 Py_XDECREF(co);
582 return NULL;
584 return (PyCodeObject *)co;
588 /* Load a module from a compiled file, execute it, and return its
589 module object WITH INCREMENTED REFERENCE COUNT */
591 static PyObject *
592 load_compiled_module(name, cpathname, fp)
593 char *name;
594 char *cpathname;
595 FILE *fp;
597 long magic;
598 PyCodeObject *co;
599 PyObject *m;
601 magic = PyMarshal_ReadLongFromFile(fp);
602 if (magic != MAGIC) {
603 PyErr_Format(PyExc_ImportError,
604 "Bad magic number in %.200s", cpathname);
605 return NULL;
607 (void) PyMarshal_ReadLongFromFile(fp);
608 co = read_compiled_module(cpathname, fp);
609 if (co == NULL)
610 return NULL;
611 if (Py_VerboseFlag)
612 PySys_WriteStderr("import %s # precompiled from %s\n",
613 name, cpathname);
614 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
615 Py_DECREF(co);
617 return m;
620 /* Parse a source file and return the corresponding code object */
622 static PyCodeObject *
623 parse_source_module(pathname, fp)
624 char *pathname;
625 FILE *fp;
627 PyCodeObject *co;
628 node *n;
630 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
631 if (n == NULL)
632 return NULL;
633 co = PyNode_Compile(n, pathname);
634 PyNode_Free(n);
636 return co;
640 /* Write a compiled module to a file, placing the time of last
641 modification of its source into the header.
642 Errors are ignored, if a write error occurs an attempt is made to
643 remove the file. */
645 static void
646 write_compiled_module(co, cpathname, mtime)
647 PyCodeObject *co;
648 char *cpathname;
649 long mtime;
651 FILE *fp;
653 fp = fopen(cpathname, "wb");
654 if (fp == NULL) {
655 if (Py_VerboseFlag)
656 PySys_WriteStderr(
657 "# can't create %s\n", cpathname);
658 return;
660 PyMarshal_WriteLongToFile(MAGIC, fp);
661 /* First write a 0 for mtime */
662 PyMarshal_WriteLongToFile(0L, fp);
663 PyMarshal_WriteObjectToFile((PyObject *)co, fp);
664 if (ferror(fp)) {
665 if (Py_VerboseFlag)
666 PySys_WriteStderr("# can't write %s\n", cpathname);
667 /* Don't keep partial file */
668 fclose(fp);
669 (void) unlink(cpathname);
670 return;
672 /* Now write the true mtime */
673 fseek(fp, 4L, 0);
674 PyMarshal_WriteLongToFile(mtime, fp);
675 fflush(fp);
676 fclose(fp);
677 if (Py_VerboseFlag)
678 PySys_WriteStderr("# wrote %s\n", cpathname);
679 #ifdef macintosh
680 setfiletype(cpathname, 'Pyth', 'PYC ');
681 #endif
685 /* Load a source module from a given file and return its module
686 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
687 byte-compiled file, use that instead. */
689 static PyObject *
690 load_source_module(name, pathname, fp)
691 char *name;
692 char *pathname;
693 FILE *fp;
695 long mtime;
696 FILE *fpc;
697 char buf[MAXPATHLEN+1];
698 char *cpathname;
699 PyCodeObject *co;
700 PyObject *m;
702 mtime = PyOS_GetLastModificationTime(pathname, fp);
703 cpathname = make_compiled_pathname(pathname, buf, MAXPATHLEN+1);
704 if (cpathname != NULL &&
705 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
706 co = read_compiled_module(cpathname, fpc);
707 fclose(fpc);
708 if (co == NULL)
709 return NULL;
710 if (Py_VerboseFlag)
711 PySys_WriteStderr("import %s # precompiled from %s\n",
712 name, cpathname);
713 pathname = cpathname;
715 else {
716 co = parse_source_module(pathname, fp);
717 if (co == NULL)
718 return NULL;
719 if (Py_VerboseFlag)
720 PySys_WriteStderr("import %s # from %s\n",
721 name, pathname);
722 write_compiled_module(co, cpathname, mtime);
724 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
725 Py_DECREF(co);
727 return m;
731 /* Forward */
732 static PyObject *load_module Py_PROTO((char *, FILE *, char *, int));
733 static struct filedescr *find_module Py_PROTO((char *, PyObject *,
734 char *, int, FILE **));
735 static struct _frozen *find_frozen Py_PROTO((char *name));
737 /* Load a package and return its module object WITH INCREMENTED
738 REFERENCE COUNT */
740 static PyObject *
741 load_package(name, pathname)
742 char *name;
743 char *pathname;
745 PyObject *m, *d, *file, *path;
746 int err;
747 char buf[MAXPATHLEN+1];
748 FILE *fp = NULL;
749 struct filedescr *fdp;
751 m = PyImport_AddModule(name);
752 if (m == NULL)
753 return NULL;
754 if (Py_VerboseFlag)
755 PySys_WriteStderr("import %s # directory %s\n",
756 name, pathname);
757 d = PyModule_GetDict(m);
758 file = PyString_FromString(pathname);
759 if (file == NULL)
760 return NULL;
761 path = Py_BuildValue("[O]", file);
762 if (path == NULL) {
763 Py_DECREF(file);
764 return NULL;
766 err = PyDict_SetItemString(d, "__file__", file);
767 if (err == 0)
768 err = PyDict_SetItemString(d, "__path__", path);
769 if (err != 0) {
770 m = NULL;
771 goto cleanup;
773 buf[0] = '\0';
774 fdp = find_module("__init__", path, buf, sizeof(buf), &fp);
775 if (fdp == NULL) {
776 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
777 PyErr_Clear();
779 else
780 m = NULL;
781 goto cleanup;
783 m = load_module(name, fp, buf, fdp->type);
784 if (fp != NULL)
785 fclose(fp);
786 cleanup:
787 Py_XDECREF(path);
788 Py_XDECREF(file);
789 return m;
793 /* Helper to test for built-in module */
795 static int
796 is_builtin(name)
797 char *name;
799 int i;
800 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
801 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
802 if (PyImport_Inittab[i].initfunc == NULL)
803 return -1;
804 else
805 return 1;
808 return 0;
812 /* Search the path (default sys.path) for a module. Return the
813 corresponding filedescr struct, and (via return arguments) the
814 pathname and an open file. Return NULL if the module is not found. */
816 #ifdef MS_COREDLL
817 extern FILE *PyWin_FindRegisteredModule();
818 #endif
820 #ifdef CHECK_IMPORT_CASE
821 static int check_case(char *, int, int, char *);
822 #endif
824 static int find_init_module Py_PROTO((char *)); /* Forward */
826 static struct filedescr *
827 find_module(realname, path, buf, buflen, p_fp)
828 char *realname;
829 PyObject *path;
830 /* Output parameters: */
831 char *buf;
832 int buflen;
833 FILE **p_fp;
835 int i, npath, len, namelen;
836 struct _frozen *f;
837 struct filedescr *fdp = NULL;
838 FILE *fp = NULL;
839 struct stat statbuf;
840 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
841 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
842 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
843 char name[MAXPATHLEN+1];
845 strcpy(name, realname);
847 if (path != NULL && PyString_Check(path)) {
848 /* Submodule of "frozen" package:
849 Set name to the fullname, path to NULL
850 and continue as "usual" */
851 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
852 PyErr_SetString(PyExc_ImportError,
853 "full frozen module name too long");
854 return NULL;
856 strcpy(buf, PyString_AsString(path));
857 strcat(buf, ".");
858 strcat(buf, name);
859 strcpy(name, buf);
860 path = NULL;
862 if (path == NULL) {
863 if (is_builtin(name)) {
864 strcpy(buf, name);
865 return &fd_builtin;
867 if ((f = find_frozen(name)) != NULL) {
868 strcpy(buf, name);
869 return &fd_frozen;
872 #ifdef MS_COREDLL
873 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
874 if (fp != NULL) {
875 *p_fp = fp;
876 return fdp;
878 #endif
879 path = PySys_GetObject("path");
881 if (path == NULL || !PyList_Check(path)) {
882 PyErr_SetString(PyExc_ImportError,
883 "sys.path must be a list of directory names");
884 return NULL;
886 npath = PyList_Size(path);
887 namelen = strlen(name);
888 for (i = 0; i < npath; i++) {
889 PyObject *v = PyList_GetItem(path, i);
890 if (!PyString_Check(v))
891 continue;
892 len = PyString_Size(v);
893 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen)
894 continue; /* Too long */
895 strcpy(buf, PyString_AsString(v));
896 if ((int)strlen(buf) != len)
897 continue; /* v contains '\0' */
898 #ifdef macintosh
899 #ifdef INTERN_STRINGS
901 ** Speedup: each sys.path item is interned, and
902 ** FindResourceModule remembers which items refer to
903 ** folders (so we don't have to bother trying to look
904 ** into them for resources).
906 PyString_InternInPlace(&PyList_GET_ITEM(path, i));
907 v = PyList_GET_ITEM(path, i);
908 #endif
909 if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
910 static struct filedescr resfiledescr =
911 {"", "", PY_RESOURCE};
913 return &resfiledescr;
915 if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
916 static struct filedescr resfiledescr =
917 {"", "", PY_CODERESOURCE};
919 return &resfiledescr;
921 #endif
922 if (len > 0 && buf[len-1] != SEP
923 #ifdef ALTSEP
924 && buf[len-1] != ALTSEP
925 #endif
927 buf[len++] = SEP;
928 #ifdef IMPORT_8x3_NAMES
929 /* see if we are searching in directory dos-8x3 */
930 if (len > 7 && !strncmp(buf + len - 8, "dos-8x3", 7)){
931 int j;
932 char ch; /* limit name to 8 lower-case characters */
933 for (j = 0; (ch = name[j]) && j < 8; j++)
934 if (isupper(ch))
935 buf[len++] = tolower(ch);
936 else
937 buf[len++] = ch;
939 else /* Not in dos-8x3, use the full name */
940 #endif
942 strcpy(buf+len, name);
943 len += namelen;
945 #ifdef HAVE_STAT
946 if (stat(buf, &statbuf) == 0) {
947 if (S_ISDIR(statbuf.st_mode)) {
948 if (find_init_module(buf)) {
949 #ifdef CHECK_IMPORT_CASE
950 if (!check_case(buf, len, namelen,
951 name))
952 return NULL;
953 #endif
954 return &fd_package;
958 #else
959 /* XXX How are you going to test for directories? */
960 #endif
961 #ifdef macintosh
962 fdp = PyMac_FindModuleExtension(buf, &len, name);
963 if (fdp)
964 fp = fopen(buf, fdp->mode);
965 #else
966 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
967 strcpy(buf+len, fdp->suffix);
968 if (Py_VerboseFlag > 1)
969 PySys_WriteStderr("# trying %s\n", buf);
970 fp = fopen(buf, fdp->mode);
971 if (fp != NULL)
972 break;
974 #endif /* !macintosh */
975 if (fp != NULL)
976 break;
978 if (fp == NULL) {
979 PyErr_Format(PyExc_ImportError,
980 "No module named %.200s", name);
981 return NULL;
983 #ifdef CHECK_IMPORT_CASE
984 if (!check_case(buf, len, namelen, name)) {
985 fclose(fp);
986 return NULL;
988 #endif
990 *p_fp = fp;
991 return fdp;
994 #ifdef CHECK_IMPORT_CASE
996 #ifdef MS_WIN32
997 #include <windows.h>
998 #include <ctype.h>
1000 static int
1001 allcaps8x3(s)
1002 char *s;
1004 /* Return 1 if s is an 8.3 filename in ALLCAPS */
1005 char c;
1006 char *dot = strchr(s, '.');
1007 char *end = strchr(s, '\0');
1008 if (dot != NULL) {
1009 if (dot-s > 8)
1010 return 1; /* More than 8 before '.' */
1011 if (end-dot > 4)
1012 return 1; /* More than 3 after '.' */
1013 end = strchr(dot+1, '.');
1014 if (end != NULL)
1015 return 1; /* More than one dot */
1017 else if (end-s > 8)
1018 return 1; /* More than 8 and no dot */
1019 while ((c = *s++)) {
1020 if (islower(c))
1021 return 0;
1023 return 1;
1026 static int
1027 check_case(char *buf, int len, int namelen, char *name)
1029 WIN32_FIND_DATA data;
1030 HANDLE h;
1031 if (getenv("PYTHONCASEOK") != NULL)
1032 return 1;
1033 h = FindFirstFile(buf, &data);
1034 if (h == INVALID_HANDLE_VALUE) {
1035 PyErr_Format(PyExc_NameError,
1036 "Can't find file for module %.100s\n(filename %.300s)",
1037 name, buf);
1038 return 0;
1040 FindClose(h);
1041 if (allcaps8x3(data.cFileName)) {
1042 /* Skip the test if the filename is ALL.CAPS. This can
1043 happen in certain circumstances beyond our control,
1044 e.g. when software is installed under NT on a FAT
1045 filesystem and then the same FAT filesystem is used
1046 under Windows 95. */
1047 return 1;
1049 if (strncmp(data.cFileName, name, namelen) != 0) {
1050 strcpy(buf+len-namelen, data.cFileName);
1051 PyErr_Format(PyExc_NameError,
1052 "Case mismatch for module name %.100s\n(filename %.300s)",
1053 name, buf);
1054 return 0;
1056 return 1;
1058 #endif /* MS_WIN32 */
1060 #ifdef macintosh
1061 #include <TextUtils.h>
1062 #ifdef USE_GUSI
1063 #include "TFileSpec.h" /* for Path2FSSpec() */
1064 #endif
1065 static int
1066 check_case(char *buf, int len, int namelen, char *name)
1068 FSSpec fss;
1069 OSErr err;
1070 #ifndef USE_GUSI
1071 err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
1072 #else
1073 /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
1074 the way, which is fine for all directories, but here we need
1075 the original name of the alias file (say, Dlg.ppc.slb, not
1076 toolboxmodules.ppc.slb). */
1077 char *colon;
1078 err = Path2FSSpec(buf, &fss);
1079 if (err == noErr) {
1080 colon = strrchr(buf, ':'); /* find filename */
1081 if (colon != NULL)
1082 err = FSMakeFSSpec(fss.vRefNum, fss.parID,
1083 Pstring(colon+1), &fss);
1084 else
1085 err = FSMakeFSSpec(fss.vRefNum, fss.parID,
1086 fss.name, &fss);
1088 #endif
1089 if (err) {
1090 PyErr_Format(PyExc_NameError,
1091 "Can't find file for module %.100s\n(filename %.300s)",
1092 name, buf);
1093 return 0;
1095 p2cstr(fss.name);
1096 if ( strncmp(name, (char *)fss.name, namelen) != 0 ) {
1097 PyErr_Format(PyExc_NameError,
1098 "Case mismatch for module name %.100s\n(filename %.300s)",
1099 name, fss.name);
1100 return 0;
1102 return 1;
1104 #endif /* macintosh */
1106 #ifdef DJGPP
1107 #include <dir.h>
1109 static int
1110 check_case(char *buf, int len, int namelen, char *name)
1112 struct ffblk ffblk;
1113 int done;
1115 if (getenv("PYTHONCASEOK") != NULL)
1116 return 1;
1117 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1118 if (done) {
1119 PyErr_Format(PyExc_NameError,
1120 "Can't find file for module %.100s\n(filename %.300s)",
1121 name, buf);
1122 return 0;
1125 if (strncmp(ffblk.ff_name, name, namelen) != 0) {
1126 strcpy(buf+len-namelen, ffblk.ff_name);
1127 PyErr_Format(PyExc_NameError,
1128 "Case mismatch for module name %.100s\n(filename %.300s)",
1129 name, buf);
1130 return 0;
1132 return 1;
1134 #endif
1136 #endif /* CHECK_IMPORT_CASE */
1138 #ifdef HAVE_STAT
1139 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1140 static int
1141 find_init_module(buf)
1142 char *buf;
1144 int save_len = strlen(buf);
1145 int i = save_len;
1146 struct stat statbuf;
1148 if (save_len + 13 >= MAXPATHLEN)
1149 return 0;
1150 buf[i++] = SEP;
1151 strcpy(buf+i, "__init__.py");
1152 if (stat(buf, &statbuf) == 0) {
1153 buf[save_len] = '\0';
1154 return 1;
1156 i += strlen(buf+i);
1157 if (Py_OptimizeFlag)
1158 strcpy(buf+i, "o");
1159 else
1160 strcpy(buf+i, "c");
1161 if (stat(buf, &statbuf) == 0) {
1162 buf[save_len] = '\0';
1163 return 1;
1165 buf[save_len] = '\0';
1166 return 0;
1168 #endif /* HAVE_STAT */
1171 static int init_builtin Py_PROTO((char *)); /* Forward */
1173 /* Load an external module using the default search path and return
1174 its module object WITH INCREMENTED REFERENCE COUNT */
1176 static PyObject *
1177 load_module(name, fp, buf, type)
1178 char *name;
1179 FILE *fp;
1180 char *buf;
1181 int type;
1183 PyObject *modules;
1184 PyObject *m;
1185 int err;
1187 /* First check that there's an open file (if we need one) */
1188 switch (type) {
1189 case PY_SOURCE:
1190 case PY_COMPILED:
1191 if (fp == NULL) {
1192 PyErr_Format(PyExc_ValueError,
1193 "file object required for import (type code %d)",
1194 type);
1195 return NULL;
1199 switch (type) {
1201 case PY_SOURCE:
1202 m = load_source_module(name, buf, fp);
1203 break;
1205 case PY_COMPILED:
1206 m = load_compiled_module(name, buf, fp);
1207 break;
1209 case C_EXTENSION:
1210 m = _PyImport_LoadDynamicModule(name, buf, fp);
1211 break;
1213 #ifdef macintosh
1214 case PY_RESOURCE:
1215 m = PyMac_LoadResourceModule(name, buf);
1216 break;
1217 case PY_CODERESOURCE:
1218 m = PyMac_LoadCodeResourceModule(name, buf);
1219 break;
1220 #endif
1222 case PKG_DIRECTORY:
1223 m = load_package(name, buf);
1224 break;
1226 case C_BUILTIN:
1227 case PY_FROZEN:
1228 if (buf != NULL && buf[0] != '\0')
1229 name = buf;
1230 if (type == C_BUILTIN)
1231 err = init_builtin(name);
1232 else
1233 err = PyImport_ImportFrozenModule(name);
1234 if (err < 0)
1235 return NULL;
1236 if (err == 0) {
1237 PyErr_Format(PyExc_ImportError,
1238 "Purported %s module %.200s not found",
1239 type == C_BUILTIN ?
1240 "builtin" : "frozen",
1241 name);
1242 return NULL;
1244 modules = PyImport_GetModuleDict();
1245 m = PyDict_GetItemString(modules, name);
1246 if (m == NULL) {
1247 PyErr_Format(
1248 PyExc_ImportError,
1249 "%s module %.200s not properly initialized",
1250 type == C_BUILTIN ?
1251 "builtin" : "frozen",
1252 name);
1253 return NULL;
1255 Py_INCREF(m);
1256 break;
1258 default:
1259 PyErr_Format(PyExc_ImportError,
1260 "Don't know how to import %.200s (type code %d)",
1261 name, type);
1262 m = NULL;
1266 return m;
1270 /* Initialize a built-in module.
1271 Return 1 for succes, 0 if the module is not found, and -1 with
1272 an exception set if the initialization failed. */
1274 static int
1275 init_builtin(name)
1276 char *name;
1278 struct _inittab *p;
1279 PyObject *mod;
1281 if ((mod = _PyImport_FindExtension(name, name)) != NULL)
1282 return 1;
1284 for (p = PyImport_Inittab; p->name != NULL; p++) {
1285 if (strcmp(name, p->name) == 0) {
1286 if (p->initfunc == NULL) {
1287 PyErr_Format(PyExc_ImportError,
1288 "Cannot re-init internal module %.200s",
1289 name);
1290 return -1;
1292 if (Py_VerboseFlag)
1293 PySys_WriteStderr("import %s # builtin\n", name);
1294 (*p->initfunc)();
1295 if (PyErr_Occurred())
1296 return -1;
1297 if (_PyImport_FixupExtension(name, name) == NULL)
1298 return -1;
1299 return 1;
1302 return 0;
1306 /* Frozen modules */
1308 static struct _frozen *
1309 find_frozen(name)
1310 char *name;
1312 struct _frozen *p;
1314 for (p = PyImport_FrozenModules; ; p++) {
1315 if (p->name == NULL)
1316 return NULL;
1317 if (strcmp(p->name, name) == 0)
1318 break;
1320 return p;
1323 static PyObject *
1324 get_frozen_object(name)
1325 char *name;
1327 struct _frozen *p = find_frozen(name);
1328 int size;
1330 if (p == NULL) {
1331 PyErr_Format(PyExc_ImportError,
1332 "No such frozen object named %.200s",
1333 name);
1334 return NULL;
1336 size = p->size;
1337 if (size < 0)
1338 size = -size;
1339 return PyMarshal_ReadObjectFromString((char *)p->code, size);
1342 /* Initialize a frozen module.
1343 Return 1 for succes, 0 if the module is not found, and -1 with
1344 an exception set if the initialization failed.
1345 This function is also used from frozenmain.c */
1348 PyImport_ImportFrozenModule(name)
1349 char *name;
1351 struct _frozen *p = find_frozen(name);
1352 PyObject *co;
1353 PyObject *m;
1354 int ispackage;
1355 int size;
1357 if (p == NULL)
1358 return 0;
1359 size = p->size;
1360 ispackage = (size < 0);
1361 if (ispackage)
1362 size = -size;
1363 if (Py_VerboseFlag)
1364 PySys_WriteStderr("import %s # frozen%s\n",
1365 name, ispackage ? " package" : "");
1366 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1367 if (co == NULL)
1368 return -1;
1369 if (!PyCode_Check(co)) {
1370 Py_DECREF(co);
1371 PyErr_Format(PyExc_TypeError,
1372 "frozen object %.200s is not a code object",
1373 name);
1374 return -1;
1376 if (ispackage) {
1377 /* Set __path__ to the package name */
1378 PyObject *d, *s;
1379 int err;
1380 m = PyImport_AddModule(name);
1381 if (m == NULL)
1382 return -1;
1383 d = PyModule_GetDict(m);
1384 s = PyString_InternFromString(name);
1385 if (s == NULL)
1386 return -1;
1387 err = PyDict_SetItemString(d, "__path__", s);
1388 Py_DECREF(s);
1389 if (err != 0)
1390 return err;
1392 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
1393 Py_DECREF(co);
1394 if (m == NULL)
1395 return -1;
1396 Py_DECREF(m);
1397 return 1;
1401 /* Import a module, either built-in, frozen, or external, and return
1402 its module object WITH INCREMENTED REFERENCE COUNT */
1404 PyObject *
1405 PyImport_ImportModule(name)
1406 char *name;
1408 static PyObject *fromlist = NULL;
1409 if (fromlist == NULL && strchr(name, '.') != NULL) {
1410 fromlist = Py_BuildValue("[s]", "*");
1411 if (fromlist == NULL)
1412 return NULL;
1414 return PyImport_ImportModuleEx(name, NULL, NULL, fromlist);
1417 /* Forward declarations for helper routines */
1418 static PyObject *get_parent Py_PROTO((PyObject *globals,
1419 char *buf, int *p_buflen));
1420 static PyObject *load_next Py_PROTO((PyObject *mod, PyObject *altmod,
1421 char **p_name, char *buf, int *p_buflen));
1422 static int mark_miss Py_PROTO((char *name));
1423 static int ensure_fromlist Py_PROTO((PyObject *mod, PyObject *fromlist,
1424 char *buf, int buflen, int recursive));
1425 static PyObject * import_submodule Py_PROTO((PyObject *mod,
1426 char *name, char *fullname));
1428 /* The Magnum Opus of dotted-name import :-) */
1430 static PyObject *
1431 import_module_ex(name, globals, locals, fromlist)
1432 char *name;
1433 PyObject *globals;
1434 PyObject *locals;
1435 PyObject *fromlist;
1437 char buf[MAXPATHLEN+1];
1438 int buflen = 0;
1439 PyObject *parent, *head, *next, *tail;
1441 parent = get_parent(globals, buf, &buflen);
1442 if (parent == NULL)
1443 return NULL;
1445 head = load_next(parent, Py_None, &name, buf, &buflen);
1446 if (head == NULL)
1447 return NULL;
1449 tail = head;
1450 Py_INCREF(tail);
1451 while (name) {
1452 next = load_next(tail, tail, &name, buf, &buflen);
1453 Py_DECREF(tail);
1454 if (next == NULL) {
1455 Py_DECREF(head);
1456 return NULL;
1458 tail = next;
1461 if (fromlist != NULL) {
1462 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1463 fromlist = NULL;
1466 if (fromlist == NULL) {
1467 Py_DECREF(tail);
1468 return head;
1471 Py_DECREF(head);
1472 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
1473 Py_DECREF(tail);
1474 return NULL;
1477 return tail;
1480 PyObject *
1481 PyImport_ImportModuleEx(name, globals, locals, fromlist)
1482 char *name;
1483 PyObject *globals;
1484 PyObject *locals;
1485 PyObject *fromlist;
1487 PyObject *result;
1488 lock_import();
1489 result = import_module_ex(name, globals, locals, fromlist);
1490 unlock_import();
1491 return result;
1494 static PyObject *
1495 get_parent(globals, buf, p_buflen)
1496 PyObject *globals;
1497 char *buf;
1498 int *p_buflen;
1500 static PyObject *namestr = NULL;
1501 static PyObject *pathstr = NULL;
1502 PyObject *modname, *modpath, *modules, *parent;
1504 if (globals == NULL || !PyDict_Check(globals))
1505 return Py_None;
1507 if (namestr == NULL) {
1508 namestr = PyString_InternFromString("__name__");
1509 if (namestr == NULL)
1510 return NULL;
1512 if (pathstr == NULL) {
1513 pathstr = PyString_InternFromString("__path__");
1514 if (pathstr == NULL)
1515 return NULL;
1518 *buf = '\0';
1519 *p_buflen = 0;
1520 modname = PyDict_GetItem(globals, namestr);
1521 if (modname == NULL || !PyString_Check(modname))
1522 return Py_None;
1524 modpath = PyDict_GetItem(globals, pathstr);
1525 if (modpath != NULL) {
1526 int len = PyString_GET_SIZE(modname);
1527 if (len > MAXPATHLEN) {
1528 PyErr_SetString(PyExc_ValueError,
1529 "Module name too long");
1530 return NULL;
1532 strcpy(buf, PyString_AS_STRING(modname));
1533 *p_buflen = len;
1535 else {
1536 char *start = PyString_AS_STRING(modname);
1537 char *lastdot = strrchr(start, '.');
1538 int len;
1539 if (lastdot == NULL)
1540 return Py_None;
1541 len = lastdot - start;
1542 if (len >= MAXPATHLEN) {
1543 PyErr_SetString(PyExc_ValueError,
1544 "Module name too long");
1545 return NULL;
1547 strncpy(buf, start, len);
1548 buf[len] = '\0';
1549 *p_buflen = len;
1552 modules = PyImport_GetModuleDict();
1553 parent = PyDict_GetItemString(modules, buf);
1554 if (parent == NULL)
1555 parent = Py_None;
1556 return parent;
1557 /* We expect, but can't guarantee, if parent != None, that:
1558 - parent.__name__ == buf
1559 - parent.__dict__ is globals
1560 If this is violated... Who cares? */
1563 static PyObject *
1564 load_next(mod, altmod, p_name, buf, p_buflen)
1565 PyObject *mod;
1566 PyObject *altmod; /* Either None or same as mod */
1567 char **p_name;
1568 char *buf;
1569 int *p_buflen;
1571 char *name = *p_name;
1572 char *dot = strchr(name, '.');
1573 int len;
1574 char *p;
1575 PyObject *result;
1577 if (dot == NULL) {
1578 *p_name = NULL;
1579 len = strlen(name);
1581 else {
1582 *p_name = dot+1;
1583 len = dot-name;
1585 if (len == 0) {
1586 PyErr_SetString(PyExc_ValueError,
1587 "Empty module name");
1588 return NULL;
1591 p = buf + *p_buflen;
1592 if (p != buf)
1593 *p++ = '.';
1594 if (p+len-buf >= MAXPATHLEN) {
1595 PyErr_SetString(PyExc_ValueError,
1596 "Module name too long");
1597 return NULL;
1599 strncpy(p, name, len);
1600 p[len] = '\0';
1601 *p_buflen = p+len-buf;
1603 result = import_submodule(mod, p, buf);
1604 if (result == Py_None && altmod != mod) {
1605 Py_DECREF(result);
1606 /* Here, altmod must be None and mod must not be None */
1607 result = import_submodule(altmod, p, p);
1608 if (result != NULL && result != Py_None) {
1609 if (mark_miss(buf) != 0) {
1610 Py_DECREF(result);
1611 return NULL;
1613 strncpy(buf, name, len);
1614 buf[len] = '\0';
1615 *p_buflen = len;
1618 if (result == NULL)
1619 return NULL;
1621 if (result == Py_None) {
1622 Py_DECREF(result);
1623 PyErr_Format(PyExc_ImportError,
1624 "No module named %.200s", name);
1625 return NULL;
1628 return result;
1631 static int
1632 mark_miss(name)
1633 char *name;
1635 PyObject *modules = PyImport_GetModuleDict();
1636 return PyDict_SetItemString(modules, name, Py_None);
1639 static int
1640 ensure_fromlist(mod, fromlist, buf, buflen, recursive)
1641 PyObject *mod;
1642 PyObject *fromlist;
1643 char *buf;
1644 int buflen;
1645 int recursive;
1647 int i;
1649 if (!PyObject_HasAttrString(mod, "__path__"))
1650 return 1;
1652 for (i = 0; ; i++) {
1653 PyObject *item = PySequence_GetItem(fromlist, i);
1654 int hasit;
1655 if (item == NULL) {
1656 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1657 PyErr_Clear();
1658 return 1;
1660 return 0;
1662 if (!PyString_Check(item)) {
1663 PyErr_SetString(PyExc_TypeError,
1664 "Item in ``from list'' not a string");
1665 Py_DECREF(item);
1666 return 0;
1668 if (PyString_AS_STRING(item)[0] == '*') {
1669 PyObject *all;
1670 Py_DECREF(item);
1671 /* See if the package defines __all__ */
1672 if (recursive)
1673 continue; /* Avoid endless recursion */
1674 all = PyObject_GetAttrString(mod, "__all__");
1675 if (all == NULL)
1676 PyErr_Clear();
1677 else {
1678 if (!ensure_fromlist(mod, all, buf, buflen, 1))
1679 return 0;
1680 Py_DECREF(all);
1682 continue;
1684 hasit = PyObject_HasAttr(mod, item);
1685 if (!hasit) {
1686 char *subname = PyString_AS_STRING(item);
1687 PyObject *submod;
1688 char *p;
1689 if (buflen + strlen(subname) >= MAXPATHLEN) {
1690 PyErr_SetString(PyExc_ValueError,
1691 "Module name too long");
1692 Py_DECREF(item);
1693 return 0;
1695 p = buf + buflen;
1696 *p++ = '.';
1697 strcpy(p, subname);
1698 submod = import_submodule(mod, subname, buf);
1699 Py_XDECREF(submod);
1700 if (submod == NULL) {
1701 Py_DECREF(item);
1702 return 0;
1705 Py_DECREF(item);
1708 /* NOTREACHED */
1711 static PyObject *
1712 import_submodule(mod, subname, fullname)
1713 PyObject *mod; /* May be None */
1714 char *subname;
1715 char *fullname;
1717 PyObject *modules = PyImport_GetModuleDict();
1718 PyObject *m;
1720 /* Require:
1721 if mod == None: subname == fullname
1722 else: mod.__name__ + "." + subname == fullname
1725 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
1726 Py_INCREF(m);
1728 else {
1729 PyObject *path;
1730 char buf[MAXPATHLEN+1];
1731 struct filedescr *fdp;
1732 FILE *fp = NULL;
1734 if (mod == Py_None)
1735 path = NULL;
1736 else {
1737 path = PyObject_GetAttrString(mod, "__path__");
1738 if (path == NULL) {
1739 PyErr_Clear();
1740 Py_INCREF(Py_None);
1741 return Py_None;
1745 buf[0] = '\0';
1746 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1747 Py_XDECREF(path);
1748 if (fdp == NULL) {
1749 if (!PyErr_ExceptionMatches(PyExc_ImportError))
1750 return NULL;
1751 PyErr_Clear();
1752 Py_INCREF(Py_None);
1753 return Py_None;
1755 m = load_module(fullname, fp, buf, fdp->type);
1756 if (fp)
1757 fclose(fp);
1758 if (m != NULL && mod != Py_None) {
1759 if (PyObject_SetAttrString(mod, subname, m) < 0) {
1760 Py_DECREF(m);
1761 m = NULL;
1766 return m;
1770 /* Re-import a module of any kind and return its module object, WITH
1771 INCREMENTED REFERENCE COUNT */
1773 PyObject *
1774 PyImport_ReloadModule(m)
1775 PyObject *m;
1777 PyObject *modules = PyImport_GetModuleDict();
1778 PyObject *path = NULL;
1779 char *name, *subname;
1780 char buf[MAXPATHLEN+1];
1781 struct filedescr *fdp;
1782 FILE *fp = NULL;
1784 if (m == NULL || !PyModule_Check(m)) {
1785 PyErr_SetString(PyExc_TypeError,
1786 "reload() argument must be module");
1787 return NULL;
1789 name = PyModule_GetName(m);
1790 if (name == NULL)
1791 return NULL;
1792 if (m != PyDict_GetItemString(modules, name)) {
1793 PyErr_Format(PyExc_ImportError,
1794 "reload(): module %.200s not in sys.modules",
1795 name);
1796 return NULL;
1798 subname = strrchr(name, '.');
1799 if (subname == NULL)
1800 subname = name;
1801 else {
1802 PyObject *parentname, *parent;
1803 parentname = PyString_FromStringAndSize(name, (subname-name));
1804 if (parentname == NULL)
1805 return NULL;
1806 parent = PyDict_GetItem(modules, parentname);
1807 Py_DECREF(parentname);
1808 if (parent == NULL) {
1809 PyErr_Format(PyExc_ImportError,
1810 "reload(): parent %.200s not in sys.modules",
1811 name);
1812 return NULL;
1814 subname++;
1815 path = PyObject_GetAttrString(parent, "__path__");
1816 if (path == NULL)
1817 PyErr_Clear();
1819 buf[0] = '\0';
1820 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1821 Py_XDECREF(path);
1822 if (fdp == NULL)
1823 return NULL;
1824 m = load_module(name, fp, buf, fdp->type);
1825 if (fp)
1826 fclose(fp);
1827 return m;
1831 /* Higher-level import emulator which emulates the "import" statement
1832 more accurately -- it invokes the __import__() function from the
1833 builtins of the current globals. This means that the import is
1834 done using whatever import hooks are installed in the current
1835 environment, e.g. by "rexec".
1836 A dummy list ["__doc__"] is passed as the 4th argument so that
1837 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1838 will return <module "gencache"> instead of <module "win32com">. */
1840 PyObject *
1841 PyImport_Import(module_name)
1842 PyObject *module_name;
1844 static PyObject *silly_list = NULL;
1845 static PyObject *builtins_str = NULL;
1846 static PyObject *import_str = NULL;
1847 static PyObject *standard_builtins = NULL;
1848 PyObject *globals = NULL;
1849 PyObject *import = NULL;
1850 PyObject *builtins = NULL;
1851 PyObject *r = NULL;
1853 /* Initialize constant string objects */
1854 if (silly_list == NULL) {
1855 import_str = PyString_InternFromString("__import__");
1856 if (import_str == NULL)
1857 return NULL;
1858 builtins_str = PyString_InternFromString("__builtins__");
1859 if (builtins_str == NULL)
1860 return NULL;
1861 silly_list = Py_BuildValue("[s]", "__doc__");
1862 if (silly_list == NULL)
1863 return NULL;
1866 /* Get the builtins from current globals */
1867 globals = PyEval_GetGlobals();
1868 if(globals != NULL) {
1869 Py_INCREF(globals);
1870 builtins = PyObject_GetItem(globals, builtins_str);
1871 if (builtins == NULL)
1872 goto err;
1874 else {
1875 /* No globals -- use standard builtins, and fake globals */
1876 PyErr_Clear();
1878 if (standard_builtins == NULL) {
1879 standard_builtins =
1880 PyImport_ImportModule("__builtin__");
1881 if (standard_builtins == NULL)
1882 return NULL;
1885 builtins = standard_builtins;
1886 Py_INCREF(builtins);
1887 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1888 if (globals == NULL)
1889 goto err;
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;
1900 /* Call the _import__ function with the proper argument list */
1901 r = PyObject_CallFunction(import, "OOOO",
1902 module_name, globals, globals, silly_list);
1904 err:
1905 Py_XDECREF(globals);
1906 Py_XDECREF(builtins);
1907 Py_XDECREF(import);
1909 return r;
1913 /* Module 'imp' provides Python access to the primitives used for
1914 importing modules.
1917 static PyObject *
1918 imp_get_magic(self, args)
1919 PyObject *self;
1920 PyObject *args;
1922 char buf[4];
1924 if (!PyArg_ParseTuple(args, ""))
1925 return NULL;
1926 buf[0] = (char) ((MAGIC >> 0) & 0xff);
1927 buf[1] = (char) ((MAGIC >> 8) & 0xff);
1928 buf[2] = (char) ((MAGIC >> 16) & 0xff);
1929 buf[3] = (char) ((MAGIC >> 24) & 0xff);
1931 return PyString_FromStringAndSize(buf, 4);
1934 static PyObject *
1935 imp_get_suffixes(self, args)
1936 PyObject *self;
1937 PyObject *args;
1939 PyObject *list;
1940 struct filedescr *fdp;
1942 if (!PyArg_ParseTuple(args, ""))
1943 return NULL;
1944 list = PyList_New(0);
1945 if (list == NULL)
1946 return NULL;
1947 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1948 PyObject *item = Py_BuildValue("ssi",
1949 fdp->suffix, fdp->mode, fdp->type);
1950 if (item == NULL) {
1951 Py_DECREF(list);
1952 return NULL;
1954 if (PyList_Append(list, item) < 0) {
1955 Py_DECREF(list);
1956 Py_DECREF(item);
1957 return NULL;
1959 Py_DECREF(item);
1961 return list;
1964 static PyObject *
1965 call_find_module(name, path)
1966 char *name;
1967 PyObject *path; /* list or None or NULL */
1969 extern int fclose Py_PROTO((FILE *));
1970 PyObject *fob, *ret;
1971 struct filedescr *fdp;
1972 char pathname[MAXPATHLEN+1];
1973 FILE *fp = NULL;
1975 pathname[0] = '\0';
1976 if (path == Py_None)
1977 path = NULL;
1978 fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
1979 if (fdp == NULL)
1980 return NULL;
1981 if (fp != NULL) {
1982 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
1983 if (fob == NULL) {
1984 fclose(fp);
1985 return NULL;
1988 else {
1989 fob = Py_None;
1990 Py_INCREF(fob);
1992 ret = Py_BuildValue("Os(ssi)",
1993 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
1994 Py_DECREF(fob);
1995 return ret;
1998 static PyObject *
1999 imp_find_module(self, args)
2000 PyObject *self;
2001 PyObject *args;
2003 char *name;
2004 PyObject *path = NULL;
2005 if (!PyArg_ParseTuple(args, "s|O", &name, &path))
2006 return NULL;
2007 return call_find_module(name, path);
2010 static PyObject *
2011 imp_init_builtin(self, args)
2012 PyObject *self;
2013 PyObject *args;
2015 char *name;
2016 int ret;
2017 PyObject *m;
2018 if (!PyArg_ParseTuple(args, "s", &name))
2019 return NULL;
2020 ret = init_builtin(name);
2021 if (ret < 0)
2022 return NULL;
2023 if (ret == 0) {
2024 Py_INCREF(Py_None);
2025 return Py_None;
2027 m = PyImport_AddModule(name);
2028 Py_XINCREF(m);
2029 return m;
2032 static PyObject *
2033 imp_init_frozen(self, args)
2034 PyObject *self;
2035 PyObject *args;
2037 char *name;
2038 int ret;
2039 PyObject *m;
2040 if (!PyArg_ParseTuple(args, "s", &name))
2041 return NULL;
2042 ret = PyImport_ImportFrozenModule(name);
2043 if (ret < 0)
2044 return NULL;
2045 if (ret == 0) {
2046 Py_INCREF(Py_None);
2047 return Py_None;
2049 m = PyImport_AddModule(name);
2050 Py_XINCREF(m);
2051 return m;
2054 static PyObject *
2055 imp_get_frozen_object(self, args)
2056 PyObject *self;
2057 PyObject *args;
2059 char *name;
2061 if (!PyArg_ParseTuple(args, "s", &name))
2062 return NULL;
2063 return get_frozen_object(name);
2066 static PyObject *
2067 imp_is_builtin(self, args)
2068 PyObject *self;
2069 PyObject *args;
2071 char *name;
2072 if (!PyArg_ParseTuple(args, "s", &name))
2073 return NULL;
2074 return PyInt_FromLong(is_builtin(name));
2077 static PyObject *
2078 imp_is_frozen(self, args)
2079 PyObject *self;
2080 PyObject *args;
2082 char *name;
2083 struct _frozen *p;
2084 if (!PyArg_ParseTuple(args, "s", &name))
2085 return NULL;
2086 p = find_frozen(name);
2087 return PyInt_FromLong((long) (p == NULL ? 0 : p->size));
2090 static FILE *
2091 get_file(pathname, fob, mode)
2092 char *pathname;
2093 PyObject *fob;
2094 char *mode;
2096 FILE *fp;
2097 if (fob == NULL) {
2098 fp = fopen(pathname, mode);
2099 if (fp == NULL)
2100 PyErr_SetFromErrno(PyExc_IOError);
2102 else {
2103 fp = PyFile_AsFile(fob);
2104 if (fp == NULL)
2105 PyErr_SetString(PyExc_ValueError,
2106 "bad/closed file object");
2108 return fp;
2111 static PyObject *
2112 imp_load_compiled(self, args)
2113 PyObject *self;
2114 PyObject *args;
2116 char *name;
2117 char *pathname;
2118 PyObject *fob = NULL;
2119 PyObject *m;
2120 FILE *fp;
2121 if (!PyArg_ParseTuple(args, "ss|O!", &name, &pathname,
2122 &PyFile_Type, &fob))
2123 return NULL;
2124 fp = get_file(pathname, fob, "rb");
2125 if (fp == NULL)
2126 return NULL;
2127 m = load_compiled_module(name, pathname, fp);
2128 if (fob == NULL)
2129 fclose(fp);
2130 return m;
2133 static PyObject *
2134 imp_load_dynamic(self, args)
2135 PyObject *self;
2136 PyObject *args;
2138 char *name;
2139 char *pathname;
2140 PyObject *fob = NULL;
2141 PyObject *m;
2142 FILE *fp = NULL;
2143 if (!PyArg_ParseTuple(args, "ss|O!", &name, &pathname,
2144 &PyFile_Type, &fob))
2145 return NULL;
2146 if (fob) {
2147 fp = get_file(pathname, fob, "r");
2148 if (fp == NULL)
2149 return NULL;
2151 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2152 return m;
2155 static PyObject *
2156 imp_load_source(self, args)
2157 PyObject *self;
2158 PyObject *args;
2160 char *name;
2161 char *pathname;
2162 PyObject *fob = NULL;
2163 PyObject *m;
2164 FILE *fp;
2165 if (!PyArg_ParseTuple(args, "ss|O!", &name, &pathname,
2166 &PyFile_Type, &fob))
2167 return NULL;
2168 fp = get_file(pathname, fob, "r");
2169 if (fp == NULL)
2170 return NULL;
2171 m = load_source_module(name, pathname, fp);
2172 if (fob == NULL)
2173 fclose(fp);
2174 return m;
2177 #ifdef macintosh
2178 static PyObject *
2179 imp_load_resource(self, args)
2180 PyObject *self;
2181 PyObject *args;
2183 char *name;
2184 char *pathname;
2185 PyObject *m;
2187 if (!PyArg_ParseTuple(args, "ss", &name, &pathname))
2188 return NULL;
2189 m = PyMac_LoadResourceModule(name, pathname);
2190 return m;
2192 #endif /* macintosh */
2194 static PyObject *
2195 imp_load_module(self, args)
2196 PyObject *self;
2197 PyObject *args;
2199 char *name;
2200 PyObject *fob;
2201 char *pathname;
2202 char *suffix; /* Unused */
2203 char *mode;
2204 int type;
2205 FILE *fp;
2207 if (!PyArg_ParseTuple(args, "sOs(ssi)",
2208 &name, &fob, &pathname,
2209 &suffix, &mode, &type))
2210 return NULL;
2211 if (*mode && (*mode != 'r' || strchr(mode, '+') != NULL)) {
2212 PyErr_Format(PyExc_ValueError,
2213 "invalid file open mode %.200s", mode);
2214 return NULL;
2216 if (fob == Py_None)
2217 fp = NULL;
2218 else {
2219 if (!PyFile_Check(fob)) {
2220 PyErr_SetString(PyExc_ValueError,
2221 "load_module arg#2 should be a file or None");
2222 return NULL;
2224 fp = get_file(pathname, fob, mode);
2225 if (fp == NULL)
2226 return NULL;
2228 return load_module(name, fp, pathname, type);
2231 static PyObject *
2232 imp_load_package(self, args)
2233 PyObject *self;
2234 PyObject *args;
2236 char *name;
2237 char *pathname;
2238 if (!PyArg_ParseTuple(args, "ss", &name, &pathname))
2239 return NULL;
2240 return load_package(name, pathname);
2243 static PyObject *
2244 imp_new_module(self, args)
2245 PyObject *self;
2246 PyObject *args;
2248 char *name;
2249 if (!PyArg_ParseTuple(args, "s", &name))
2250 return NULL;
2251 return PyModule_New(name);
2254 /* Doc strings */
2256 static char doc_imp[] = "\
2257 This module provides the components needed to build your own\n\
2258 __import__ function. Undocumented functions are obsolete.\n\
2261 static char doc_find_module[] = "\
2262 find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2263 Search for a module. If path is omitted or None, search for a\n\
2264 built-in, frozen or special module and continue search in sys.path.\n\
2265 The module name cannot contain '.'; to search for a submodule of a\n\
2266 package, pass the submodule name and the package's __path__.\
2269 static char doc_load_module[] = "\
2270 load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2271 Load a module, given information returned by find_module().\n\
2272 The module name must include the full package name, if any.\
2275 static char doc_get_magic[] = "\
2276 get_magic() -> string\n\
2277 Return the magic number for .pyc or .pyo files.\
2280 static char doc_get_suffixes[] = "\
2281 get_suffixes() -> [(suffix, mode, type), ...]\n\
2282 Return a list of (suffix, mode, type) tuples describing the files\n\
2283 that find_module() looks for.\
2286 static char doc_new_module[] = "\
2287 new_module(name) -> module\n\
2288 Create a new module. Do not enter it in sys.modules.\n\
2289 The module name must include the full package name, if any.\
2292 static PyMethodDef imp_methods[] = {
2293 {"find_module", imp_find_module, 1, doc_find_module},
2294 {"get_magic", imp_get_magic, 1, doc_get_magic},
2295 {"get_suffixes", imp_get_suffixes, 1, doc_get_suffixes},
2296 {"load_module", imp_load_module, 1, doc_load_module},
2297 {"new_module", imp_new_module, 1, doc_new_module},
2298 /* The rest are obsolete */
2299 {"get_frozen_object", imp_get_frozen_object, 1},
2300 {"init_builtin", imp_init_builtin, 1},
2301 {"init_frozen", imp_init_frozen, 1},
2302 {"is_builtin", imp_is_builtin, 1},
2303 {"is_frozen", imp_is_frozen, 1},
2304 {"load_compiled", imp_load_compiled, 1},
2305 {"load_dynamic", imp_load_dynamic, 1},
2306 {"load_package", imp_load_package, 1},
2307 #ifdef macintosh
2308 {"load_resource", imp_load_resource, 1},
2309 #endif
2310 {"load_source", imp_load_source, 1},
2311 {NULL, NULL} /* sentinel */
2314 static int
2315 setint(d, name, value)
2316 PyObject *d;
2317 char *name;
2318 int value;
2320 PyObject *v;
2321 int err;
2323 v = PyInt_FromLong((long)value);
2324 err = PyDict_SetItemString(d, name, v);
2325 Py_XDECREF(v);
2326 return err;
2329 void
2330 initimp()
2332 PyObject *m, *d;
2334 m = Py_InitModule4("imp", imp_methods, doc_imp,
2335 NULL, PYTHON_API_VERSION);
2336 d = PyModule_GetDict(m);
2338 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2339 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2340 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2341 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2342 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2343 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2344 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2345 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
2346 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
2348 failure:
2353 /* API for embedding applications that want to add their own entries to the
2354 table of built-in modules. This should normally be called *before*
2355 Py_Initialize(). When the malloc() or realloc() call fails, -1 is returned
2356 and the existing table is unchanged.
2358 After a similar function by Just van Rossum. */
2361 PyImport_ExtendInittab(newtab)
2362 struct _inittab *newtab;
2364 static struct _inittab *our_copy = NULL;
2365 struct _inittab *p;
2366 int i, n;
2368 /* Count the number of entries in both tables */
2369 for (n = 0; newtab[n].name != NULL; n++)
2371 if (n == 0)
2372 return 0; /* Nothing to do */
2373 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2376 /* Allocate new memory for the combined table */
2377 if (our_copy == NULL)
2378 p = malloc((i+n+1) * sizeof(struct _inittab));
2379 else
2380 p = realloc(our_copy, (i+n+1) * sizeof(struct _inittab));
2381 if (p == NULL)
2382 return -1;
2384 /* Copy the tables into the new memory */
2385 if (our_copy != PyImport_Inittab)
2386 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2387 PyImport_Inittab = our_copy = p;
2388 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2390 return 0;
2393 /* Shorthand to add a single entry given a name and a function */
2396 PyImport_AppendInittab(name, initfunc)
2397 char *name;
2398 void (*initfunc)();
2400 struct _inittab newtab[2];
2402 memset(newtab, '\0', sizeof newtab);
2404 newtab[0].name = name;
2405 newtab[0].initfunc = initfunc;
2407 return PyImport_ExtendInittab(newtab);