Last set of CW Pro 5 projects (probably)
[python/dscho.git] / Python / import.c
blobf38ee4198c024fde5d2f9fe0558c67c8ffcba9b1
1 /***********************************************************
2 Copyright (c) 2000, BeOpen.com.
3 Copyright (c) 1995-2000, Corporation for National Research Initiatives.
4 Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
5 All rights reserved.
7 See the file "Misc/COPYRIGHT" for information on usage and
8 redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
9 ******************************************************************/
11 /* Module definition and import implementation */
13 #include "Python.h"
15 #include "node.h"
16 #include "token.h"
17 #include "errcode.h"
18 #include "marshal.h"
19 #include "compile.h"
20 #include "eval.h"
21 #include "osdefs.h"
22 #include "importdl.h"
23 #ifdef macintosh
24 #include "macglue.h"
25 #endif
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>
29 #endif
31 /* We expect that stat exists on most systems.
32 It's confirmed on Unix, Mac and Windows.
33 If you don't have it, add #define DONT_HAVE_STAT to your config.h. */
34 #ifndef DONT_HAVE_STAT
35 #define HAVE_STAT
37 #ifndef DONT_HAVE_SYS_TYPES_H
38 #include <sys/types.h>
39 #endif
40 #ifndef DONT_HAVE_SYS_STAT_H
41 #include <sys/stat.h>
42 #elif defined(HAVE_STAT_H)
43 #include <stat.h>
44 #endif
46 #if defined(PYCC_VACPP)
47 /* VisualAge C/C++ Failed to Define MountType Field in sys/stat.h */
48 #define S_IFMT (S_IFDIR|S_IFCHR|S_IFREG)
49 #endif
51 #ifndef S_ISDIR
52 #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
53 #endif
55 #endif
58 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
59 /* In getmtime.c */
61 /* Magic word to reject .pyc files generated by other Python versions */
62 /* Change for each incompatible change */
63 /* The value of CR and LF is incorporated so if you ever read or write
64 a .pyc file in text mode the magic number will be wrong; also, the
65 Apple MPW compiler swaps their values, botching string constants */
66 /* XXX Perhaps the magic number should be frozen and a version field
67 added to the .pyc file header? */
68 /* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */
69 #define MAGIC (50822 | ((long)'\r'<<16) | ((long)'\n'<<24))
71 /* Magic word as global; note that _PyImport_Init() can change the
72 value of this global to accommodate for alterations of how the
73 compiler works which are enabled by command line switches. */
74 static long pyc_magic = MAGIC;
76 /* See _PyImport_FixupExtension() below */
77 static PyObject *extensions = NULL;
79 /* This table is defined in config.c: */
80 extern struct _inittab _PyImport_Inittab[];
82 struct _inittab *PyImport_Inittab = _PyImport_Inittab;
84 /* these tables define the module suffixes that Python recognizes */
85 struct filedescr * _PyImport_Filetab = NULL;
86 static const struct filedescr _PyImport_StandardFiletab[] = {
87 {".py", "r", PY_SOURCE},
88 {".pyc", "rb", PY_COMPILED},
89 {0, 0}
92 /* Initialize things */
94 void
95 _PyImport_Init(void)
97 const struct filedescr *scan;
98 struct filedescr *filetab;
99 int countD = 0;
100 int countS = 0;
102 /* prepare _PyImport_Filetab: copy entries from
103 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
105 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
106 ++countD;
107 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
108 ++countS;
109 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
110 memcpy(filetab, _PyImport_DynLoadFiletab,
111 countD * sizeof(struct filedescr));
112 memcpy(filetab + countD, _PyImport_StandardFiletab,
113 countS * sizeof(struct filedescr));
114 filetab[countD + countS].suffix = NULL;
116 _PyImport_Filetab = filetab;
118 if (Py_OptimizeFlag) {
119 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
120 for (; filetab->suffix != NULL; filetab++) {
121 if (strcmp(filetab->suffix, ".pyc") == 0)
122 filetab->suffix = ".pyo";
126 if (Py_UnicodeFlag) {
127 /* Fix the pyc_magic so that byte compiled code created
128 using the all-Unicode method doesn't interfere with
129 code created in normal operation mode. */
130 pyc_magic = MAGIC + 1;
134 void
135 _PyImport_Fini(void)
137 Py_XDECREF(extensions);
138 extensions = NULL;
142 /* Locking primitives to prevent parallel imports of the same module
143 in different threads to return with a partially loaded module.
144 These calls are serialized by the global interpreter lock. */
146 #ifdef WITH_THREAD
148 #include "pythread.h"
150 static PyThread_type_lock import_lock = 0;
151 static long import_lock_thread = -1;
152 static int import_lock_level = 0;
154 static void
155 lock_import(void)
157 long me = PyThread_get_thread_ident();
158 if (me == -1)
159 return; /* Too bad */
160 if (import_lock == NULL)
161 import_lock = PyThread_allocate_lock();
162 if (import_lock_thread == me) {
163 import_lock_level++;
164 return;
166 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) {
167 PyThreadState *tstate = PyEval_SaveThread();
168 PyThread_acquire_lock(import_lock, 1);
169 PyEval_RestoreThread(tstate);
171 import_lock_thread = me;
172 import_lock_level = 1;
175 static void
176 unlock_import(void)
178 long me = PyThread_get_thread_ident();
179 if (me == -1)
180 return; /* Too bad */
181 if (import_lock_thread != me)
182 Py_FatalError("unlock_import: not holding the import lock");
183 import_lock_level--;
184 if (import_lock_level == 0) {
185 import_lock_thread = -1;
186 PyThread_release_lock(import_lock);
190 #else
192 #define lock_import()
193 #define unlock_import()
195 #endif
197 /* Helper for sys */
199 PyObject *
200 PyImport_GetModuleDict(void)
202 PyInterpreterState *interp = PyThreadState_Get()->interp;
203 if (interp->modules == NULL)
204 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
205 return interp->modules;
209 /* List of names to clear in sys */
210 static char* sys_deletes[] = {
211 "path", "argv", "ps1", "ps2", "exitfunc",
212 "exc_type", "exc_value", "exc_traceback",
213 "last_type", "last_value", "last_traceback",
214 NULL
217 static char* sys_files[] = {
218 "stdin", "__stdin__",
219 "stdout", "__stdout__",
220 "stderr", "__stderr__",
221 NULL
225 /* Un-initialize things, as good as we can */
227 void
228 PyImport_Cleanup(void)
230 int pos, ndone;
231 char *name;
232 PyObject *key, *value, *dict;
233 PyInterpreterState *interp = PyThreadState_Get()->interp;
234 PyObject *modules = interp->modules;
236 if (modules == NULL)
237 return; /* Already done */
239 /* Delete some special variables first. These are common
240 places where user values hide and people complain when their
241 destructors fail. Since the modules containing them are
242 deleted *last* of all, they would come too late in the normal
243 destruction order. Sigh. */
245 value = PyDict_GetItemString(modules, "__builtin__");
246 if (value != NULL && PyModule_Check(value)) {
247 dict = PyModule_GetDict(value);
248 if (Py_VerboseFlag)
249 PySys_WriteStderr("# clear __builtin__._\n");
250 PyDict_SetItemString(dict, "_", Py_None);
252 value = PyDict_GetItemString(modules, "sys");
253 if (value != NULL && PyModule_Check(value)) {
254 char **p;
255 PyObject *v;
256 dict = PyModule_GetDict(value);
257 for (p = sys_deletes; *p != NULL; p++) {
258 if (Py_VerboseFlag)
259 PySys_WriteStderr("# clear sys.%s\n", *p);
260 PyDict_SetItemString(dict, *p, Py_None);
262 for (p = sys_files; *p != NULL; p+=2) {
263 if (Py_VerboseFlag)
264 PySys_WriteStderr("# restore sys.%s\n", *p);
265 v = PyDict_GetItemString(dict, *(p+1));
266 if (v == NULL)
267 v = Py_None;
268 PyDict_SetItemString(dict, *p, v);
272 /* First, delete __main__ */
273 value = PyDict_GetItemString(modules, "__main__");
274 if (value != NULL && PyModule_Check(value)) {
275 if (Py_VerboseFlag)
276 PySys_WriteStderr("# cleanup __main__\n");
277 _PyModule_Clear(value);
278 PyDict_SetItemString(modules, "__main__", Py_None);
281 /* The special treatment of __builtin__ here is because even
282 when it's not referenced as a module, its dictionary is
283 referenced by almost every module's __builtins__. Since
284 deleting a module clears its dictionary (even if there are
285 references left to it), we need to delete the __builtin__
286 module last. Likewise, we don't delete sys until the very
287 end because it is implicitly referenced (e.g. by print).
289 Also note that we 'delete' modules by replacing their entry
290 in the modules dict with None, rather than really deleting
291 them; this avoids a rehash of the modules dictionary and
292 also marks them as "non existent" so they won't be
293 re-imported. */
295 /* Next, repeatedly delete modules with a reference count of
296 one (skipping __builtin__ and sys) and delete them */
297 do {
298 ndone = 0;
299 pos = 0;
300 while (PyDict_Next(modules, &pos, &key, &value)) {
301 if (value->ob_refcnt != 1)
302 continue;
303 if (PyString_Check(key) && PyModule_Check(value)) {
304 name = PyString_AS_STRING(key);
305 if (strcmp(name, "__builtin__") == 0)
306 continue;
307 if (strcmp(name, "sys") == 0)
308 continue;
309 if (Py_VerboseFlag)
310 PySys_WriteStderr(
311 "# cleanup[1] %s\n", name);
312 _PyModule_Clear(value);
313 PyDict_SetItem(modules, key, Py_None);
314 ndone++;
317 } while (ndone > 0);
319 /* Next, delete all modules (still skipping __builtin__ and sys) */
320 pos = 0;
321 while (PyDict_Next(modules, &pos, &key, &value)) {
322 if (PyString_Check(key) && PyModule_Check(value)) {
323 name = PyString_AS_STRING(key);
324 if (strcmp(name, "__builtin__") == 0)
325 continue;
326 if (strcmp(name, "sys") == 0)
327 continue;
328 if (Py_VerboseFlag)
329 PySys_WriteStderr("# cleanup[2] %s\n", name);
330 _PyModule_Clear(value);
331 PyDict_SetItem(modules, key, Py_None);
335 /* Next, delete sys and __builtin__ (in that order) */
336 value = PyDict_GetItemString(modules, "sys");
337 if (value != NULL && PyModule_Check(value)) {
338 if (Py_VerboseFlag)
339 PySys_WriteStderr("# cleanup sys\n");
340 _PyModule_Clear(value);
341 PyDict_SetItemString(modules, "sys", Py_None);
343 value = PyDict_GetItemString(modules, "__builtin__");
344 if (value != NULL && PyModule_Check(value)) {
345 if (Py_VerboseFlag)
346 PySys_WriteStderr("# cleanup __builtin__\n");
347 _PyModule_Clear(value);
348 PyDict_SetItemString(modules, "__builtin__", Py_None);
351 /* Finally, clear and delete the modules directory */
352 PyDict_Clear(modules);
353 interp->modules = NULL;
354 Py_DECREF(modules);
358 /* Helper for pythonrun.c -- return magic number */
360 long
361 PyImport_GetMagicNumber(void)
363 return pyc_magic;
367 /* Magic for extension modules (built-in as well as dynamically
368 loaded). To prevent initializing an extension module more than
369 once, we keep a static dictionary 'extensions' keyed by module name
370 (for built-in modules) or by filename (for dynamically loaded
371 modules), containing these modules. A copy od the module's
372 dictionary is stored by calling _PyImport_FixupExtension()
373 immediately after the module initialization function succeeds. A
374 copy can be retrieved from there by calling
375 _PyImport_FindExtension(). */
377 PyObject *
378 _PyImport_FixupExtension(char *name, char *filename)
380 PyObject *modules, *mod, *dict, *copy;
381 if (extensions == NULL) {
382 extensions = PyDict_New();
383 if (extensions == NULL)
384 return NULL;
386 modules = PyImport_GetModuleDict();
387 mod = PyDict_GetItemString(modules, name);
388 if (mod == NULL || !PyModule_Check(mod)) {
389 PyErr_Format(PyExc_SystemError,
390 "_PyImport_FixupExtension: module %.200s not loaded", name);
391 return NULL;
393 dict = PyModule_GetDict(mod);
394 if (dict == NULL)
395 return NULL;
396 copy = PyObject_CallMethod(dict, "copy", "");
397 if (copy == NULL)
398 return NULL;
399 PyDict_SetItemString(extensions, filename, copy);
400 Py_DECREF(copy);
401 return copy;
404 PyObject *
405 _PyImport_FindExtension(char *name, char *filename)
407 PyObject *dict, *mod, *mdict, *result;
408 if (extensions == NULL)
409 return NULL;
410 dict = PyDict_GetItemString(extensions, filename);
411 if (dict == NULL)
412 return NULL;
413 mod = PyImport_AddModule(name);
414 if (mod == NULL)
415 return NULL;
416 mdict = PyModule_GetDict(mod);
417 if (mdict == NULL)
418 return NULL;
419 result = PyObject_CallMethod(mdict, "update", "O", dict);
420 if (result == NULL)
421 return NULL;
422 Py_DECREF(result);
423 if (Py_VerboseFlag)
424 PySys_WriteStderr("import %s # previously loaded (%s)\n",
425 name, filename);
426 return mod;
430 /* Get the module object corresponding to a module name.
431 First check the modules dictionary if there's one there,
432 if not, create a new one and insert in in the modules dictionary.
433 Because the former action is most common, THIS DOES NOT RETURN A
434 'NEW' REFERENCE! */
436 PyObject *
437 PyImport_AddModule(char *name)
439 PyObject *modules = PyImport_GetModuleDict();
440 PyObject *m;
442 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
443 PyModule_Check(m))
444 return m;
445 m = PyModule_New(name);
446 if (m == NULL)
447 return NULL;
448 if (PyDict_SetItemString(modules, name, m) != 0) {
449 Py_DECREF(m);
450 return NULL;
452 Py_DECREF(m); /* Yes, it still exists, in modules! */
454 return m;
458 /* Execute a code object in a module and return the module object
459 WITH INCREMENTED REFERENCE COUNT */
461 PyObject *
462 PyImport_ExecCodeModule(char *name, PyObject *co)
464 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
467 PyObject *
468 PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
470 PyObject *modules = PyImport_GetModuleDict();
471 PyObject *m, *d, *v;
473 m = PyImport_AddModule(name);
474 if (m == NULL)
475 return NULL;
476 d = PyModule_GetDict(m);
477 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
478 if (PyDict_SetItemString(d, "__builtins__",
479 PyEval_GetBuiltins()) != 0)
480 return NULL;
482 /* Remember the filename as the __file__ attribute */
483 v = NULL;
484 if (pathname != NULL) {
485 v = PyString_FromString(pathname);
486 if (v == NULL)
487 PyErr_Clear();
489 if (v == NULL) {
490 v = ((PyCodeObject *)co)->co_filename;
491 Py_INCREF(v);
493 if (PyDict_SetItemString(d, "__file__", v) != 0)
494 PyErr_Clear(); /* Not important enough to report */
495 Py_DECREF(v);
497 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
498 if (v == NULL)
499 return NULL;
500 Py_DECREF(v);
502 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
503 PyErr_Format(PyExc_ImportError,
504 "Loaded module %.200s not found in sys.modules",
505 name);
506 return NULL;
509 Py_INCREF(m);
511 return m;
515 /* Given a pathname for a Python source file, fill a buffer with the
516 pathname for the corresponding compiled file. Return the pathname
517 for the compiled file, or NULL if there's no space in the buffer.
518 Doesn't set an exception. */
520 static char *
521 make_compiled_pathname(char *pathname, char *buf, size_t buflen)
523 size_t len;
525 len = strlen(pathname);
526 if (len+2 > buflen)
527 return NULL;
528 strcpy(buf, pathname);
529 strcpy(buf+len, Py_OptimizeFlag ? "o" : "c");
531 return buf;
535 /* Given a pathname for a Python source file, its time of last
536 modification, and a pathname for a compiled file, check whether the
537 compiled file represents the same version of the source. If so,
538 return a FILE pointer for the compiled file, positioned just after
539 the header; if not, return NULL.
540 Doesn't set an exception. */
542 static FILE *
543 check_compiled_module(char *pathname, long mtime, char *cpathname)
545 FILE *fp;
546 long magic;
547 long pyc_mtime;
549 fp = fopen(cpathname, "rb");
550 if (fp == NULL)
551 return NULL;
552 magic = PyMarshal_ReadLongFromFile(fp);
553 if (magic != pyc_magic) {
554 if (Py_VerboseFlag)
555 PySys_WriteStderr("# %s has bad magic\n", cpathname);
556 fclose(fp);
557 return NULL;
559 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
560 if (pyc_mtime != mtime) {
561 if (Py_VerboseFlag)
562 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
563 fclose(fp);
564 return NULL;
566 if (Py_VerboseFlag)
567 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
568 return fp;
572 /* Read a code object from a file and check it for validity */
574 static PyCodeObject *
575 read_compiled_module(char *cpathname, FILE *fp)
577 PyObject *co;
579 co = PyMarshal_ReadObjectFromFile(fp);
580 /* Ugly: rd_object() may return NULL with or without error */
581 if (co == NULL || !PyCode_Check(co)) {
582 if (!PyErr_Occurred())
583 PyErr_Format(PyExc_ImportError,
584 "Non-code object in %.200s", cpathname);
585 Py_XDECREF(co);
586 return NULL;
588 return (PyCodeObject *)co;
592 /* Load a module from a compiled file, execute it, and return its
593 module object WITH INCREMENTED REFERENCE COUNT */
595 static PyObject *
596 load_compiled_module(char *name, char *cpathname, FILE *fp)
598 long magic;
599 PyCodeObject *co;
600 PyObject *m;
602 magic = PyMarshal_ReadLongFromFile(fp);
603 if (magic != pyc_magic) {
604 PyErr_Format(PyExc_ImportError,
605 "Bad magic number in %.200s", cpathname);
606 return NULL;
608 (void) PyMarshal_ReadLongFromFile(fp);
609 co = read_compiled_module(cpathname, fp);
610 if (co == NULL)
611 return NULL;
612 if (Py_VerboseFlag)
613 PySys_WriteStderr("import %s # precompiled from %s\n",
614 name, cpathname);
615 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
616 Py_DECREF(co);
618 return m;
621 /* Parse a source file and return the corresponding code object */
623 static PyCodeObject *
624 parse_source_module(char *pathname, FILE *fp)
626 PyCodeObject *co;
627 node *n;
629 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
630 if (n == NULL)
631 return NULL;
632 co = PyNode_Compile(n, pathname);
633 PyNode_Free(n);
635 return co;
639 /* Write a compiled module to a file, placing the time of last
640 modification of its source into the header.
641 Errors are ignored, if a write error occurs an attempt is made to
642 remove the file. */
644 static void
645 write_compiled_module(PyCodeObject *co, char *cpathname, long mtime)
647 FILE *fp;
649 fp = fopen(cpathname, "wb");
650 if (fp == NULL) {
651 if (Py_VerboseFlag)
652 PySys_WriteStderr(
653 "# can't create %s\n", cpathname);
654 return;
656 PyMarshal_WriteLongToFile(pyc_magic, fp);
657 /* First write a 0 for mtime */
658 PyMarshal_WriteLongToFile(0L, fp);
659 PyMarshal_WriteObjectToFile((PyObject *)co, fp);
660 if (ferror(fp)) {
661 if (Py_VerboseFlag)
662 PySys_WriteStderr("# can't write %s\n", cpathname);
663 /* Don't keep partial file */
664 fclose(fp);
665 (void) unlink(cpathname);
666 return;
668 /* Now write the true mtime */
669 fseek(fp, 4L, 0);
670 PyMarshal_WriteLongToFile(mtime, fp);
671 fflush(fp);
672 fclose(fp);
673 if (Py_VerboseFlag)
674 PySys_WriteStderr("# wrote %s\n", cpathname);
675 #ifdef macintosh
676 PyMac_setfiletype(cpathname, 'Pyth', 'PYC ');
677 #endif
681 /* Load a source module from a given file and return its module
682 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
683 byte-compiled file, use that instead. */
685 static PyObject *
686 load_source_module(char *name, char *pathname, FILE *fp)
688 time_t mtime;
689 FILE *fpc;
690 char buf[MAXPATHLEN+1];
691 char *cpathname;
692 PyCodeObject *co;
693 PyObject *m;
695 mtime = PyOS_GetLastModificationTime(pathname, fp);
696 if (mtime == -1)
697 return NULL;
698 #if SIZEOF_TIME_T > 4
699 /* Python's .pyc timestamp handling presumes that the timestamp fits
700 in 4 bytes. This will be fine until sometime in the year 2038,
701 when a 4-byte signed time_t will overflow.
703 if (mtime >> 32) {
704 PyErr_SetString(PyExc_OverflowError,
705 "modification time overflows a 4 bytes");
706 return NULL;
708 #endif
709 cpathname = make_compiled_pathname(pathname, buf, (size_t)MAXPATHLEN+1);
710 if (cpathname != NULL &&
711 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
712 co = read_compiled_module(cpathname, fpc);
713 fclose(fpc);
714 if (co == NULL)
715 return NULL;
716 if (Py_VerboseFlag)
717 PySys_WriteStderr("import %s # precompiled from %s\n",
718 name, cpathname);
719 pathname = cpathname;
721 else {
722 co = parse_source_module(pathname, fp);
723 if (co == NULL)
724 return NULL;
725 if (Py_VerboseFlag)
726 PySys_WriteStderr("import %s # from %s\n",
727 name, pathname);
728 write_compiled_module(co, cpathname, mtime);
730 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
731 Py_DECREF(co);
733 return m;
737 /* Forward */
738 static PyObject *load_module(char *, FILE *, char *, int);
739 static struct filedescr *find_module(char *, PyObject *,
740 char *, size_t, FILE **);
741 static struct _frozen *find_frozen(char *name);
743 /* Load a package and return its module object WITH INCREMENTED
744 REFERENCE COUNT */
746 static PyObject *
747 load_package(char *name, char *pathname)
749 PyObject *m, *d, *file, *path;
750 int err;
751 char buf[MAXPATHLEN+1];
752 FILE *fp = NULL;
753 struct filedescr *fdp;
755 m = PyImport_AddModule(name);
756 if (m == NULL)
757 return NULL;
758 if (Py_VerboseFlag)
759 PySys_WriteStderr("import %s # directory %s\n",
760 name, pathname);
761 d = PyModule_GetDict(m);
762 file = PyString_FromString(pathname);
763 if (file == NULL)
764 return NULL;
765 path = Py_BuildValue("[O]", file);
766 if (path == NULL) {
767 Py_DECREF(file);
768 return NULL;
770 err = PyDict_SetItemString(d, "__file__", file);
771 if (err == 0)
772 err = PyDict_SetItemString(d, "__path__", path);
773 if (err != 0) {
774 m = NULL;
775 goto cleanup;
777 buf[0] = '\0';
778 fdp = find_module("__init__", path, buf, sizeof(buf), &fp);
779 if (fdp == NULL) {
780 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
781 PyErr_Clear();
783 else
784 m = NULL;
785 goto cleanup;
787 m = load_module(name, fp, buf, fdp->type);
788 if (fp != NULL)
789 fclose(fp);
790 cleanup:
791 Py_XDECREF(path);
792 Py_XDECREF(file);
793 return m;
797 /* Helper to test for built-in module */
799 static int
800 is_builtin(char *name)
802 int i;
803 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
804 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
805 if (PyImport_Inittab[i].initfunc == NULL)
806 return -1;
807 else
808 return 1;
811 return 0;
815 /* Search the path (default sys.path) for a module. Return the
816 corresponding filedescr struct, and (via return arguments) the
817 pathname and an open file. Return NULL if the module is not found. */
819 #ifdef MS_COREDLL
820 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
821 char *, int);
822 #endif
824 #ifdef CHECK_IMPORT_CASE
825 static int check_case(char *, int, int, char *);
826 #endif
828 static int find_init_module(char *); /* Forward */
830 static struct filedescr *
831 find_module(char *realname, PyObject *path, char *buf, size_t buflen,
832 FILE **p_fp)
834 int i, npath;
835 size_t 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 if (strlen(realname) > MAXPATHLEN) {
846 PyErr_SetString(PyExc_OverflowError, "module name is too long");
847 return NULL;
849 strcpy(name, realname);
851 if (path != NULL && PyString_Check(path)) {
852 /* Submodule of "frozen" package:
853 Set name to the fullname, path to NULL
854 and continue as "usual" */
855 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
856 PyErr_SetString(PyExc_ImportError,
857 "full frozen module name too long");
858 return NULL;
860 strcpy(buf, PyString_AsString(path));
861 strcat(buf, ".");
862 strcat(buf, name);
863 strcpy(name, buf);
864 path = NULL;
866 if (path == NULL) {
867 if (is_builtin(name)) {
868 strcpy(buf, name);
869 return &fd_builtin;
871 if ((f = find_frozen(name)) != NULL) {
872 strcpy(buf, name);
873 return &fd_frozen;
876 #ifdef MS_COREDLL
877 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
878 if (fp != NULL) {
879 *p_fp = fp;
880 return fdp;
882 #endif
883 path = PySys_GetObject("path");
885 if (path == NULL || !PyList_Check(path)) {
886 PyErr_SetString(PyExc_ImportError,
887 "sys.path must be a list of directory names");
888 return NULL;
890 npath = PyList_Size(path);
891 namelen = strlen(name);
892 for (i = 0; i < npath; i++) {
893 PyObject *v = PyList_GetItem(path, i);
894 if (!PyString_Check(v))
895 continue;
896 len = PyString_Size(v);
897 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen)
898 continue; /* Too long */
899 strcpy(buf, PyString_AsString(v));
900 if (strlen(buf) != len)
901 continue; /* v contains '\0' */
902 #ifdef macintosh
903 #ifdef INTERN_STRINGS
905 ** Speedup: each sys.path item is interned, and
906 ** FindResourceModule remembers which items refer to
907 ** folders (so we don't have to bother trying to look
908 ** into them for resources).
910 PyString_InternInPlace(&PyList_GET_ITEM(path, i));
911 v = PyList_GET_ITEM(path, i);
912 #endif
913 if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
914 static struct filedescr resfiledescr =
915 {"", "", PY_RESOURCE};
917 return &resfiledescr;
919 if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
920 static struct filedescr resfiledescr =
921 {"", "", PY_CODERESOURCE};
923 return &resfiledescr;
925 #endif
926 if (len > 0 && buf[len-1] != SEP
927 #ifdef ALTSEP
928 && buf[len-1] != ALTSEP
929 #endif
931 buf[len++] = SEP;
932 #ifdef IMPORT_8x3_NAMES
933 /* see if we are searching in directory dos-8x3 */
934 if (len > 7 && !strncmp(buf + len - 8, "dos-8x3", 7)){
935 int j;
936 char ch; /* limit name to 8 lower-case characters */
937 for (j = 0; (ch = name[j]) && j < 8; j++)
938 if (isupper(ch))
939 buf[len++] = tolower(ch);
940 else
941 buf[len++] = ch;
943 else /* Not in dos-8x3, use the full name */
944 #endif
946 strcpy(buf+len, name);
947 len += namelen;
949 #ifdef HAVE_STAT
950 if (stat(buf, &statbuf) == 0) {
951 if (S_ISDIR(statbuf.st_mode)) {
952 if (find_init_module(buf)) {
953 #ifdef CHECK_IMPORT_CASE
954 if (!check_case(buf, len, namelen,
955 name))
956 return NULL;
957 #endif
958 return &fd_package;
962 #else
963 /* XXX How are you going to test for directories? */
964 #endif
965 #ifdef macintosh
966 fdp = PyMac_FindModuleExtension(buf, &len, name);
967 if (fdp)
968 fp = fopen(buf, fdp->mode);
969 #else
970 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
971 strcpy(buf+len, fdp->suffix);
972 if (Py_VerboseFlag > 1)
973 PySys_WriteStderr("# trying %s\n", buf);
974 fp = fopen(buf, fdp->mode);
975 if (fp != NULL)
976 break;
978 #endif /* !macintosh */
979 if (fp != NULL)
980 break;
982 if (fp == NULL) {
983 PyErr_Format(PyExc_ImportError,
984 "No module named %.200s", name);
985 return NULL;
987 #ifdef CHECK_IMPORT_CASE
988 if (!check_case(buf, len, namelen, name)) {
989 fclose(fp);
990 return NULL;
992 #endif
994 *p_fp = fp;
995 return fdp;
998 #ifdef CHECK_IMPORT_CASE
1000 #ifdef MS_WIN32
1001 #include <windows.h>
1002 #include <ctype.h>
1004 static int
1005 allcaps8x3(char *s)
1007 /* Return 1 if s is an 8.3 filename in ALLCAPS */
1008 char c;
1009 char *dot = strchr(s, '.');
1010 char *end = strchr(s, '\0');
1011 if (dot != NULL) {
1012 if (dot-s > 8)
1013 return 0; /* More than 8 before '.' */
1014 if (end-dot > 4)
1015 return 0; /* More than 3 after '.' */
1016 end = strchr(dot+1, '.');
1017 if (end != NULL)
1018 return 0; /* More than one dot */
1020 else if (end-s > 8)
1021 return 0; /* More than 8 and no dot */
1022 while ((c = *s++)) {
1023 if (islower(c))
1024 return 0;
1026 return 1;
1029 static int
1030 check_case(char *buf, int len, int namelen, char *name)
1032 WIN32_FIND_DATA data;
1033 HANDLE h;
1034 if (getenv("PYTHONCASEOK") != NULL)
1035 return 1;
1036 h = FindFirstFile(buf, &data);
1037 if (h == INVALID_HANDLE_VALUE) {
1038 PyErr_Format(PyExc_NameError,
1039 "Can't find file for module %.100s\n(filename %.300s)",
1040 name, buf);
1041 return 0;
1043 FindClose(h);
1044 if (allcaps8x3(data.cFileName)) {
1045 /* Skip the test if the filename is ALL.CAPS. This can
1046 happen in certain circumstances beyond our control,
1047 e.g. when software is installed under NT on a FAT
1048 filesystem and then the same FAT filesystem is used
1049 under Windows 95. */
1050 return 1;
1052 if (strncmp(data.cFileName, name, namelen) != 0) {
1053 strcpy(buf+len-namelen, data.cFileName);
1054 PyErr_Format(PyExc_NameError,
1055 "Case mismatch for module name %.100s\n(filename %.300s)",
1056 name, buf);
1057 return 0;
1059 return 1;
1061 #endif /* MS_WIN32 */
1063 #ifdef macintosh
1064 #include <TextUtils.h>
1065 #ifdef USE_GUSI1
1066 #include "TFileSpec.h" /* for Path2FSSpec() */
1067 #endif
1068 static int
1069 check_case(char *buf, int len, int namelen, char *name)
1071 FSSpec fss;
1072 OSErr err;
1073 #ifndef USE_GUSI1
1074 err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
1075 #else
1076 /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
1077 the way, which is fine for all directories, but here we need
1078 the original name of the alias file (say, Dlg.ppc.slb, not
1079 toolboxmodules.ppc.slb). */
1080 char *colon;
1081 err = Path2FSSpec(buf, &fss);
1082 if (err == noErr) {
1083 colon = strrchr(buf, ':'); /* find filename */
1084 if (colon != NULL)
1085 err = FSMakeFSSpec(fss.vRefNum, fss.parID,
1086 Pstring(colon+1), &fss);
1087 else
1088 err = FSMakeFSSpec(fss.vRefNum, fss.parID,
1089 fss.name, &fss);
1091 #endif
1092 if (err) {
1093 PyErr_Format(PyExc_NameError,
1094 "Can't find file for module %.100s\n(filename %.300s)",
1095 name, buf);
1096 return 0;
1098 if ( namelen > fss.name[0] || strncmp(name, (char *)fss.name+1, namelen) != 0 ) {
1099 PyErr_Format(PyExc_NameError,
1100 "Case mismatch for module name %.100s\n(filename %.300s)",
1101 name, fss.name);
1102 return 0;
1104 return 1;
1106 #endif /* macintosh */
1108 #ifdef DJGPP
1109 #include <dir.h>
1111 static int
1112 check_case(char *buf, int len, int namelen, char *name)
1114 struct ffblk ffblk;
1115 int done;
1117 if (getenv("PYTHONCASEOK") != NULL)
1118 return 1;
1119 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1120 if (done) {
1121 PyErr_Format(PyExc_NameError,
1122 "Can't find file for module %.100s\n(filename %.300s)",
1123 name, buf);
1124 return 0;
1127 if (strncmp(ffblk.ff_name, name, namelen) != 0) {
1128 strcpy(buf+len-namelen, ffblk.ff_name);
1129 PyErr_Format(PyExc_NameError,
1130 "Case mismatch for module name %.100s\n(filename %.300s)",
1131 name, buf);
1132 return 0;
1134 return 1;
1136 #endif
1138 #endif /* CHECK_IMPORT_CASE */
1140 #ifdef HAVE_STAT
1141 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1142 static int
1143 find_init_module(char *buf)
1145 size_t save_len = strlen(buf);
1146 size_t i = save_len;
1147 struct stat statbuf;
1149 if (save_len + 13 >= MAXPATHLEN)
1150 return 0;
1151 buf[i++] = SEP;
1152 strcpy(buf+i, "__init__.py");
1153 if (stat(buf, &statbuf) == 0) {
1154 buf[save_len] = '\0';
1155 return 1;
1157 i += strlen(buf+i);
1158 if (Py_OptimizeFlag)
1159 strcpy(buf+i, "o");
1160 else
1161 strcpy(buf+i, "c");
1162 if (stat(buf, &statbuf) == 0) {
1163 buf[save_len] = '\0';
1164 return 1;
1166 buf[save_len] = '\0';
1167 return 0;
1169 #endif /* HAVE_STAT */
1172 static int init_builtin(char *); /* Forward */
1174 /* Load an external module using the default search path and return
1175 its module object WITH INCREMENTED REFERENCE COUNT */
1177 static PyObject *
1178 load_module(char *name, FILE *fp, char *buf, int type)
1180 PyObject *modules;
1181 PyObject *m;
1182 int err;
1184 /* First check that there's an open file (if we need one) */
1185 switch (type) {
1186 case PY_SOURCE:
1187 case PY_COMPILED:
1188 if (fp == NULL) {
1189 PyErr_Format(PyExc_ValueError,
1190 "file object required for import (type code %d)",
1191 type);
1192 return NULL;
1196 switch (type) {
1198 case PY_SOURCE:
1199 m = load_source_module(name, buf, fp);
1200 break;
1202 case PY_COMPILED:
1203 m = load_compiled_module(name, buf, fp);
1204 break;
1206 #ifdef HAVE_DYNAMIC_LOADING
1207 case C_EXTENSION:
1208 m = _PyImport_LoadDynamicModule(name, buf, fp);
1209 break;
1210 #endif
1212 #ifdef macintosh
1213 case PY_RESOURCE:
1214 m = PyMac_LoadResourceModule(name, buf);
1215 break;
1216 case PY_CODERESOURCE:
1217 m = PyMac_LoadCodeResourceModule(name, buf);
1218 break;
1219 #endif
1221 case PKG_DIRECTORY:
1222 m = load_package(name, buf);
1223 break;
1225 case C_BUILTIN:
1226 case PY_FROZEN:
1227 if (buf != NULL && buf[0] != '\0')
1228 name = buf;
1229 if (type == C_BUILTIN)
1230 err = init_builtin(name);
1231 else
1232 err = PyImport_ImportFrozenModule(name);
1233 if (err < 0)
1234 return NULL;
1235 if (err == 0) {
1236 PyErr_Format(PyExc_ImportError,
1237 "Purported %s module %.200s not found",
1238 type == C_BUILTIN ?
1239 "builtin" : "frozen",
1240 name);
1241 return NULL;
1243 modules = PyImport_GetModuleDict();
1244 m = PyDict_GetItemString(modules, name);
1245 if (m == NULL) {
1246 PyErr_Format(
1247 PyExc_ImportError,
1248 "%s module %.200s not properly initialized",
1249 type == C_BUILTIN ?
1250 "builtin" : "frozen",
1251 name);
1252 return NULL;
1254 Py_INCREF(m);
1255 break;
1257 default:
1258 PyErr_Format(PyExc_ImportError,
1259 "Don't know how to import %.200s (type code %d)",
1260 name, type);
1261 m = NULL;
1265 return m;
1269 /* Initialize a built-in module.
1270 Return 1 for succes, 0 if the module is not found, and -1 with
1271 an exception set if the initialization failed. */
1273 static int
1274 init_builtin(char *name)
1276 struct _inittab *p;
1277 PyObject *mod;
1279 if ((mod = _PyImport_FindExtension(name, name)) != NULL)
1280 return 1;
1282 for (p = PyImport_Inittab; p->name != NULL; p++) {
1283 if (strcmp(name, p->name) == 0) {
1284 if (p->initfunc == NULL) {
1285 PyErr_Format(PyExc_ImportError,
1286 "Cannot re-init internal module %.200s",
1287 name);
1288 return -1;
1290 if (Py_VerboseFlag)
1291 PySys_WriteStderr("import %s # builtin\n", name);
1292 (*p->initfunc)();
1293 if (PyErr_Occurred())
1294 return -1;
1295 if (_PyImport_FixupExtension(name, name) == NULL)
1296 return -1;
1297 return 1;
1300 return 0;
1304 /* Frozen modules */
1306 static struct _frozen *
1307 find_frozen(char *name)
1309 struct _frozen *p;
1311 for (p = PyImport_FrozenModules; ; p++) {
1312 if (p->name == NULL)
1313 return NULL;
1314 if (strcmp(p->name, name) == 0)
1315 break;
1317 return p;
1320 static PyObject *
1321 get_frozen_object(char *name)
1323 struct _frozen *p = find_frozen(name);
1324 int size;
1326 if (p == NULL) {
1327 PyErr_Format(PyExc_ImportError,
1328 "No such frozen object named %.200s",
1329 name);
1330 return NULL;
1332 size = p->size;
1333 if (size < 0)
1334 size = -size;
1335 return PyMarshal_ReadObjectFromString((char *)p->code, size);
1338 /* Initialize a frozen module.
1339 Return 1 for succes, 0 if the module is not found, and -1 with
1340 an exception set if the initialization failed.
1341 This function is also used from frozenmain.c */
1344 PyImport_ImportFrozenModule(char *name)
1346 struct _frozen *p = find_frozen(name);
1347 PyObject *co;
1348 PyObject *m;
1349 int ispackage;
1350 int size;
1352 if (p == NULL)
1353 return 0;
1354 size = p->size;
1355 ispackage = (size < 0);
1356 if (ispackage)
1357 size = -size;
1358 if (Py_VerboseFlag)
1359 PySys_WriteStderr("import %s # frozen%s\n",
1360 name, ispackage ? " package" : "");
1361 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1362 if (co == NULL)
1363 return -1;
1364 if (!PyCode_Check(co)) {
1365 Py_DECREF(co);
1366 PyErr_Format(PyExc_TypeError,
1367 "frozen object %.200s is not a code object",
1368 name);
1369 return -1;
1371 if (ispackage) {
1372 /* Set __path__ to the package name */
1373 PyObject *d, *s;
1374 int err;
1375 m = PyImport_AddModule(name);
1376 if (m == NULL)
1377 return -1;
1378 d = PyModule_GetDict(m);
1379 s = PyString_InternFromString(name);
1380 if (s == NULL)
1381 return -1;
1382 err = PyDict_SetItemString(d, "__path__", s);
1383 Py_DECREF(s);
1384 if (err != 0)
1385 return err;
1387 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
1388 Py_DECREF(co);
1389 if (m == NULL)
1390 return -1;
1391 Py_DECREF(m);
1392 return 1;
1396 /* Import a module, either built-in, frozen, or external, and return
1397 its module object WITH INCREMENTED REFERENCE COUNT */
1399 PyObject *
1400 PyImport_ImportModule(char *name)
1402 static PyObject *fromlist = NULL;
1403 if (fromlist == NULL && strchr(name, '.') != NULL) {
1404 fromlist = Py_BuildValue("[s]", "*");
1405 if (fromlist == NULL)
1406 return NULL;
1408 return PyImport_ImportModuleEx(name, NULL, NULL, fromlist);
1411 /* Forward declarations for helper routines */
1412 static PyObject *get_parent(PyObject *globals, char *buf, int *p_buflen);
1413 static PyObject *load_next(PyObject *mod, PyObject *altmod,
1414 char **p_name, char *buf, int *p_buflen);
1415 static int mark_miss(char *name);
1416 static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1417 char *buf, int buflen, int recursive);
1418 static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
1420 /* The Magnum Opus of dotted-name import :-) */
1422 static PyObject *
1423 import_module_ex(char *name, PyObject *globals, PyObject *locals,
1424 PyObject *fromlist)
1426 char buf[MAXPATHLEN+1];
1427 int buflen = 0;
1428 PyObject *parent, *head, *next, *tail;
1430 parent = get_parent(globals, buf, &buflen);
1431 if (parent == NULL)
1432 return NULL;
1434 head = load_next(parent, Py_None, &name, buf, &buflen);
1435 if (head == NULL)
1436 return NULL;
1438 tail = head;
1439 Py_INCREF(tail);
1440 while (name) {
1441 next = load_next(tail, tail, &name, buf, &buflen);
1442 Py_DECREF(tail);
1443 if (next == NULL) {
1444 Py_DECREF(head);
1445 return NULL;
1447 tail = next;
1450 if (fromlist != NULL) {
1451 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1452 fromlist = NULL;
1455 if (fromlist == NULL) {
1456 Py_DECREF(tail);
1457 return head;
1460 Py_DECREF(head);
1461 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
1462 Py_DECREF(tail);
1463 return NULL;
1466 return tail;
1469 PyObject *
1470 PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1471 PyObject *fromlist)
1473 PyObject *result;
1474 lock_import();
1475 result = import_module_ex(name, globals, locals, fromlist);
1476 unlock_import();
1477 return result;
1480 static PyObject *
1481 get_parent(PyObject *globals, char *buf, int *p_buflen)
1483 static PyObject *namestr = NULL;
1484 static PyObject *pathstr = NULL;
1485 PyObject *modname, *modpath, *modules, *parent;
1487 if (globals == NULL || !PyDict_Check(globals))
1488 return Py_None;
1490 if (namestr == NULL) {
1491 namestr = PyString_InternFromString("__name__");
1492 if (namestr == NULL)
1493 return NULL;
1495 if (pathstr == NULL) {
1496 pathstr = PyString_InternFromString("__path__");
1497 if (pathstr == NULL)
1498 return NULL;
1501 *buf = '\0';
1502 *p_buflen = 0;
1503 modname = PyDict_GetItem(globals, namestr);
1504 if (modname == NULL || !PyString_Check(modname))
1505 return Py_None;
1507 modpath = PyDict_GetItem(globals, pathstr);
1508 if (modpath != NULL) {
1509 int len = PyString_GET_SIZE(modname);
1510 if (len > MAXPATHLEN) {
1511 PyErr_SetString(PyExc_ValueError,
1512 "Module name too long");
1513 return NULL;
1515 strcpy(buf, PyString_AS_STRING(modname));
1516 *p_buflen = len;
1518 else {
1519 char *start = PyString_AS_STRING(modname);
1520 char *lastdot = strrchr(start, '.');
1521 size_t len;
1522 if (lastdot == NULL)
1523 return Py_None;
1524 len = lastdot - start;
1525 if (len >= MAXPATHLEN) {
1526 PyErr_SetString(PyExc_ValueError,
1527 "Module name too long");
1528 return NULL;
1530 strncpy(buf, start, len);
1531 buf[len] = '\0';
1532 *p_buflen = len;
1535 modules = PyImport_GetModuleDict();
1536 parent = PyDict_GetItemString(modules, buf);
1537 if (parent == NULL)
1538 parent = Py_None;
1539 return parent;
1540 /* We expect, but can't guarantee, if parent != None, that:
1541 - parent.__name__ == buf
1542 - parent.__dict__ is globals
1543 If this is violated... Who cares? */
1546 /* altmod is either None or same as mod */
1547 static PyObject *
1548 load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
1549 int *p_buflen)
1551 char *name = *p_name;
1552 char *dot = strchr(name, '.');
1553 size_t len;
1554 char *p;
1555 PyObject *result;
1557 if (dot == NULL) {
1558 *p_name = NULL;
1559 len = strlen(name);
1561 else {
1562 *p_name = dot+1;
1563 len = dot-name;
1565 if (len == 0) {
1566 PyErr_SetString(PyExc_ValueError,
1567 "Empty module name");
1568 return NULL;
1571 p = buf + *p_buflen;
1572 if (p != buf)
1573 *p++ = '.';
1574 if (p+len-buf >= MAXPATHLEN) {
1575 PyErr_SetString(PyExc_ValueError,
1576 "Module name too long");
1577 return NULL;
1579 strncpy(p, name, len);
1580 p[len] = '\0';
1581 *p_buflen = p+len-buf;
1583 result = import_submodule(mod, p, buf);
1584 if (result == Py_None && altmod != mod) {
1585 Py_DECREF(result);
1586 /* Here, altmod must be None and mod must not be None */
1587 result = import_submodule(altmod, p, p);
1588 if (result != NULL && result != Py_None) {
1589 if (mark_miss(buf) != 0) {
1590 Py_DECREF(result);
1591 return NULL;
1593 strncpy(buf, name, len);
1594 buf[len] = '\0';
1595 *p_buflen = len;
1598 if (result == NULL)
1599 return NULL;
1601 if (result == Py_None) {
1602 Py_DECREF(result);
1603 PyErr_Format(PyExc_ImportError,
1604 "No module named %.200s", name);
1605 return NULL;
1608 return result;
1611 static int
1612 mark_miss(char *name)
1614 PyObject *modules = PyImport_GetModuleDict();
1615 return PyDict_SetItemString(modules, name, Py_None);
1618 static int
1619 ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen,
1620 int recursive)
1622 int i;
1624 if (!PyObject_HasAttrString(mod, "__path__"))
1625 return 1;
1627 for (i = 0; ; i++) {
1628 PyObject *item = PySequence_GetItem(fromlist, i);
1629 int hasit;
1630 if (item == NULL) {
1631 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1632 PyErr_Clear();
1633 return 1;
1635 return 0;
1637 if (!PyString_Check(item)) {
1638 PyErr_SetString(PyExc_TypeError,
1639 "Item in ``from list'' not a string");
1640 Py_DECREF(item);
1641 return 0;
1643 if (PyString_AS_STRING(item)[0] == '*') {
1644 PyObject *all;
1645 Py_DECREF(item);
1646 /* See if the package defines __all__ */
1647 if (recursive)
1648 continue; /* Avoid endless recursion */
1649 all = PyObject_GetAttrString(mod, "__all__");
1650 if (all == NULL)
1651 PyErr_Clear();
1652 else {
1653 if (!ensure_fromlist(mod, all, buf, buflen, 1))
1654 return 0;
1655 Py_DECREF(all);
1657 continue;
1659 hasit = PyObject_HasAttr(mod, item);
1660 if (!hasit) {
1661 char *subname = PyString_AS_STRING(item);
1662 PyObject *submod;
1663 char *p;
1664 if (buflen + strlen(subname) >= MAXPATHLEN) {
1665 PyErr_SetString(PyExc_ValueError,
1666 "Module name too long");
1667 Py_DECREF(item);
1668 return 0;
1670 p = buf + buflen;
1671 *p++ = '.';
1672 strcpy(p, subname);
1673 submod = import_submodule(mod, subname, buf);
1674 Py_XDECREF(submod);
1675 if (submod == NULL) {
1676 Py_DECREF(item);
1677 return 0;
1680 Py_DECREF(item);
1683 /* NOTREACHED */
1686 static PyObject *
1687 import_submodule(PyObject *mod, char *subname, char *fullname)
1689 PyObject *modules = PyImport_GetModuleDict();
1690 PyObject *m;
1692 /* Require:
1693 if mod == None: subname == fullname
1694 else: mod.__name__ + "." + subname == fullname
1697 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
1698 Py_INCREF(m);
1700 else {
1701 PyObject *path;
1702 char buf[MAXPATHLEN+1];
1703 struct filedescr *fdp;
1704 FILE *fp = NULL;
1706 if (mod == Py_None)
1707 path = NULL;
1708 else {
1709 path = PyObject_GetAttrString(mod, "__path__");
1710 if (path == NULL) {
1711 PyErr_Clear();
1712 Py_INCREF(Py_None);
1713 return Py_None;
1717 buf[0] = '\0';
1718 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1719 Py_XDECREF(path);
1720 if (fdp == NULL) {
1721 if (!PyErr_ExceptionMatches(PyExc_ImportError))
1722 return NULL;
1723 PyErr_Clear();
1724 Py_INCREF(Py_None);
1725 return Py_None;
1727 m = load_module(fullname, fp, buf, fdp->type);
1728 if (fp)
1729 fclose(fp);
1730 if (m != NULL && mod != Py_None) {
1731 if (PyObject_SetAttrString(mod, subname, m) < 0) {
1732 Py_DECREF(m);
1733 m = NULL;
1738 return m;
1742 /* Re-import a module of any kind and return its module object, WITH
1743 INCREMENTED REFERENCE COUNT */
1745 PyObject *
1746 PyImport_ReloadModule(PyObject *m)
1748 PyObject *modules = PyImport_GetModuleDict();
1749 PyObject *path = NULL;
1750 char *name, *subname;
1751 char buf[MAXPATHLEN+1];
1752 struct filedescr *fdp;
1753 FILE *fp = NULL;
1755 if (m == NULL || !PyModule_Check(m)) {
1756 PyErr_SetString(PyExc_TypeError,
1757 "reload() argument must be module");
1758 return NULL;
1760 name = PyModule_GetName(m);
1761 if (name == NULL)
1762 return NULL;
1763 if (m != PyDict_GetItemString(modules, name)) {
1764 PyErr_Format(PyExc_ImportError,
1765 "reload(): module %.200s not in sys.modules",
1766 name);
1767 return NULL;
1769 subname = strrchr(name, '.');
1770 if (subname == NULL)
1771 subname = name;
1772 else {
1773 PyObject *parentname, *parent;
1774 parentname = PyString_FromStringAndSize(name, (subname-name));
1775 if (parentname == NULL)
1776 return NULL;
1777 parent = PyDict_GetItem(modules, parentname);
1778 Py_DECREF(parentname);
1779 if (parent == NULL) {
1780 PyErr_Format(PyExc_ImportError,
1781 "reload(): parent %.200s not in sys.modules",
1782 name);
1783 return NULL;
1785 subname++;
1786 path = PyObject_GetAttrString(parent, "__path__");
1787 if (path == NULL)
1788 PyErr_Clear();
1790 buf[0] = '\0';
1791 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1792 Py_XDECREF(path);
1793 if (fdp == NULL)
1794 return NULL;
1795 m = load_module(name, fp, buf, fdp->type);
1796 if (fp)
1797 fclose(fp);
1798 return m;
1802 /* Higher-level import emulator which emulates the "import" statement
1803 more accurately -- it invokes the __import__() function from the
1804 builtins of the current globals. This means that the import is
1805 done using whatever import hooks are installed in the current
1806 environment, e.g. by "rexec".
1807 A dummy list ["__doc__"] is passed as the 4th argument so that
1808 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1809 will return <module "gencache"> instead of <module "win32com">. */
1811 PyObject *
1812 PyImport_Import(PyObject *module_name)
1814 static PyObject *silly_list = NULL;
1815 static PyObject *builtins_str = NULL;
1816 static PyObject *import_str = NULL;
1817 static PyObject *standard_builtins = NULL;
1818 PyObject *globals = NULL;
1819 PyObject *import = NULL;
1820 PyObject *builtins = NULL;
1821 PyObject *r = NULL;
1823 /* Initialize constant string objects */
1824 if (silly_list == NULL) {
1825 import_str = PyString_InternFromString("__import__");
1826 if (import_str == NULL)
1827 return NULL;
1828 builtins_str = PyString_InternFromString("__builtins__");
1829 if (builtins_str == NULL)
1830 return NULL;
1831 silly_list = Py_BuildValue("[s]", "__doc__");
1832 if (silly_list == NULL)
1833 return NULL;
1836 /* Get the builtins from current globals */
1837 globals = PyEval_GetGlobals();
1838 if(globals != NULL) {
1839 Py_INCREF(globals);
1840 builtins = PyObject_GetItem(globals, builtins_str);
1841 if (builtins == NULL)
1842 goto err;
1844 else {
1845 /* No globals -- use standard builtins, and fake globals */
1846 PyErr_Clear();
1848 if (standard_builtins == NULL) {
1849 standard_builtins =
1850 PyImport_ImportModule("__builtin__");
1851 if (standard_builtins == NULL)
1852 return NULL;
1855 builtins = standard_builtins;
1856 Py_INCREF(builtins);
1857 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1858 if (globals == NULL)
1859 goto err;
1862 /* Get the __import__ function from the builtins */
1863 if (PyDict_Check(builtins))
1864 import=PyObject_GetItem(builtins, import_str);
1865 else
1866 import=PyObject_GetAttr(builtins, import_str);
1867 if (import == NULL)
1868 goto err;
1870 /* Call the _import__ function with the proper argument list */
1871 r = PyObject_CallFunction(import, "OOOO",
1872 module_name, globals, globals, silly_list);
1874 err:
1875 Py_XDECREF(globals);
1876 Py_XDECREF(builtins);
1877 Py_XDECREF(import);
1879 return r;
1883 /* Module 'imp' provides Python access to the primitives used for
1884 importing modules.
1887 static PyObject *
1888 imp_get_magic(PyObject *self, PyObject *args)
1890 char buf[4];
1892 if (!PyArg_ParseTuple(args, ":get_magic"))
1893 return NULL;
1894 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
1895 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
1896 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
1897 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
1899 return PyString_FromStringAndSize(buf, 4);
1902 static PyObject *
1903 imp_get_suffixes(PyObject *self, PyObject *args)
1905 PyObject *list;
1906 struct filedescr *fdp;
1908 if (!PyArg_ParseTuple(args, ":get_suffixes"))
1909 return NULL;
1910 list = PyList_New(0);
1911 if (list == NULL)
1912 return NULL;
1913 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1914 PyObject *item = Py_BuildValue("ssi",
1915 fdp->suffix, fdp->mode, fdp->type);
1916 if (item == NULL) {
1917 Py_DECREF(list);
1918 return NULL;
1920 if (PyList_Append(list, item) < 0) {
1921 Py_DECREF(list);
1922 Py_DECREF(item);
1923 return NULL;
1925 Py_DECREF(item);
1927 return list;
1930 static PyObject *
1931 call_find_module(char *name, PyObject *path)
1933 extern int fclose(FILE *);
1934 PyObject *fob, *ret;
1935 struct filedescr *fdp;
1936 char pathname[MAXPATHLEN+1];
1937 FILE *fp = NULL;
1939 pathname[0] = '\0';
1940 if (path == Py_None)
1941 path = NULL;
1942 fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
1943 if (fdp == NULL)
1944 return NULL;
1945 if (fp != NULL) {
1946 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
1947 if (fob == NULL) {
1948 fclose(fp);
1949 return NULL;
1952 else {
1953 fob = Py_None;
1954 Py_INCREF(fob);
1956 ret = Py_BuildValue("Os(ssi)",
1957 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
1958 Py_DECREF(fob);
1959 return ret;
1962 static PyObject *
1963 imp_find_module(PyObject *self, PyObject *args)
1965 char *name;
1966 PyObject *path = NULL;
1967 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
1968 return NULL;
1969 return call_find_module(name, path);
1972 static PyObject *
1973 imp_init_builtin(PyObject *self, PyObject *args)
1975 char *name;
1976 int ret;
1977 PyObject *m;
1978 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
1979 return NULL;
1980 ret = init_builtin(name);
1981 if (ret < 0)
1982 return NULL;
1983 if (ret == 0) {
1984 Py_INCREF(Py_None);
1985 return Py_None;
1987 m = PyImport_AddModule(name);
1988 Py_XINCREF(m);
1989 return m;
1992 static PyObject *
1993 imp_init_frozen(PyObject *self, PyObject *args)
1995 char *name;
1996 int ret;
1997 PyObject *m;
1998 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
1999 return NULL;
2000 ret = PyImport_ImportFrozenModule(name);
2001 if (ret < 0)
2002 return NULL;
2003 if (ret == 0) {
2004 Py_INCREF(Py_None);
2005 return Py_None;
2007 m = PyImport_AddModule(name);
2008 Py_XINCREF(m);
2009 return m;
2012 static PyObject *
2013 imp_get_frozen_object(PyObject *self, PyObject *args)
2015 char *name;
2017 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2018 return NULL;
2019 return get_frozen_object(name);
2022 static PyObject *
2023 imp_is_builtin(PyObject *self, PyObject *args)
2025 char *name;
2026 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2027 return NULL;
2028 return PyInt_FromLong(is_builtin(name));
2031 static PyObject *
2032 imp_is_frozen(PyObject *self, PyObject *args)
2034 char *name;
2035 struct _frozen *p;
2036 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
2037 return NULL;
2038 p = find_frozen(name);
2039 return PyInt_FromLong((long) (p == NULL ? 0 : p->size));
2042 static FILE *
2043 get_file(char *pathname, PyObject *fob, char *mode)
2045 FILE *fp;
2046 if (fob == NULL) {
2047 fp = fopen(pathname, mode);
2048 if (fp == NULL)
2049 PyErr_SetFromErrno(PyExc_IOError);
2051 else {
2052 fp = PyFile_AsFile(fob);
2053 if (fp == NULL)
2054 PyErr_SetString(PyExc_ValueError,
2055 "bad/closed file object");
2057 return fp;
2060 static PyObject *
2061 imp_load_compiled(PyObject *self, PyObject *args)
2063 char *name;
2064 char *pathname;
2065 PyObject *fob = NULL;
2066 PyObject *m;
2067 FILE *fp;
2068 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
2069 &PyFile_Type, &fob))
2070 return NULL;
2071 fp = get_file(pathname, fob, "rb");
2072 if (fp == NULL)
2073 return NULL;
2074 m = load_compiled_module(name, pathname, fp);
2075 if (fob == NULL)
2076 fclose(fp);
2077 return m;
2080 #ifdef HAVE_DYNAMIC_LOADING
2082 static PyObject *
2083 imp_load_dynamic(PyObject *self, PyObject *args)
2085 char *name;
2086 char *pathname;
2087 PyObject *fob = NULL;
2088 PyObject *m;
2089 FILE *fp = NULL;
2090 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
2091 &PyFile_Type, &fob))
2092 return NULL;
2093 if (fob) {
2094 fp = get_file(pathname, fob, "r");
2095 if (fp == NULL)
2096 return NULL;
2098 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2099 return m;
2102 #endif /* HAVE_DYNAMIC_LOADING */
2104 static PyObject *
2105 imp_load_source(PyObject *self, PyObject *args)
2107 char *name;
2108 char *pathname;
2109 PyObject *fob = NULL;
2110 PyObject *m;
2111 FILE *fp;
2112 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
2113 &PyFile_Type, &fob))
2114 return NULL;
2115 fp = get_file(pathname, fob, "r");
2116 if (fp == NULL)
2117 return NULL;
2118 m = load_source_module(name, pathname, fp);
2119 if (fob == NULL)
2120 fclose(fp);
2121 return m;
2124 #ifdef macintosh
2125 static PyObject *
2126 imp_load_resource(PyObject *self, PyObject *args)
2128 char *name;
2129 char *pathname;
2130 PyObject *m;
2132 if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname))
2133 return NULL;
2134 m = PyMac_LoadResourceModule(name, pathname);
2135 return m;
2137 #endif /* macintosh */
2139 static PyObject *
2140 imp_load_module(PyObject *self, PyObject *args)
2142 char *name;
2143 PyObject *fob;
2144 char *pathname;
2145 char *suffix; /* Unused */
2146 char *mode;
2147 int type;
2148 FILE *fp;
2150 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
2151 &name, &fob, &pathname,
2152 &suffix, &mode, &type))
2153 return NULL;
2154 if (*mode && (*mode != 'r' || strchr(mode, '+') != NULL)) {
2155 PyErr_Format(PyExc_ValueError,
2156 "invalid file open mode %.200s", mode);
2157 return NULL;
2159 if (fob == Py_None)
2160 fp = NULL;
2161 else {
2162 if (!PyFile_Check(fob)) {
2163 PyErr_SetString(PyExc_ValueError,
2164 "load_module arg#2 should be a file or None");
2165 return NULL;
2167 fp = get_file(pathname, fob, mode);
2168 if (fp == NULL)
2169 return NULL;
2171 return load_module(name, fp, pathname, type);
2174 static PyObject *
2175 imp_load_package(PyObject *self, PyObject *args)
2177 char *name;
2178 char *pathname;
2179 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
2180 return NULL;
2181 return load_package(name, pathname);
2184 static PyObject *
2185 imp_new_module(PyObject *self, PyObject *args)
2187 char *name;
2188 if (!PyArg_ParseTuple(args, "s:new_module", &name))
2189 return NULL;
2190 return PyModule_New(name);
2193 /* Doc strings */
2195 static char doc_imp[] = "\
2196 This module provides the components needed to build your own\n\
2197 __import__ function. Undocumented functions are obsolete.\n\
2200 static char doc_find_module[] = "\
2201 find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2202 Search for a module. If path is omitted or None, search for a\n\
2203 built-in, frozen or special module and continue search in sys.path.\n\
2204 The module name cannot contain '.'; to search for a submodule of a\n\
2205 package, pass the submodule name and the package's __path__.\
2208 static char doc_load_module[] = "\
2209 load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2210 Load a module, given information returned by find_module().\n\
2211 The module name must include the full package name, if any.\
2214 static char doc_get_magic[] = "\
2215 get_magic() -> string\n\
2216 Return the magic number for .pyc or .pyo files.\
2219 static char doc_get_suffixes[] = "\
2220 get_suffixes() -> [(suffix, mode, type), ...]\n\
2221 Return a list of (suffix, mode, type) tuples describing the files\n\
2222 that find_module() looks for.\
2225 static char doc_new_module[] = "\
2226 new_module(name) -> module\n\
2227 Create a new module. Do not enter it in sys.modules.\n\
2228 The module name must include the full package name, if any.\
2231 static PyMethodDef imp_methods[] = {
2232 {"find_module", imp_find_module, 1, doc_find_module},
2233 {"get_magic", imp_get_magic, 1, doc_get_magic},
2234 {"get_suffixes", imp_get_suffixes, 1, doc_get_suffixes},
2235 {"load_module", imp_load_module, 1, doc_load_module},
2236 {"new_module", imp_new_module, 1, doc_new_module},
2237 /* The rest are obsolete */
2238 {"get_frozen_object", imp_get_frozen_object, 1},
2239 {"init_builtin", imp_init_builtin, 1},
2240 {"init_frozen", imp_init_frozen, 1},
2241 {"is_builtin", imp_is_builtin, 1},
2242 {"is_frozen", imp_is_frozen, 1},
2243 {"load_compiled", imp_load_compiled, 1},
2244 #ifdef HAVE_DYNAMIC_LOADING
2245 {"load_dynamic", imp_load_dynamic, 1},
2246 #endif
2247 {"load_package", imp_load_package, 1},
2248 #ifdef macintosh
2249 {"load_resource", imp_load_resource, 1},
2250 #endif
2251 {"load_source", imp_load_source, 1},
2252 {NULL, NULL} /* sentinel */
2255 static int
2256 setint(PyObject *d, char *name, int value)
2258 PyObject *v;
2259 int err;
2261 v = PyInt_FromLong((long)value);
2262 err = PyDict_SetItemString(d, name, v);
2263 Py_XDECREF(v);
2264 return err;
2267 void
2268 initimp(void)
2270 PyObject *m, *d;
2272 m = Py_InitModule4("imp", imp_methods, doc_imp,
2273 NULL, PYTHON_API_VERSION);
2274 d = PyModule_GetDict(m);
2276 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2277 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2278 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2279 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2280 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2281 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2282 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2283 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
2284 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
2286 failure:
2291 /* API for embedding applications that want to add their own entries
2292 to the table of built-in modules. This should normally be called
2293 *before* Py_Initialize(). When the table resize fails, -1 is
2294 returned and the existing table is unchanged.
2296 After a similar function by Just van Rossum. */
2299 PyImport_ExtendInittab(struct _inittab *newtab)
2301 static struct _inittab *our_copy = NULL;
2302 struct _inittab *p;
2303 int i, n;
2305 /* Count the number of entries in both tables */
2306 for (n = 0; newtab[n].name != NULL; n++)
2308 if (n == 0)
2309 return 0; /* Nothing to do */
2310 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2313 /* Allocate new memory for the combined table */
2314 p = our_copy;
2315 PyMem_RESIZE(p, struct _inittab, i+n+1);
2316 if (p == NULL)
2317 return -1;
2319 /* Copy the tables into the new memory */
2320 if (our_copy != PyImport_Inittab)
2321 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2322 PyImport_Inittab = our_copy = p;
2323 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2325 return 0;
2328 /* Shorthand to add a single entry given a name and a function */
2331 PyImport_AppendInittab(char *name, void (*initfunc)(void))
2333 struct _inittab newtab[2];
2335 memset(newtab, '\0', sizeof newtab);
2337 newtab[0].name = name;
2338 newtab[0].initfunc = initfunc;
2340 return PyImport_ExtendInittab(newtab);