This commit was manufactured by cvs2svn to create tag 'r22a4-fork'.
[python/dscho.git] / Python / import.c
blob52ad85e99e3a0bda3c091b02c224c02583f9c9ab
2 /* Module definition and import implementation */
4 #include "Python.h"
6 #include "node.h"
7 #include "token.h"
8 #include "errcode.h"
9 #include "marshal.h"
10 #include "compile.h"
11 #include "eval.h"
12 #include "osdefs.h"
13 #include "importdl.h"
14 #ifdef macintosh
15 #include "macglue.h"
16 #endif
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
22 #ifdef HAVE_FCNTL_H
23 #include <fcntl.h>
24 #endif
26 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
27 /* In getmtime.c */
29 /* Magic word to reject .pyc files generated by other Python versions */
30 /* Change for each incompatible change */
31 /* The value of CR and LF is incorporated so if you ever read or write
32 a .pyc file in text mode the magic number will be wrong; also, the
33 Apple MPW compiler swaps their values, botching string constants */
34 /* XXX Perhaps the magic number should be frozen and a version field
35 added to the .pyc file header? */
36 /* New way to come up with the magic number: (YEAR-1995), MONTH, DAY */
37 #define MAGIC (60717 | ((long)'\r'<<16) | ((long)'\n'<<24))
39 /* Magic word as global; note that _PyImport_Init() can change the
40 value of this global to accommodate for alterations of how the
41 compiler works which are enabled by command line switches. */
42 static long pyc_magic = MAGIC;
44 /* See _PyImport_FixupExtension() below */
45 static PyObject *extensions = NULL;
47 /* This table is defined in config.c: */
48 extern struct _inittab _PyImport_Inittab[];
50 struct _inittab *PyImport_Inittab = _PyImport_Inittab;
52 /* these tables define the module suffixes that Python recognizes */
53 struct filedescr * _PyImport_Filetab = NULL;
55 #ifdef RISCOS
56 static const struct filedescr _PyImport_StandardFiletab[] = {
57 {"/py", "r", PY_SOURCE},
58 {"/pyc", "rb", PY_COMPILED},
59 {0, 0}
61 #else
62 static const struct filedescr _PyImport_StandardFiletab[] = {
63 {".py", "r", PY_SOURCE},
64 #ifdef MS_WIN32
65 {".pyw", "r", PY_SOURCE},
66 #endif
67 {".pyc", "rb", PY_COMPILED},
68 {0, 0}
70 #endif
72 /* Initialize things */
74 void
75 _PyImport_Init(void)
77 const struct filedescr *scan;
78 struct filedescr *filetab;
79 int countD = 0;
80 int countS = 0;
82 /* prepare _PyImport_Filetab: copy entries from
83 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
85 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
86 ++countD;
87 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
88 ++countS;
89 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
90 memcpy(filetab, _PyImport_DynLoadFiletab,
91 countD * sizeof(struct filedescr));
92 memcpy(filetab + countD, _PyImport_StandardFiletab,
93 countS * sizeof(struct filedescr));
94 filetab[countD + countS].suffix = NULL;
96 _PyImport_Filetab = filetab;
98 if (Py_OptimizeFlag) {
99 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
100 for (; filetab->suffix != NULL; filetab++) {
101 #ifndef RISCOS
102 if (strcmp(filetab->suffix, ".pyc") == 0)
103 filetab->suffix = ".pyo";
104 #else
105 if (strcmp(filetab->suffix, "/pyc") == 0)
106 filetab->suffix = "/pyo";
107 #endif
111 if (Py_UnicodeFlag) {
112 /* Fix the pyc_magic so that byte compiled code created
113 using the all-Unicode method doesn't interfere with
114 code created in normal operation mode. */
115 pyc_magic = MAGIC + 1;
119 void
120 _PyImport_Fini(void)
122 Py_XDECREF(extensions);
123 extensions = NULL;
124 PyMem_DEL(_PyImport_Filetab);
125 _PyImport_Filetab = NULL;
129 /* Locking primitives to prevent parallel imports of the same module
130 in different threads to return with a partially loaded module.
131 These calls are serialized by the global interpreter lock. */
133 #ifdef WITH_THREAD
135 #include "pythread.h"
137 static PyThread_type_lock import_lock = 0;
138 static long import_lock_thread = -1;
139 static int import_lock_level = 0;
141 static void
142 lock_import(void)
144 long me = PyThread_get_thread_ident();
145 if (me == -1)
146 return; /* Too bad */
147 if (import_lock == NULL)
148 import_lock = PyThread_allocate_lock();
149 if (import_lock_thread == me) {
150 import_lock_level++;
151 return;
153 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0)) {
154 PyThreadState *tstate = PyEval_SaveThread();
155 PyThread_acquire_lock(import_lock, 1);
156 PyEval_RestoreThread(tstate);
158 import_lock_thread = me;
159 import_lock_level = 1;
162 static void
163 unlock_import(void)
165 long me = PyThread_get_thread_ident();
166 if (me == -1)
167 return; /* Too bad */
168 if (import_lock_thread != me)
169 Py_FatalError("unlock_import: not holding the import lock");
170 import_lock_level--;
171 if (import_lock_level == 0) {
172 import_lock_thread = -1;
173 PyThread_release_lock(import_lock);
177 #else
179 #define lock_import()
180 #define unlock_import()
182 #endif
184 static PyObject *
185 imp_lock_held(PyObject *self, PyObject *args)
187 if (!PyArg_ParseTuple(args, ":lock_held"))
188 return NULL;
189 #ifdef WITH_THREAD
190 return PyInt_FromLong(import_lock_thread != -1);
191 #else
192 return PyInt_FromLong(0);
193 #endif
196 /* Helper for sys */
198 PyObject *
199 PyImport_GetModuleDict(void)
201 PyInterpreterState *interp = PyThreadState_Get()->interp;
202 if (interp->modules == NULL)
203 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
204 return interp->modules;
208 /* List of names to clear in sys */
209 static char* sys_deletes[] = {
210 "path", "argv", "ps1", "ps2", "exitfunc",
211 "exc_type", "exc_value", "exc_traceback",
212 "last_type", "last_value", "last_traceback",
213 NULL
216 static char* sys_files[] = {
217 "stdin", "__stdin__",
218 "stdout", "__stdout__",
219 "stderr", "__stderr__",
220 NULL
224 /* Un-initialize things, as good as we can */
226 void
227 PyImport_Cleanup(void)
229 int pos, ndone;
230 char *name;
231 PyObject *key, *value, *dict;
232 PyInterpreterState *interp = PyThreadState_Get()->interp;
233 PyObject *modules = interp->modules;
235 if (modules == NULL)
236 return; /* Already done */
238 /* Delete some special variables first. These are common
239 places where user values hide and people complain when their
240 destructors fail. Since the modules containing them are
241 deleted *last* of all, they would come too late in the normal
242 destruction order. Sigh. */
244 value = PyDict_GetItemString(modules, "__builtin__");
245 if (value != NULL && PyModule_Check(value)) {
246 dict = PyModule_GetDict(value);
247 if (Py_VerboseFlag)
248 PySys_WriteStderr("# clear __builtin__._\n");
249 PyDict_SetItemString(dict, "_", Py_None);
251 value = PyDict_GetItemString(modules, "sys");
252 if (value != NULL && PyModule_Check(value)) {
253 char **p;
254 PyObject *v;
255 dict = PyModule_GetDict(value);
256 for (p = sys_deletes; *p != NULL; p++) {
257 if (Py_VerboseFlag)
258 PySys_WriteStderr("# clear sys.%s\n", *p);
259 PyDict_SetItemString(dict, *p, Py_None);
261 for (p = sys_files; *p != NULL; p+=2) {
262 if (Py_VerboseFlag)
263 PySys_WriteStderr("# restore sys.%s\n", *p);
264 v = PyDict_GetItemString(dict, *(p+1));
265 if (v == NULL)
266 v = Py_None;
267 PyDict_SetItemString(dict, *p, v);
271 /* First, delete __main__ */
272 value = PyDict_GetItemString(modules, "__main__");
273 if (value != NULL && PyModule_Check(value)) {
274 if (Py_VerboseFlag)
275 PySys_WriteStderr("# cleanup __main__\n");
276 _PyModule_Clear(value);
277 PyDict_SetItemString(modules, "__main__", Py_None);
280 /* The special treatment of __builtin__ here is because even
281 when it's not referenced as a module, its dictionary is
282 referenced by almost every module's __builtins__. Since
283 deleting a module clears its dictionary (even if there are
284 references left to it), we need to delete the __builtin__
285 module last. Likewise, we don't delete sys until the very
286 end because it is implicitly referenced (e.g. by print).
288 Also note that we 'delete' modules by replacing their entry
289 in the modules dict with None, rather than really deleting
290 them; this avoids a rehash of the modules dictionary and
291 also marks them as "non existent" so they won't be
292 re-imported. */
294 /* Next, repeatedly delete modules with a reference count of
295 one (skipping __builtin__ and sys) and delete them */
296 do {
297 ndone = 0;
298 pos = 0;
299 while (PyDict_Next(modules, &pos, &key, &value)) {
300 if (value->ob_refcnt != 1)
301 continue;
302 if (PyString_Check(key) && PyModule_Check(value)) {
303 name = PyString_AS_STRING(key);
304 if (strcmp(name, "__builtin__") == 0)
305 continue;
306 if (strcmp(name, "sys") == 0)
307 continue;
308 if (Py_VerboseFlag)
309 PySys_WriteStderr(
310 "# cleanup[1] %s\n", name);
311 _PyModule_Clear(value);
312 PyDict_SetItem(modules, key, Py_None);
313 ndone++;
316 } while (ndone > 0);
318 /* Next, delete all modules (still skipping __builtin__ and sys) */
319 pos = 0;
320 while (PyDict_Next(modules, &pos, &key, &value)) {
321 if (PyString_Check(key) && PyModule_Check(value)) {
322 name = PyString_AS_STRING(key);
323 if (strcmp(name, "__builtin__") == 0)
324 continue;
325 if (strcmp(name, "sys") == 0)
326 continue;
327 if (Py_VerboseFlag)
328 PySys_WriteStderr("# cleanup[2] %s\n", name);
329 _PyModule_Clear(value);
330 PyDict_SetItem(modules, key, Py_None);
334 /* Next, delete sys and __builtin__ (in that order) */
335 value = PyDict_GetItemString(modules, "sys");
336 if (value != NULL && PyModule_Check(value)) {
337 if (Py_VerboseFlag)
338 PySys_WriteStderr("# cleanup sys\n");
339 _PyModule_Clear(value);
340 PyDict_SetItemString(modules, "sys", Py_None);
342 value = PyDict_GetItemString(modules, "__builtin__");
343 if (value != NULL && PyModule_Check(value)) {
344 if (Py_VerboseFlag)
345 PySys_WriteStderr("# cleanup __builtin__\n");
346 _PyModule_Clear(value);
347 PyDict_SetItemString(modules, "__builtin__", Py_None);
350 /* Finally, clear and delete the modules directory */
351 PyDict_Clear(modules);
352 interp->modules = NULL;
353 Py_DECREF(modules);
357 /* Helper for pythonrun.c -- return magic number */
359 long
360 PyImport_GetMagicNumber(void)
362 return pyc_magic;
366 /* Magic for extension modules (built-in as well as dynamically
367 loaded). To prevent initializing an extension module more than
368 once, we keep a static dictionary 'extensions' keyed by module name
369 (for built-in modules) or by filename (for dynamically loaded
370 modules), containing these modules. A copy of the module's
371 dictionary is stored by calling _PyImport_FixupExtension()
372 immediately after the module initialization function succeeds. A
373 copy can be retrieved from there by calling
374 _PyImport_FindExtension(). */
376 PyObject *
377 _PyImport_FixupExtension(char *name, char *filename)
379 PyObject *modules, *mod, *dict, *copy;
380 if (extensions == NULL) {
381 extensions = PyDict_New();
382 if (extensions == NULL)
383 return NULL;
385 modules = PyImport_GetModuleDict();
386 mod = PyDict_GetItemString(modules, name);
387 if (mod == NULL || !PyModule_Check(mod)) {
388 PyErr_Format(PyExc_SystemError,
389 "_PyImport_FixupExtension: module %.200s not loaded", name);
390 return NULL;
392 dict = PyModule_GetDict(mod);
393 if (dict == NULL)
394 return NULL;
395 copy = PyObject_CallMethod(dict, "copy", "");
396 if (copy == NULL)
397 return NULL;
398 PyDict_SetItemString(extensions, filename, copy);
399 Py_DECREF(copy);
400 return copy;
403 PyObject *
404 _PyImport_FindExtension(char *name, char *filename)
406 PyObject *dict, *mod, *mdict, *result;
407 if (extensions == NULL)
408 return NULL;
409 dict = PyDict_GetItemString(extensions, filename);
410 if (dict == NULL)
411 return NULL;
412 mod = PyImport_AddModule(name);
413 if (mod == NULL)
414 return NULL;
415 mdict = PyModule_GetDict(mod);
416 if (mdict == NULL)
417 return NULL;
418 result = PyObject_CallMethod(mdict, "update", "O", dict);
419 if (result == NULL)
420 return NULL;
421 Py_DECREF(result);
422 if (Py_VerboseFlag)
423 PySys_WriteStderr("import %s # previously loaded (%s)\n",
424 name, filename);
425 return mod;
429 /* Get the module object corresponding to a module name.
430 First check the modules dictionary if there's one there,
431 if not, create a new one and insert in in the modules dictionary.
432 Because the former action is most common, THIS DOES NOT RETURN A
433 'NEW' REFERENCE! */
435 PyObject *
436 PyImport_AddModule(char *name)
438 PyObject *modules = PyImport_GetModuleDict();
439 PyObject *m;
441 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
442 PyModule_Check(m))
443 return m;
444 m = PyModule_New(name);
445 if (m == NULL)
446 return NULL;
447 if (PyDict_SetItemString(modules, name, m) != 0) {
448 Py_DECREF(m);
449 return NULL;
451 Py_DECREF(m); /* Yes, it still exists, in modules! */
453 return m;
457 /* Execute a code object in a module and return the module object
458 WITH INCREMENTED REFERENCE COUNT */
460 PyObject *
461 PyImport_ExecCodeModule(char *name, PyObject *co)
463 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
466 PyObject *
467 PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
469 PyObject *modules = PyImport_GetModuleDict();
470 PyObject *m, *d, *v;
472 m = PyImport_AddModule(name);
473 if (m == NULL)
474 return NULL;
475 d = PyModule_GetDict(m);
476 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
477 if (PyDict_SetItemString(d, "__builtins__",
478 PyEval_GetBuiltins()) != 0)
479 return NULL;
481 /* Remember the filename as the __file__ attribute */
482 v = NULL;
483 if (pathname != NULL) {
484 v = PyString_FromString(pathname);
485 if (v == NULL)
486 PyErr_Clear();
488 if (v == NULL) {
489 v = ((PyCodeObject *)co)->co_filename;
490 Py_INCREF(v);
492 if (PyDict_SetItemString(d, "__file__", v) != 0)
493 PyErr_Clear(); /* Not important enough to report */
494 Py_DECREF(v);
496 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
497 if (v == NULL)
498 return NULL;
499 Py_DECREF(v);
501 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
502 PyErr_Format(PyExc_ImportError,
503 "Loaded module %.200s not found in sys.modules",
504 name);
505 return NULL;
508 Py_INCREF(m);
510 return m;
514 /* Given a pathname for a Python source file, fill a buffer with the
515 pathname for the corresponding compiled file. Return the pathname
516 for the compiled file, or NULL if there's no space in the buffer.
517 Doesn't set an exception. */
519 static char *
520 make_compiled_pathname(char *pathname, char *buf, size_t buflen)
522 size_t len = strlen(pathname);
523 if (len+2 > buflen)
524 return NULL;
526 #ifdef MS_WIN32
527 /* Treat .pyw as if it were .py. The case of ".pyw" must match
528 that used in _PyImport_StandardFiletab. */
529 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
530 --len; /* pretend 'w' isn't there */
531 #endif
532 memcpy(buf, pathname, len);
533 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
534 buf[len+1] = '\0';
536 return buf;
540 /* Given a pathname for a Python source file, its time of last
541 modification, and a pathname for a compiled file, check whether the
542 compiled file represents the same version of the source. If so,
543 return a FILE pointer for the compiled file, positioned just after
544 the header; if not, return NULL.
545 Doesn't set an exception. */
547 static FILE *
548 check_compiled_module(char *pathname, long mtime, char *cpathname)
550 FILE *fp;
551 long magic;
552 long pyc_mtime;
554 fp = fopen(cpathname, "rb");
555 if (fp == NULL)
556 return NULL;
557 magic = PyMarshal_ReadLongFromFile(fp);
558 if (magic != pyc_magic) {
559 if (Py_VerboseFlag)
560 PySys_WriteStderr("# %s has bad magic\n", cpathname);
561 fclose(fp);
562 return NULL;
564 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
565 if (pyc_mtime != mtime) {
566 if (Py_VerboseFlag)
567 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
568 fclose(fp);
569 return NULL;
571 if (Py_VerboseFlag)
572 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
573 return fp;
577 /* Read a code object from a file and check it for validity */
579 static PyCodeObject *
580 read_compiled_module(char *cpathname, FILE *fp)
582 PyObject *co;
584 co = PyMarshal_ReadLastObjectFromFile(fp);
585 /* Ugly: rd_object() may return NULL with or without error */
586 if (co == NULL || !PyCode_Check(co)) {
587 if (!PyErr_Occurred())
588 PyErr_Format(PyExc_ImportError,
589 "Non-code object in %.200s", cpathname);
590 Py_XDECREF(co);
591 return NULL;
593 return (PyCodeObject *)co;
597 /* Load a module from a compiled file, execute it, and return its
598 module object WITH INCREMENTED REFERENCE COUNT */
600 static PyObject *
601 load_compiled_module(char *name, char *cpathname, FILE *fp)
603 long magic;
604 PyCodeObject *co;
605 PyObject *m;
607 magic = PyMarshal_ReadLongFromFile(fp);
608 if (magic != pyc_magic) {
609 PyErr_Format(PyExc_ImportError,
610 "Bad magic number in %.200s", cpathname);
611 return NULL;
613 (void) PyMarshal_ReadLongFromFile(fp);
614 co = read_compiled_module(cpathname, fp);
615 if (co == NULL)
616 return NULL;
617 if (Py_VerboseFlag)
618 PySys_WriteStderr("import %s # precompiled from %s\n",
619 name, cpathname);
620 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
621 Py_DECREF(co);
623 return m;
626 /* Parse a source file and return the corresponding code object */
628 static PyCodeObject *
629 parse_source_module(char *pathname, FILE *fp)
631 PyCodeObject *co;
632 node *n;
634 n = PyParser_SimpleParseFile(fp, pathname, Py_file_input);
635 if (n == NULL)
636 return NULL;
637 co = PyNode_Compile(n, pathname);
638 PyNode_Free(n);
640 return co;
644 /* Helper to open a bytecode file for writing in exclusive mode */
646 static FILE *
647 open_exclusive(char *filename)
649 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
650 /* Use O_EXCL to avoid a race condition when another process tries to
651 write the same file. When that happens, our open() call fails,
652 which is just fine (since it's only a cache).
653 XXX If the file exists and is writable but the directory is not
654 writable, the file will never be written. Oh well.
656 int fd;
657 (void) unlink(filename);
658 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
659 #ifdef O_BINARY
660 |O_BINARY /* necessary for Windows */
661 #endif
663 , 0666);
664 if (fd < 0)
665 return NULL;
666 return fdopen(fd, "wb");
667 #else
668 /* Best we can do -- on Windows this can't happen anyway */
669 return fopen(filename, "wb");
670 #endif
674 /* Write a compiled module to a file, placing the time of last
675 modification of its source into the header.
676 Errors are ignored, if a write error occurs an attempt is made to
677 remove the file. */
679 static void
680 write_compiled_module(PyCodeObject *co, char *cpathname, long mtime)
682 FILE *fp;
684 fp = open_exclusive(cpathname);
685 if (fp == NULL) {
686 if (Py_VerboseFlag)
687 PySys_WriteStderr(
688 "# can't create %s\n", cpathname);
689 return;
691 PyMarshal_WriteLongToFile(pyc_magic, fp);
692 /* First write a 0 for mtime */
693 PyMarshal_WriteLongToFile(0L, fp);
694 PyMarshal_WriteObjectToFile((PyObject *)co, fp);
695 if (ferror(fp)) {
696 if (Py_VerboseFlag)
697 PySys_WriteStderr("# can't write %s\n", cpathname);
698 /* Don't keep partial file */
699 fclose(fp);
700 (void) unlink(cpathname);
701 return;
703 /* Now write the true mtime */
704 fseek(fp, 4L, 0);
705 PyMarshal_WriteLongToFile(mtime, fp);
706 fflush(fp);
707 fclose(fp);
708 if (Py_VerboseFlag)
709 PySys_WriteStderr("# wrote %s\n", cpathname);
710 #ifdef macintosh
711 PyMac_setfiletype(cpathname, 'Pyth', 'PYC ');
712 #endif
716 /* Load a source module from a given file and return its module
717 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
718 byte-compiled file, use that instead. */
720 static PyObject *
721 load_source_module(char *name, char *pathname, FILE *fp)
723 time_t mtime;
724 FILE *fpc;
725 char buf[MAXPATHLEN+1];
726 char *cpathname;
727 PyCodeObject *co;
728 PyObject *m;
730 mtime = PyOS_GetLastModificationTime(pathname, fp);
731 if (mtime == (time_t)(-1))
732 return NULL;
733 #if SIZEOF_TIME_T > 4
734 /* Python's .pyc timestamp handling presumes that the timestamp fits
735 in 4 bytes. This will be fine until sometime in the year 2038,
736 when a 4-byte signed time_t will overflow.
738 if (mtime >> 32) {
739 PyErr_SetString(PyExc_OverflowError,
740 "modification time overflows a 4 byte field");
741 return NULL;
743 #endif
744 cpathname = make_compiled_pathname(pathname, buf,
745 (size_t)MAXPATHLEN + 1);
746 if (cpathname != NULL &&
747 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
748 co = read_compiled_module(cpathname, fpc);
749 fclose(fpc);
750 if (co == NULL)
751 return NULL;
752 if (Py_VerboseFlag)
753 PySys_WriteStderr("import %s # precompiled from %s\n",
754 name, cpathname);
755 pathname = cpathname;
757 else {
758 co = parse_source_module(pathname, fp);
759 if (co == NULL)
760 return NULL;
761 if (Py_VerboseFlag)
762 PySys_WriteStderr("import %s # from %s\n",
763 name, pathname);
764 write_compiled_module(co, cpathname, mtime);
766 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
767 Py_DECREF(co);
769 return m;
773 /* Forward */
774 static PyObject *load_module(char *, FILE *, char *, int);
775 static struct filedescr *find_module(char *, PyObject *,
776 char *, size_t, FILE **);
777 static struct _frozen *find_frozen(char *name);
779 /* Load a package and return its module object WITH INCREMENTED
780 REFERENCE COUNT */
782 static PyObject *
783 load_package(char *name, char *pathname)
785 PyObject *m, *d, *file, *path;
786 int err;
787 char buf[MAXPATHLEN+1];
788 FILE *fp = NULL;
789 struct filedescr *fdp;
791 m = PyImport_AddModule(name);
792 if (m == NULL)
793 return NULL;
794 if (Py_VerboseFlag)
795 PySys_WriteStderr("import %s # directory %s\n",
796 name, pathname);
797 d = PyModule_GetDict(m);
798 file = PyString_FromString(pathname);
799 if (file == NULL)
800 return NULL;
801 path = Py_BuildValue("[O]", file);
802 if (path == NULL) {
803 Py_DECREF(file);
804 return NULL;
806 err = PyDict_SetItemString(d, "__file__", file);
807 if (err == 0)
808 err = PyDict_SetItemString(d, "__path__", path);
809 if (err != 0) {
810 m = NULL;
811 goto cleanup;
813 buf[0] = '\0';
814 fdp = find_module("__init__", path, buf, sizeof(buf), &fp);
815 if (fdp == NULL) {
816 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
817 PyErr_Clear();
819 else
820 m = NULL;
821 goto cleanup;
823 m = load_module(name, fp, buf, fdp->type);
824 if (fp != NULL)
825 fclose(fp);
826 cleanup:
827 Py_XDECREF(path);
828 Py_XDECREF(file);
829 return m;
833 /* Helper to test for built-in module */
835 static int
836 is_builtin(char *name)
838 int i;
839 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
840 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
841 if (PyImport_Inittab[i].initfunc == NULL)
842 return -1;
843 else
844 return 1;
847 return 0;
851 /* Search the path (default sys.path) for a module. Return the
852 corresponding filedescr struct, and (via return arguments) the
853 pathname and an open file. Return NULL if the module is not found. */
855 #ifdef MS_COREDLL
856 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
857 char *, int);
858 #endif
860 static int case_ok(char *, int, int, char *);
861 static int find_init_module(char *); /* Forward */
863 static struct filedescr *
864 find_module(char *realname, PyObject *path, char *buf, size_t buflen,
865 FILE **p_fp)
867 int i, npath;
868 size_t len, namelen;
869 struct _frozen *f;
870 struct filedescr *fdp = NULL;
871 FILE *fp = NULL;
872 #ifndef RISCOS
873 struct stat statbuf;
874 #endif
875 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
876 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
877 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
878 char name[MAXPATHLEN+1];
880 if (strlen(realname) > MAXPATHLEN) {
881 PyErr_SetString(PyExc_OverflowError, "module name is too long");
882 return NULL;
884 strcpy(name, realname);
886 if (path != NULL && PyString_Check(path)) {
887 /* Submodule of "frozen" package:
888 Set name to the fullname, path to NULL
889 and continue as "usual" */
890 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
891 PyErr_SetString(PyExc_ImportError,
892 "full frozen module name too long");
893 return NULL;
895 strcpy(buf, PyString_AsString(path));
896 strcat(buf, ".");
897 strcat(buf, name);
898 strcpy(name, buf);
899 path = NULL;
901 if (path == NULL) {
902 if (is_builtin(name)) {
903 strcpy(buf, name);
904 return &fd_builtin;
906 if ((f = find_frozen(name)) != NULL) {
907 strcpy(buf, name);
908 return &fd_frozen;
911 #ifdef MS_COREDLL
912 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
913 if (fp != NULL) {
914 *p_fp = fp;
915 return fdp;
917 #endif
918 path = PySys_GetObject("path");
920 if (path == NULL || !PyList_Check(path)) {
921 PyErr_SetString(PyExc_ImportError,
922 "sys.path must be a list of directory names");
923 return NULL;
925 npath = PyList_Size(path);
926 namelen = strlen(name);
927 for (i = 0; i < npath; i++) {
928 PyObject *v = PyList_GetItem(path, i);
929 if (!PyString_Check(v))
930 continue;
931 len = PyString_Size(v);
932 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen)
933 continue; /* Too long */
934 strcpy(buf, PyString_AsString(v));
935 if (strlen(buf) != len)
936 continue; /* v contains '\0' */
937 #ifdef macintosh
938 #ifdef INTERN_STRINGS
940 ** Speedup: each sys.path item is interned, and
941 ** FindResourceModule remembers which items refer to
942 ** folders (so we don't have to bother trying to look
943 ** into them for resources).
945 PyString_InternInPlace(&PyList_GET_ITEM(path, i));
946 v = PyList_GET_ITEM(path, i);
947 #endif
948 if (PyMac_FindResourceModule((PyStringObject *)v, name, buf)) {
949 static struct filedescr resfiledescr =
950 {"", "", PY_RESOURCE};
952 return &resfiledescr;
954 if (PyMac_FindCodeResourceModule((PyStringObject *)v, name, buf)) {
955 static struct filedescr resfiledescr =
956 {"", "", PY_CODERESOURCE};
958 return &resfiledescr;
960 #endif
961 if (len > 0 && buf[len-1] != SEP
962 #ifdef ALTSEP
963 && buf[len-1] != ALTSEP
964 #endif
966 buf[len++] = SEP;
967 strcpy(buf+len, name);
968 len += namelen;
970 /* Check for package import (buf holds a directory name,
971 and there's an __init__ module in that directory */
972 #ifdef HAVE_STAT
973 if (stat(buf, &statbuf) == 0 && /* it exists */
974 S_ISDIR(statbuf.st_mode) && /* it's a directory */
975 find_init_module(buf) && /* it has __init__.py */
976 case_ok(buf, len, namelen, name)) /* and case matches */
977 return &fd_package;
978 #else
979 /* XXX How are you going to test for directories? */
980 #ifdef RISCOS
982 static struct filedescr fd = {"", "", PKG_DIRECTORY};
983 if (isdir(buf)) {
984 if (find_init_module(buf))
985 return &fd;
988 #endif
989 #endif
990 #ifdef macintosh
991 fdp = PyMac_FindModuleExtension(buf, &len, name);
992 if (fdp) {
993 #else
994 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
995 strcpy(buf+len, fdp->suffix);
996 if (Py_VerboseFlag > 1)
997 PySys_WriteStderr("# trying %s\n", buf);
998 #endif /* !macintosh */
999 fp = fopen(buf, fdp->mode);
1000 if (fp != NULL) {
1001 if (case_ok(buf, len, namelen, name))
1002 break;
1003 else { /* continue search */
1004 fclose(fp);
1005 fp = NULL;
1009 if (fp != NULL)
1010 break;
1012 if (fp == NULL) {
1013 PyErr_Format(PyExc_ImportError,
1014 "No module named %.200s", name);
1015 return NULL;
1017 *p_fp = fp;
1018 return fdp;
1021 /* case_ok(char* buf, int len, int namelen, char* name)
1022 * The arguments here are tricky, best shown by example:
1023 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1024 * ^ ^ ^ ^
1025 * |--------------------- buf ---------------------|
1026 * |------------------- len ------------------|
1027 * |------ name -------|
1028 * |----- namelen -----|
1029 * buf is the full path, but len only counts up to (& exclusive of) the
1030 * extension. name is the module name, also exclusive of extension.
1032 * We've already done a successful stat() or fopen() on buf, so know that
1033 * there's some match, possibly case-insensitive.
1035 * case_ok() is to return 1 if there's a case-sensitive match for
1036 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1037 * exists.
1039 * case_ok() is used to implement case-sensitive import semantics even
1040 * on platforms with case-insensitive filesystems. It's trivial to implement
1041 * for case-sensitive filesystems. It's pretty much a cross-platform
1042 * nightmare for systems with case-insensitive filesystems.
1045 /* First we may need a pile of platform-specific header files; the sequence
1046 * of #if's here should match the sequence in the body of case_ok().
1048 #if defined(MS_WIN32) || defined(__CYGWIN__)
1049 #include <windows.h>
1050 #ifdef __CYGWIN__
1051 #include <sys/cygwin.h>
1052 #endif
1054 #elif defined(DJGPP)
1055 #include <dir.h>
1057 #elif defined(macintosh)
1058 #include <TextUtils.h>
1059 #ifdef USE_GUSI1
1060 #include "TFileSpec.h" /* for Path2FSSpec() */
1061 #endif
1063 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1064 #include <sys/types.h>
1065 #include <dirent.h>
1067 #endif
1069 static int
1070 case_ok(char *buf, int len, int namelen, char *name)
1072 /* Pick a platform-specific implementation; the sequence of #if's here should
1073 * match the sequence just above.
1076 /* MS_WIN32 || __CYGWIN__ */
1077 #if defined(MS_WIN32) || defined(__CYGWIN__)
1078 WIN32_FIND_DATA data;
1079 HANDLE h;
1080 #ifdef __CYGWIN__
1081 char tempbuf[MAX_PATH];
1082 #endif
1084 if (Py_GETENV("PYTHONCASEOK") != NULL)
1085 return 1;
1087 #ifdef __CYGWIN__
1088 cygwin32_conv_to_win32_path(buf, tempbuf);
1089 h = FindFirstFile(tempbuf, &data);
1090 #else
1091 h = FindFirstFile(buf, &data);
1092 #endif
1093 if (h == INVALID_HANDLE_VALUE) {
1094 PyErr_Format(PyExc_NameError,
1095 "Can't find file for module %.100s\n(filename %.300s)",
1096 name, buf);
1097 return 0;
1099 FindClose(h);
1100 return strncmp(data.cFileName, name, namelen) == 0;
1102 /* DJGPP */
1103 #elif defined(DJGPP)
1104 struct ffblk ffblk;
1105 int done;
1107 if (Py_GETENV("PYTHONCASEOK") != NULL)
1108 return 1;
1110 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1111 if (done) {
1112 PyErr_Format(PyExc_NameError,
1113 "Can't find file for module %.100s\n(filename %.300s)",
1114 name, buf);
1115 return 0;
1117 return strncmp(ffblk.ff_name, name, namelen) == 0;
1119 /* macintosh */
1120 #elif defined(macintosh)
1121 FSSpec fss;
1122 OSErr err;
1124 if (Py_GETENV("PYTHONCASEOK") != NULL)
1125 return 1;
1127 #ifndef USE_GUSI1
1128 err = FSMakeFSSpec(0, 0, Pstring(buf), &fss);
1129 #else
1130 /* GUSI's Path2FSSpec() resolves all possible aliases nicely on
1131 the way, which is fine for all directories, but here we need
1132 the original name of the alias file (say, Dlg.ppc.slb, not
1133 toolboxmodules.ppc.slb). */
1134 char *colon;
1135 err = Path2FSSpec(buf, &fss);
1136 if (err == noErr) {
1137 colon = strrchr(buf, ':'); /* find filename */
1138 if (colon != NULL)
1139 err = FSMakeFSSpec(fss.vRefNum, fss.parID,
1140 Pstring(colon+1), &fss);
1141 else
1142 err = FSMakeFSSpec(fss.vRefNum, fss.parID,
1143 fss.name, &fss);
1145 #endif
1146 if (err) {
1147 PyErr_Format(PyExc_NameError,
1148 "Can't find file for module %.100s\n(filename %.300s)",
1149 name, buf);
1150 return 0;
1152 return fss.name[0] >= namelen &&
1153 strncmp(name, (char *)fss.name+1, namelen) == 0;
1155 /* new-fangled macintosh (macosx) */
1156 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1157 DIR *dirp;
1158 struct dirent *dp;
1159 char dirname[MAXPATHLEN + 1];
1160 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
1162 if (Py_GETENV("PYTHONCASEOK") != NULL)
1163 return 1;
1165 /* Copy the dir component into dirname; substitute "." if empty */
1166 if (dirlen <= 0) {
1167 dirname[0] = '.';
1168 dirname[1] = '\0';
1170 else {
1171 assert(dirlen <= MAXPATHLEN);
1172 memcpy(dirname, buf, dirlen);
1173 dirname[dirlen] = '\0';
1175 /* Open the directory and search the entries for an exact match. */
1176 dirp = opendir(dirname);
1177 if (dirp) {
1178 char *nameWithExt = buf + len - namelen;
1179 while ((dp = readdir(dirp)) != NULL) {
1180 const int thislen =
1181 #ifdef _DIRENT_HAVE_D_NAMELEN
1182 dp->d_namlen;
1183 #else
1184 strlen(dp->d_name);
1185 #endif
1186 if (thislen >= namelen &&
1187 strcmp(dp->d_name, nameWithExt) == 0) {
1188 (void)closedir(dirp);
1189 return 1; /* Found */
1192 (void)closedir(dirp);
1194 return 0 ; /* Not found */
1196 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1197 #else
1198 return 1;
1200 #endif
1204 #ifdef HAVE_STAT
1205 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1206 static int
1207 find_init_module(char *buf)
1209 const size_t save_len = strlen(buf);
1210 size_t i = save_len;
1211 char *pname; /* pointer to start of __init__ */
1212 struct stat statbuf;
1214 /* For calling case_ok(buf, len, namelen, name):
1215 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1216 * ^ ^ ^ ^
1217 * |--------------------- buf ---------------------|
1218 * |------------------- len ------------------|
1219 * |------ name -------|
1220 * |----- namelen -----|
1222 if (save_len + 13 >= MAXPATHLEN)
1223 return 0;
1224 buf[i++] = SEP;
1225 pname = buf + i;
1226 strcpy(pname, "__init__.py");
1227 if (stat(buf, &statbuf) == 0) {
1228 if (case_ok(buf,
1229 save_len + 9, /* len("/__init__") */
1230 8, /* len("__init__") */
1231 pname)) {
1232 buf[save_len] = '\0';
1233 return 1;
1236 i += strlen(pname);
1237 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1238 if (stat(buf, &statbuf) == 0) {
1239 if (case_ok(buf,
1240 save_len + 9, /* len("/__init__") */
1241 8, /* len("__init__") */
1242 pname)) {
1243 buf[save_len] = '\0';
1244 return 1;
1247 buf[save_len] = '\0';
1248 return 0;
1251 #else
1253 #ifdef RISCOS
1254 static int
1255 find_init_module(buf)
1256 char *buf;
1258 int save_len = strlen(buf);
1259 int i = save_len;
1261 if (save_len + 13 >= MAXPATHLEN)
1262 return 0;
1263 buf[i++] = SEP;
1264 strcpy(buf+i, "__init__/py");
1265 if (isfile(buf)) {
1266 buf[save_len] = '\0';
1267 return 1;
1270 if (Py_OptimizeFlag)
1271 strcpy(buf+i, "o");
1272 else
1273 strcpy(buf+i, "c");
1274 if (isfile(buf)) {
1275 buf[save_len] = '\0';
1276 return 1;
1278 buf[save_len] = '\0';
1279 return 0;
1281 #endif /*RISCOS*/
1283 #endif /* HAVE_STAT */
1286 static int init_builtin(char *); /* Forward */
1288 /* Load an external module using the default search path and return
1289 its module object WITH INCREMENTED REFERENCE COUNT */
1291 static PyObject *
1292 load_module(char *name, FILE *fp, char *buf, int type)
1294 PyObject *modules;
1295 PyObject *m;
1296 int err;
1298 /* First check that there's an open file (if we need one) */
1299 switch (type) {
1300 case PY_SOURCE:
1301 case PY_COMPILED:
1302 if (fp == NULL) {
1303 PyErr_Format(PyExc_ValueError,
1304 "file object required for import (type code %d)",
1305 type);
1306 return NULL;
1310 switch (type) {
1312 case PY_SOURCE:
1313 m = load_source_module(name, buf, fp);
1314 break;
1316 case PY_COMPILED:
1317 m = load_compiled_module(name, buf, fp);
1318 break;
1320 #ifdef HAVE_DYNAMIC_LOADING
1321 case C_EXTENSION:
1322 m = _PyImport_LoadDynamicModule(name, buf, fp);
1323 break;
1324 #endif
1326 #ifdef macintosh
1327 case PY_RESOURCE:
1328 m = PyMac_LoadResourceModule(name, buf);
1329 break;
1330 case PY_CODERESOURCE:
1331 m = PyMac_LoadCodeResourceModule(name, buf);
1332 break;
1333 #endif
1335 case PKG_DIRECTORY:
1336 m = load_package(name, buf);
1337 break;
1339 case C_BUILTIN:
1340 case PY_FROZEN:
1341 if (buf != NULL && buf[0] != '\0')
1342 name = buf;
1343 if (type == C_BUILTIN)
1344 err = init_builtin(name);
1345 else
1346 err = PyImport_ImportFrozenModule(name);
1347 if (err < 0)
1348 return NULL;
1349 if (err == 0) {
1350 PyErr_Format(PyExc_ImportError,
1351 "Purported %s module %.200s not found",
1352 type == C_BUILTIN ?
1353 "builtin" : "frozen",
1354 name);
1355 return NULL;
1357 modules = PyImport_GetModuleDict();
1358 m = PyDict_GetItemString(modules, name);
1359 if (m == NULL) {
1360 PyErr_Format(
1361 PyExc_ImportError,
1362 "%s module %.200s not properly initialized",
1363 type == C_BUILTIN ?
1364 "builtin" : "frozen",
1365 name);
1366 return NULL;
1368 Py_INCREF(m);
1369 break;
1371 default:
1372 PyErr_Format(PyExc_ImportError,
1373 "Don't know how to import %.200s (type code %d)",
1374 name, type);
1375 m = NULL;
1379 return m;
1383 /* Initialize a built-in module.
1384 Return 1 for succes, 0 if the module is not found, and -1 with
1385 an exception set if the initialization failed. */
1387 static int
1388 init_builtin(char *name)
1390 struct _inittab *p;
1391 PyObject *mod;
1393 if ((mod = _PyImport_FindExtension(name, name)) != NULL)
1394 return 1;
1396 for (p = PyImport_Inittab; p->name != NULL; p++) {
1397 if (strcmp(name, p->name) == 0) {
1398 if (p->initfunc == NULL) {
1399 PyErr_Format(PyExc_ImportError,
1400 "Cannot re-init internal module %.200s",
1401 name);
1402 return -1;
1404 if (Py_VerboseFlag)
1405 PySys_WriteStderr("import %s # builtin\n", name);
1406 (*p->initfunc)();
1407 if (PyErr_Occurred())
1408 return -1;
1409 if (_PyImport_FixupExtension(name, name) == NULL)
1410 return -1;
1411 return 1;
1414 return 0;
1418 /* Frozen modules */
1420 static struct _frozen *
1421 find_frozen(char *name)
1423 struct _frozen *p;
1425 for (p = PyImport_FrozenModules; ; p++) {
1426 if (p->name == NULL)
1427 return NULL;
1428 if (strcmp(p->name, name) == 0)
1429 break;
1431 return p;
1434 static PyObject *
1435 get_frozen_object(char *name)
1437 struct _frozen *p = find_frozen(name);
1438 int size;
1440 if (p == NULL) {
1441 PyErr_Format(PyExc_ImportError,
1442 "No such frozen object named %.200s",
1443 name);
1444 return NULL;
1446 size = p->size;
1447 if (size < 0)
1448 size = -size;
1449 return PyMarshal_ReadObjectFromString((char *)p->code, size);
1452 /* Initialize a frozen module.
1453 Return 1 for succes, 0 if the module is not found, and -1 with
1454 an exception set if the initialization failed.
1455 This function is also used from frozenmain.c */
1458 PyImport_ImportFrozenModule(char *name)
1460 struct _frozen *p = find_frozen(name);
1461 PyObject *co;
1462 PyObject *m;
1463 int ispackage;
1464 int size;
1466 if (p == NULL)
1467 return 0;
1468 size = p->size;
1469 ispackage = (size < 0);
1470 if (ispackage)
1471 size = -size;
1472 if (Py_VerboseFlag)
1473 PySys_WriteStderr("import %s # frozen%s\n",
1474 name, ispackage ? " package" : "");
1475 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1476 if (co == NULL)
1477 return -1;
1478 if (!PyCode_Check(co)) {
1479 Py_DECREF(co);
1480 PyErr_Format(PyExc_TypeError,
1481 "frozen object %.200s is not a code object",
1482 name);
1483 return -1;
1485 if (ispackage) {
1486 /* Set __path__ to the package name */
1487 PyObject *d, *s;
1488 int err;
1489 m = PyImport_AddModule(name);
1490 if (m == NULL)
1491 return -1;
1492 d = PyModule_GetDict(m);
1493 s = PyString_InternFromString(name);
1494 if (s == NULL)
1495 return -1;
1496 err = PyDict_SetItemString(d, "__path__", s);
1497 Py_DECREF(s);
1498 if (err != 0)
1499 return err;
1501 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
1502 Py_DECREF(co);
1503 if (m == NULL)
1504 return -1;
1505 Py_DECREF(m);
1506 return 1;
1510 /* Import a module, either built-in, frozen, or external, and return
1511 its module object WITH INCREMENTED REFERENCE COUNT */
1513 PyObject *
1514 PyImport_ImportModule(char *name)
1516 PyObject *pname;
1517 PyObject *result;
1519 pname = PyString_FromString(name);
1520 result = PyImport_Import(pname);
1521 Py_DECREF(pname);
1522 return result;
1525 /* Forward declarations for helper routines */
1526 static PyObject *get_parent(PyObject *globals, char *buf, int *p_buflen);
1527 static PyObject *load_next(PyObject *mod, PyObject *altmod,
1528 char **p_name, char *buf, int *p_buflen);
1529 static int mark_miss(char *name);
1530 static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1531 char *buf, int buflen, int recursive);
1532 static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
1534 /* The Magnum Opus of dotted-name import :-) */
1536 static PyObject *
1537 import_module_ex(char *name, PyObject *globals, PyObject *locals,
1538 PyObject *fromlist)
1540 char buf[MAXPATHLEN+1];
1541 int buflen = 0;
1542 PyObject *parent, *head, *next, *tail;
1544 parent = get_parent(globals, buf, &buflen);
1545 if (parent == NULL)
1546 return NULL;
1548 head = load_next(parent, Py_None, &name, buf, &buflen);
1549 if (head == NULL)
1550 return NULL;
1552 tail = head;
1553 Py_INCREF(tail);
1554 while (name) {
1555 next = load_next(tail, tail, &name, buf, &buflen);
1556 Py_DECREF(tail);
1557 if (next == NULL) {
1558 Py_DECREF(head);
1559 return NULL;
1561 tail = next;
1564 if (fromlist != NULL) {
1565 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
1566 fromlist = NULL;
1569 if (fromlist == NULL) {
1570 Py_DECREF(tail);
1571 return head;
1574 Py_DECREF(head);
1575 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
1576 Py_DECREF(tail);
1577 return NULL;
1580 return tail;
1583 PyObject *
1584 PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
1585 PyObject *fromlist)
1587 PyObject *result;
1588 lock_import();
1589 result = import_module_ex(name, globals, locals, fromlist);
1590 unlock_import();
1591 return result;
1594 static PyObject *
1595 get_parent(PyObject *globals, char *buf, int *p_buflen)
1597 static PyObject *namestr = NULL;
1598 static PyObject *pathstr = NULL;
1599 PyObject *modname, *modpath, *modules, *parent;
1601 if (globals == NULL || !PyDict_Check(globals))
1602 return Py_None;
1604 if (namestr == NULL) {
1605 namestr = PyString_InternFromString("__name__");
1606 if (namestr == NULL)
1607 return NULL;
1609 if (pathstr == NULL) {
1610 pathstr = PyString_InternFromString("__path__");
1611 if (pathstr == NULL)
1612 return NULL;
1615 *buf = '\0';
1616 *p_buflen = 0;
1617 modname = PyDict_GetItem(globals, namestr);
1618 if (modname == NULL || !PyString_Check(modname))
1619 return Py_None;
1621 modpath = PyDict_GetItem(globals, pathstr);
1622 if (modpath != NULL) {
1623 int len = PyString_GET_SIZE(modname);
1624 if (len > MAXPATHLEN) {
1625 PyErr_SetString(PyExc_ValueError,
1626 "Module name too long");
1627 return NULL;
1629 strcpy(buf, PyString_AS_STRING(modname));
1630 *p_buflen = len;
1632 else {
1633 char *start = PyString_AS_STRING(modname);
1634 char *lastdot = strrchr(start, '.');
1635 size_t len;
1636 if (lastdot == NULL)
1637 return Py_None;
1638 len = lastdot - start;
1639 if (len >= MAXPATHLEN) {
1640 PyErr_SetString(PyExc_ValueError,
1641 "Module name too long");
1642 return NULL;
1644 strncpy(buf, start, len);
1645 buf[len] = '\0';
1646 *p_buflen = len;
1649 modules = PyImport_GetModuleDict();
1650 parent = PyDict_GetItemString(modules, buf);
1651 if (parent == NULL)
1652 parent = Py_None;
1653 return parent;
1654 /* We expect, but can't guarantee, if parent != None, that:
1655 - parent.__name__ == buf
1656 - parent.__dict__ is globals
1657 If this is violated... Who cares? */
1660 /* altmod is either None or same as mod */
1661 static PyObject *
1662 load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
1663 int *p_buflen)
1665 char *name = *p_name;
1666 char *dot = strchr(name, '.');
1667 size_t len;
1668 char *p;
1669 PyObject *result;
1671 if (dot == NULL) {
1672 *p_name = NULL;
1673 len = strlen(name);
1675 else {
1676 *p_name = dot+1;
1677 len = dot-name;
1679 if (len == 0) {
1680 PyErr_SetString(PyExc_ValueError,
1681 "Empty module name");
1682 return NULL;
1685 p = buf + *p_buflen;
1686 if (p != buf)
1687 *p++ = '.';
1688 if (p+len-buf >= MAXPATHLEN) {
1689 PyErr_SetString(PyExc_ValueError,
1690 "Module name too long");
1691 return NULL;
1693 strncpy(p, name, len);
1694 p[len] = '\0';
1695 *p_buflen = p+len-buf;
1697 result = import_submodule(mod, p, buf);
1698 if (result == Py_None && altmod != mod) {
1699 Py_DECREF(result);
1700 /* Here, altmod must be None and mod must not be None */
1701 result = import_submodule(altmod, p, p);
1702 if (result != NULL && result != Py_None) {
1703 if (mark_miss(buf) != 0) {
1704 Py_DECREF(result);
1705 return NULL;
1707 strncpy(buf, name, len);
1708 buf[len] = '\0';
1709 *p_buflen = len;
1712 if (result == NULL)
1713 return NULL;
1715 if (result == Py_None) {
1716 Py_DECREF(result);
1717 PyErr_Format(PyExc_ImportError,
1718 "No module named %.200s", name);
1719 return NULL;
1722 return result;
1725 static int
1726 mark_miss(char *name)
1728 PyObject *modules = PyImport_GetModuleDict();
1729 return PyDict_SetItemString(modules, name, Py_None);
1732 static int
1733 ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, int buflen,
1734 int recursive)
1736 int i;
1738 if (!PyObject_HasAttrString(mod, "__path__"))
1739 return 1;
1741 for (i = 0; ; i++) {
1742 PyObject *item = PySequence_GetItem(fromlist, i);
1743 int hasit;
1744 if (item == NULL) {
1745 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
1746 PyErr_Clear();
1747 return 1;
1749 return 0;
1751 if (!PyString_Check(item)) {
1752 PyErr_SetString(PyExc_TypeError,
1753 "Item in ``from list'' not a string");
1754 Py_DECREF(item);
1755 return 0;
1757 if (PyString_AS_STRING(item)[0] == '*') {
1758 PyObject *all;
1759 Py_DECREF(item);
1760 /* See if the package defines __all__ */
1761 if (recursive)
1762 continue; /* Avoid endless recursion */
1763 all = PyObject_GetAttrString(mod, "__all__");
1764 if (all == NULL)
1765 PyErr_Clear();
1766 else {
1767 if (!ensure_fromlist(mod, all, buf, buflen, 1))
1768 return 0;
1769 Py_DECREF(all);
1771 continue;
1773 hasit = PyObject_HasAttr(mod, item);
1774 if (!hasit) {
1775 char *subname = PyString_AS_STRING(item);
1776 PyObject *submod;
1777 char *p;
1778 if (buflen + strlen(subname) >= MAXPATHLEN) {
1779 PyErr_SetString(PyExc_ValueError,
1780 "Module name too long");
1781 Py_DECREF(item);
1782 return 0;
1784 p = buf + buflen;
1785 *p++ = '.';
1786 strcpy(p, subname);
1787 submod = import_submodule(mod, subname, buf);
1788 Py_XDECREF(submod);
1789 if (submod == NULL) {
1790 Py_DECREF(item);
1791 return 0;
1794 Py_DECREF(item);
1797 /* NOTREACHED */
1800 static PyObject *
1801 import_submodule(PyObject *mod, char *subname, char *fullname)
1803 PyObject *modules = PyImport_GetModuleDict();
1804 PyObject *m, *res = NULL;
1806 /* Require:
1807 if mod == None: subname == fullname
1808 else: mod.__name__ + "." + subname == fullname
1811 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
1812 Py_INCREF(m);
1814 else {
1815 PyObject *path;
1816 char buf[MAXPATHLEN+1];
1817 struct filedescr *fdp;
1818 FILE *fp = NULL;
1820 if (mod == Py_None)
1821 path = NULL;
1822 else {
1823 path = PyObject_GetAttrString(mod, "__path__");
1824 if (path == NULL) {
1825 PyErr_Clear();
1826 Py_INCREF(Py_None);
1827 return Py_None;
1831 buf[0] = '\0';
1832 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1833 Py_XDECREF(path);
1834 if (fdp == NULL) {
1835 if (!PyErr_ExceptionMatches(PyExc_ImportError))
1836 return NULL;
1837 PyErr_Clear();
1838 Py_INCREF(Py_None);
1839 return Py_None;
1841 m = load_module(fullname, fp, buf, fdp->type);
1842 if (fp)
1843 fclose(fp);
1844 if (mod != Py_None) {
1845 /* Irrespective of the success of this load, make a
1846 reference to it in the parent package module.
1847 A copy gets saved in the modules dictionary
1848 under the full name, so get a reference from
1849 there, if need be. (The exception is when
1850 the load failed with a SyntaxError -- then
1851 there's no trace in sys.modules. In that case,
1852 of course, do nothing extra.) */
1853 res = m;
1854 if (res == NULL)
1855 res = PyDict_GetItemString(modules, fullname);
1856 if (res != NULL &&
1857 PyObject_SetAttrString(mod, subname, res) < 0) {
1858 Py_XDECREF(m);
1859 m = NULL;
1864 return m;
1868 /* Re-import a module of any kind and return its module object, WITH
1869 INCREMENTED REFERENCE COUNT */
1871 PyObject *
1872 PyImport_ReloadModule(PyObject *m)
1874 PyObject *modules = PyImport_GetModuleDict();
1875 PyObject *path = NULL;
1876 char *name, *subname;
1877 char buf[MAXPATHLEN+1];
1878 struct filedescr *fdp;
1879 FILE *fp = NULL;
1881 if (m == NULL || !PyModule_Check(m)) {
1882 PyErr_SetString(PyExc_TypeError,
1883 "reload() argument must be module");
1884 return NULL;
1886 name = PyModule_GetName(m);
1887 if (name == NULL)
1888 return NULL;
1889 if (m != PyDict_GetItemString(modules, name)) {
1890 PyErr_Format(PyExc_ImportError,
1891 "reload(): module %.200s not in sys.modules",
1892 name);
1893 return NULL;
1895 subname = strrchr(name, '.');
1896 if (subname == NULL)
1897 subname = name;
1898 else {
1899 PyObject *parentname, *parent;
1900 parentname = PyString_FromStringAndSize(name, (subname-name));
1901 if (parentname == NULL)
1902 return NULL;
1903 parent = PyDict_GetItem(modules, parentname);
1904 Py_DECREF(parentname);
1905 if (parent == NULL) {
1906 PyErr_Format(PyExc_ImportError,
1907 "reload(): parent %.200s not in sys.modules",
1908 name);
1909 return NULL;
1911 subname++;
1912 path = PyObject_GetAttrString(parent, "__path__");
1913 if (path == NULL)
1914 PyErr_Clear();
1916 buf[0] = '\0';
1917 fdp = find_module(subname, path, buf, MAXPATHLEN+1, &fp);
1918 Py_XDECREF(path);
1919 if (fdp == NULL)
1920 return NULL;
1921 m = load_module(name, fp, buf, fdp->type);
1922 if (fp)
1923 fclose(fp);
1924 return m;
1928 /* Higher-level import emulator which emulates the "import" statement
1929 more accurately -- it invokes the __import__() function from the
1930 builtins of the current globals. This means that the import is
1931 done using whatever import hooks are installed in the current
1932 environment, e.g. by "rexec".
1933 A dummy list ["__doc__"] is passed as the 4th argument so that
1934 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
1935 will return <module "gencache"> instead of <module "win32com">. */
1937 PyObject *
1938 PyImport_Import(PyObject *module_name)
1940 static PyObject *silly_list = NULL;
1941 static PyObject *builtins_str = NULL;
1942 static PyObject *import_str = NULL;
1943 PyObject *globals = NULL;
1944 PyObject *import = NULL;
1945 PyObject *builtins = NULL;
1946 PyObject *r = NULL;
1948 /* Initialize constant string objects */
1949 if (silly_list == NULL) {
1950 import_str = PyString_InternFromString("__import__");
1951 if (import_str == NULL)
1952 return NULL;
1953 builtins_str = PyString_InternFromString("__builtins__");
1954 if (builtins_str == NULL)
1955 return NULL;
1956 silly_list = Py_BuildValue("[s]", "__doc__");
1957 if (silly_list == NULL)
1958 return NULL;
1961 /* Get the builtins from current globals */
1962 globals = PyEval_GetGlobals();
1963 if (globals != NULL) {
1964 Py_INCREF(globals);
1965 builtins = PyObject_GetItem(globals, builtins_str);
1966 if (builtins == NULL)
1967 goto err;
1969 else {
1970 /* No globals -- use standard builtins, and fake globals */
1971 PyErr_Clear();
1973 builtins = PyImport_ImportModuleEx("__builtin__",
1974 NULL, NULL, NULL);
1975 if (builtins == NULL)
1976 return NULL;
1977 globals = Py_BuildValue("{OO}", builtins_str, builtins);
1978 if (globals == NULL)
1979 goto err;
1982 /* Get the __import__ function from the builtins */
1983 if (PyDict_Check(builtins)) {
1984 import = PyObject_GetItem(builtins, import_str);
1985 if (import == NULL)
1986 PyErr_SetObject(PyExc_KeyError, import_str);
1988 else
1989 import = PyObject_GetAttr(builtins, import_str);
1990 if (import == NULL)
1991 goto err;
1993 /* Call the _import__ function with the proper argument list */
1994 r = PyObject_CallFunction(import, "OOOO",
1995 module_name, globals, globals, silly_list);
1997 err:
1998 Py_XDECREF(globals);
1999 Py_XDECREF(builtins);
2000 Py_XDECREF(import);
2002 return r;
2006 /* Module 'imp' provides Python access to the primitives used for
2007 importing modules.
2010 static PyObject *
2011 imp_get_magic(PyObject *self, PyObject *args)
2013 char buf[4];
2015 if (!PyArg_ParseTuple(args, ":get_magic"))
2016 return NULL;
2017 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2018 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2019 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2020 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
2022 return PyString_FromStringAndSize(buf, 4);
2025 static PyObject *
2026 imp_get_suffixes(PyObject *self, PyObject *args)
2028 PyObject *list;
2029 struct filedescr *fdp;
2031 if (!PyArg_ParseTuple(args, ":get_suffixes"))
2032 return NULL;
2033 list = PyList_New(0);
2034 if (list == NULL)
2035 return NULL;
2036 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2037 PyObject *item = Py_BuildValue("ssi",
2038 fdp->suffix, fdp->mode, fdp->type);
2039 if (item == NULL) {
2040 Py_DECREF(list);
2041 return NULL;
2043 if (PyList_Append(list, item) < 0) {
2044 Py_DECREF(list);
2045 Py_DECREF(item);
2046 return NULL;
2048 Py_DECREF(item);
2050 return list;
2053 static PyObject *
2054 call_find_module(char *name, PyObject *path)
2056 extern int fclose(FILE *);
2057 PyObject *fob, *ret;
2058 struct filedescr *fdp;
2059 char pathname[MAXPATHLEN+1];
2060 FILE *fp = NULL;
2062 pathname[0] = '\0';
2063 if (path == Py_None)
2064 path = NULL;
2065 fdp = find_module(name, path, pathname, MAXPATHLEN+1, &fp);
2066 if (fdp == NULL)
2067 return NULL;
2068 if (fp != NULL) {
2069 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2070 if (fob == NULL) {
2071 fclose(fp);
2072 return NULL;
2075 else {
2076 fob = Py_None;
2077 Py_INCREF(fob);
2079 ret = Py_BuildValue("Os(ssi)",
2080 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
2081 Py_DECREF(fob);
2082 return ret;
2085 static PyObject *
2086 imp_find_module(PyObject *self, PyObject *args)
2088 char *name;
2089 PyObject *path = NULL;
2090 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
2091 return NULL;
2092 return call_find_module(name, path);
2095 static PyObject *
2096 imp_init_builtin(PyObject *self, PyObject *args)
2098 char *name;
2099 int ret;
2100 PyObject *m;
2101 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
2102 return NULL;
2103 ret = init_builtin(name);
2104 if (ret < 0)
2105 return NULL;
2106 if (ret == 0) {
2107 Py_INCREF(Py_None);
2108 return Py_None;
2110 m = PyImport_AddModule(name);
2111 Py_XINCREF(m);
2112 return m;
2115 static PyObject *
2116 imp_init_frozen(PyObject *self, PyObject *args)
2118 char *name;
2119 int ret;
2120 PyObject *m;
2121 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
2122 return NULL;
2123 ret = PyImport_ImportFrozenModule(name);
2124 if (ret < 0)
2125 return NULL;
2126 if (ret == 0) {
2127 Py_INCREF(Py_None);
2128 return Py_None;
2130 m = PyImport_AddModule(name);
2131 Py_XINCREF(m);
2132 return m;
2135 static PyObject *
2136 imp_get_frozen_object(PyObject *self, PyObject *args)
2138 char *name;
2140 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2141 return NULL;
2142 return get_frozen_object(name);
2145 static PyObject *
2146 imp_is_builtin(PyObject *self, PyObject *args)
2148 char *name;
2149 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2150 return NULL;
2151 return PyInt_FromLong(is_builtin(name));
2154 static PyObject *
2155 imp_is_frozen(PyObject *self, PyObject *args)
2157 char *name;
2158 struct _frozen *p;
2159 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
2160 return NULL;
2161 p = find_frozen(name);
2162 return PyInt_FromLong((long) (p == NULL ? 0 : p->size));
2165 static FILE *
2166 get_file(char *pathname, PyObject *fob, char *mode)
2168 FILE *fp;
2169 if (fob == NULL) {
2170 fp = fopen(pathname, mode);
2171 if (fp == NULL)
2172 PyErr_SetFromErrno(PyExc_IOError);
2174 else {
2175 fp = PyFile_AsFile(fob);
2176 if (fp == NULL)
2177 PyErr_SetString(PyExc_ValueError,
2178 "bad/closed file object");
2180 return fp;
2183 static PyObject *
2184 imp_load_compiled(PyObject *self, PyObject *args)
2186 char *name;
2187 char *pathname;
2188 PyObject *fob = NULL;
2189 PyObject *m;
2190 FILE *fp;
2191 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
2192 &PyFile_Type, &fob))
2193 return NULL;
2194 fp = get_file(pathname, fob, "rb");
2195 if (fp == NULL)
2196 return NULL;
2197 m = load_compiled_module(name, pathname, fp);
2198 if (fob == NULL)
2199 fclose(fp);
2200 return m;
2203 #ifdef HAVE_DYNAMIC_LOADING
2205 static PyObject *
2206 imp_load_dynamic(PyObject *self, PyObject *args)
2208 char *name;
2209 char *pathname;
2210 PyObject *fob = NULL;
2211 PyObject *m;
2212 FILE *fp = NULL;
2213 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
2214 &PyFile_Type, &fob))
2215 return NULL;
2216 if (fob) {
2217 fp = get_file(pathname, fob, "r");
2218 if (fp == NULL)
2219 return NULL;
2221 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2222 return m;
2225 #endif /* HAVE_DYNAMIC_LOADING */
2227 static PyObject *
2228 imp_load_source(PyObject *self, PyObject *args)
2230 char *name;
2231 char *pathname;
2232 PyObject *fob = NULL;
2233 PyObject *m;
2234 FILE *fp;
2235 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
2236 &PyFile_Type, &fob))
2237 return NULL;
2238 fp = get_file(pathname, fob, "r");
2239 if (fp == NULL)
2240 return NULL;
2241 m = load_source_module(name, pathname, fp);
2242 if (fob == NULL)
2243 fclose(fp);
2244 return m;
2247 #ifdef macintosh
2248 static PyObject *
2249 imp_load_resource(PyObject *self, PyObject *args)
2251 char *name;
2252 char *pathname;
2253 PyObject *m;
2255 if (!PyArg_ParseTuple(args, "ss:load_resource", &name, &pathname))
2256 return NULL;
2257 m = PyMac_LoadResourceModule(name, pathname);
2258 return m;
2260 #endif /* macintosh */
2262 static PyObject *
2263 imp_load_module(PyObject *self, PyObject *args)
2265 char *name;
2266 PyObject *fob;
2267 char *pathname;
2268 char *suffix; /* Unused */
2269 char *mode;
2270 int type;
2271 FILE *fp;
2273 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
2274 &name, &fob, &pathname,
2275 &suffix, &mode, &type))
2276 return NULL;
2277 if (*mode && (*mode != 'r' || strchr(mode, '+') != NULL)) {
2278 PyErr_Format(PyExc_ValueError,
2279 "invalid file open mode %.200s", mode);
2280 return NULL;
2282 if (fob == Py_None)
2283 fp = NULL;
2284 else {
2285 if (!PyFile_Check(fob)) {
2286 PyErr_SetString(PyExc_ValueError,
2287 "load_module arg#2 should be a file or None");
2288 return NULL;
2290 fp = get_file(pathname, fob, mode);
2291 if (fp == NULL)
2292 return NULL;
2294 return load_module(name, fp, pathname, type);
2297 static PyObject *
2298 imp_load_package(PyObject *self, PyObject *args)
2300 char *name;
2301 char *pathname;
2302 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
2303 return NULL;
2304 return load_package(name, pathname);
2307 static PyObject *
2308 imp_new_module(PyObject *self, PyObject *args)
2310 char *name;
2311 if (!PyArg_ParseTuple(args, "s:new_module", &name))
2312 return NULL;
2313 return PyModule_New(name);
2316 /* Doc strings */
2318 static char doc_imp[] = "\
2319 This module provides the components needed to build your own\n\
2320 __import__ function. Undocumented functions are obsolete.\n\
2323 static char doc_find_module[] = "\
2324 find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2325 Search for a module. If path is omitted or None, search for a\n\
2326 built-in, frozen or special module and continue search in sys.path.\n\
2327 The module name cannot contain '.'; to search for a submodule of a\n\
2328 package, pass the submodule name and the package's __path__.\
2331 static char doc_load_module[] = "\
2332 load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2333 Load a module, given information returned by find_module().\n\
2334 The module name must include the full package name, if any.\
2337 static char doc_get_magic[] = "\
2338 get_magic() -> string\n\
2339 Return the magic number for .pyc or .pyo files.\
2342 static char doc_get_suffixes[] = "\
2343 get_suffixes() -> [(suffix, mode, type), ...]\n\
2344 Return a list of (suffix, mode, type) tuples describing the files\n\
2345 that find_module() looks for.\
2348 static char doc_new_module[] = "\
2349 new_module(name) -> module\n\
2350 Create a new module. Do not enter it in sys.modules.\n\
2351 The module name must include the full package name, if any.\
2354 static char doc_lock_held[] = "\
2355 lock_held() -> 0 or 1\n\
2356 Return 1 if the import lock is currently held.\n\
2357 On platforms without threads, return 0.\
2360 static PyMethodDef imp_methods[] = {
2361 {"find_module", imp_find_module, 1, doc_find_module},
2362 {"get_magic", imp_get_magic, 1, doc_get_magic},
2363 {"get_suffixes", imp_get_suffixes, 1, doc_get_suffixes},
2364 {"load_module", imp_load_module, 1, doc_load_module},
2365 {"new_module", imp_new_module, 1, doc_new_module},
2366 {"lock_held", imp_lock_held, 1, doc_lock_held},
2367 /* The rest are obsolete */
2368 {"get_frozen_object", imp_get_frozen_object, 1},
2369 {"init_builtin", imp_init_builtin, 1},
2370 {"init_frozen", imp_init_frozen, 1},
2371 {"is_builtin", imp_is_builtin, 1},
2372 {"is_frozen", imp_is_frozen, 1},
2373 {"load_compiled", imp_load_compiled, 1},
2374 #ifdef HAVE_DYNAMIC_LOADING
2375 {"load_dynamic", imp_load_dynamic, 1},
2376 #endif
2377 {"load_package", imp_load_package, 1},
2378 #ifdef macintosh
2379 {"load_resource", imp_load_resource, 1},
2380 #endif
2381 {"load_source", imp_load_source, 1},
2382 {NULL, NULL} /* sentinel */
2385 static int
2386 setint(PyObject *d, char *name, int value)
2388 PyObject *v;
2389 int err;
2391 v = PyInt_FromLong((long)value);
2392 err = PyDict_SetItemString(d, name, v);
2393 Py_XDECREF(v);
2394 return err;
2397 void
2398 initimp(void)
2400 PyObject *m, *d;
2402 m = Py_InitModule4("imp", imp_methods, doc_imp,
2403 NULL, PYTHON_API_VERSION);
2404 d = PyModule_GetDict(m);
2406 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2407 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2408 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2409 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2410 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2411 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2412 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2413 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
2414 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
2416 failure:
2421 /* API for embedding applications that want to add their own entries
2422 to the table of built-in modules. This should normally be called
2423 *before* Py_Initialize(). When the table resize fails, -1 is
2424 returned and the existing table is unchanged.
2426 After a similar function by Just van Rossum. */
2429 PyImport_ExtendInittab(struct _inittab *newtab)
2431 static struct _inittab *our_copy = NULL;
2432 struct _inittab *p;
2433 int i, n;
2435 /* Count the number of entries in both tables */
2436 for (n = 0; newtab[n].name != NULL; n++)
2438 if (n == 0)
2439 return 0; /* Nothing to do */
2440 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2443 /* Allocate new memory for the combined table */
2444 p = our_copy;
2445 PyMem_RESIZE(p, struct _inittab, i+n+1);
2446 if (p == NULL)
2447 return -1;
2449 /* Copy the tables into the new memory */
2450 if (our_copy != PyImport_Inittab)
2451 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2452 PyImport_Inittab = our_copy = p;
2453 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2455 return 0;
2458 /* Shorthand to add a single entry given a name and a function */
2461 PyImport_AppendInittab(char *name, void (*initfunc)(void))
2463 struct _inittab newtab[2];
2465 memset(newtab, '\0', sizeof newtab);
2467 newtab[0].name = name;
2468 newtab[0].initfunc = initfunc;
2470 return PyImport_ExtendInittab(newtab);