issue1597011: Fix for bz2 module corner-case error due to error checking bug.
[python.git] / Python / import.c
blobe5f7cc61fcf8f4e781caf4ae007604ab74be3db6
2 /* Module definition and import implementation */
4 #include "Python.h"
6 #include "Python-ast.h"
7 #undef Yield /* undefine macro conflicting with winbase.h */
8 #include "pyarena.h"
9 #include "pythonrun.h"
10 #include "errcode.h"
11 #include "marshal.h"
12 #include "code.h"
13 #include "compile.h"
14 #include "eval.h"
15 #include "osdefs.h"
16 #include "importdl.h"
18 #ifdef HAVE_FCNTL_H
19 #include <fcntl.h>
20 #endif
21 #ifdef __cplusplus
22 extern "C" {
23 #endif
25 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
26 /* In getmtime.c */
28 /* Magic word to reject .pyc files generated by other Python versions.
29 It should change for each incompatible change to the bytecode.
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.
35 The magic numbers must be spaced apart atleast 2 values, as the
36 -U interpeter flag will cause MAGIC+1 being used. They have been
37 odd numbers for some time now.
39 There were a variety of old schemes for setting the magic number.
40 The current working scheme is to increment the previous value by
41 10.
43 Known values:
44 Python 1.5: 20121
45 Python 1.5.1: 20121
46 Python 1.5.2: 20121
47 Python 1.6: 50428
48 Python 2.0: 50823
49 Python 2.0.1: 50823
50 Python 2.1: 60202
51 Python 2.1.1: 60202
52 Python 2.1.2: 60202
53 Python 2.2: 60717
54 Python 2.3a0: 62011
55 Python 2.3a0: 62021
56 Python 2.3a0: 62011 (!)
57 Python 2.4a0: 62041
58 Python 2.4a3: 62051
59 Python 2.4b1: 62061
60 Python 2.5a0: 62071
61 Python 2.5a0: 62081 (ast-branch)
62 Python 2.5a0: 62091 (with)
63 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
64 Python 2.5b3: 62101 (fix wrong code: for x, in ...)
65 Python 2.5b3: 62111 (fix wrong code: x += yield)
66 Python 2.5c1: 62121 (fix wrong lnotab with for loops and
67 storing constants that should have been removed)
68 Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
69 Python 2.6a0: 62141 (peephole optimizations)
72 #define MAGIC (62141 | ((long)'\r'<<16) | ((long)'\n'<<24))
74 /* Magic word as global; note that _PyImport_Init() can change the
75 value of this global to accommodate for alterations of how the
76 compiler works which are enabled by command line switches. */
77 static long pyc_magic = MAGIC;
79 /* See _PyImport_FixupExtension() below */
80 static PyObject *extensions = NULL;
82 /* This table is defined in config.c: */
83 extern struct _inittab _PyImport_Inittab[];
85 struct _inittab *PyImport_Inittab = _PyImport_Inittab;
87 /* these tables define the module suffixes that Python recognizes */
88 struct filedescr * _PyImport_Filetab = NULL;
90 #ifdef RISCOS
91 static const struct filedescr _PyImport_StandardFiletab[] = {
92 {"/py", "U", PY_SOURCE},
93 {"/pyc", "rb", PY_COMPILED},
94 {0, 0}
96 #else
97 static const struct filedescr _PyImport_StandardFiletab[] = {
98 {".py", "U", PY_SOURCE},
99 #ifdef MS_WINDOWS
100 {".pyw", "U", PY_SOURCE},
101 #endif
102 {".pyc", "rb", PY_COMPILED},
103 {0, 0}
105 #endif
107 static PyTypeObject NullImporterType; /* Forward reference */
109 /* Initialize things */
111 void
112 _PyImport_Init(void)
114 const struct filedescr *scan;
115 struct filedescr *filetab;
116 int countD = 0;
117 int countS = 0;
119 /* prepare _PyImport_Filetab: copy entries from
120 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
122 #ifdef HAVE_DYNAMIC_LOADING
123 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
124 ++countD;
125 #endif
126 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
127 ++countS;
128 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
129 if (filetab == NULL)
130 Py_FatalError("Can't initialize import file table.");
131 #ifdef HAVE_DYNAMIC_LOADING
132 memcpy(filetab, _PyImport_DynLoadFiletab,
133 countD * sizeof(struct filedescr));
134 #endif
135 memcpy(filetab + countD, _PyImport_StandardFiletab,
136 countS * sizeof(struct filedescr));
137 filetab[countD + countS].suffix = NULL;
139 _PyImport_Filetab = filetab;
141 if (Py_OptimizeFlag) {
142 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
143 for (; filetab->suffix != NULL; filetab++) {
144 #ifndef RISCOS
145 if (strcmp(filetab->suffix, ".pyc") == 0)
146 filetab->suffix = ".pyo";
147 #else
148 if (strcmp(filetab->suffix, "/pyc") == 0)
149 filetab->suffix = "/pyo";
150 #endif
154 if (Py_UnicodeFlag) {
155 /* Fix the pyc_magic so that byte compiled code created
156 using the all-Unicode method doesn't interfere with
157 code created in normal operation mode. */
158 pyc_magic = MAGIC + 1;
162 void
163 _PyImportHooks_Init(void)
165 PyObject *v, *path_hooks = NULL, *zimpimport;
166 int err = 0;
168 /* adding sys.path_hooks and sys.path_importer_cache, setting up
169 zipimport */
170 if (PyType_Ready(&NullImporterType) < 0)
171 goto error;
173 if (Py_VerboseFlag)
174 PySys_WriteStderr("# installing zipimport hook\n");
176 v = PyList_New(0);
177 if (v == NULL)
178 goto error;
179 err = PySys_SetObject("meta_path", v);
180 Py_DECREF(v);
181 if (err)
182 goto error;
183 v = PyDict_New();
184 if (v == NULL)
185 goto error;
186 err = PySys_SetObject("path_importer_cache", v);
187 Py_DECREF(v);
188 if (err)
189 goto error;
190 path_hooks = PyList_New(0);
191 if (path_hooks == NULL)
192 goto error;
193 err = PySys_SetObject("path_hooks", path_hooks);
194 if (err) {
195 error:
196 PyErr_Print();
197 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
198 "path_importer_cache, or NullImporter failed"
202 zimpimport = PyImport_ImportModule("zipimport");
203 if (zimpimport == NULL) {
204 PyErr_Clear(); /* No zip import module -- okay */
205 if (Py_VerboseFlag)
206 PySys_WriteStderr("# can't import zipimport\n");
208 else {
209 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
210 "zipimporter");
211 Py_DECREF(zimpimport);
212 if (zipimporter == NULL) {
213 PyErr_Clear(); /* No zipimporter object -- okay */
214 if (Py_VerboseFlag)
215 PySys_WriteStderr(
216 "# can't import zipimport.zipimporter\n");
218 else {
219 /* sys.path_hooks.append(zipimporter) */
220 err = PyList_Append(path_hooks, zipimporter);
221 Py_DECREF(zipimporter);
222 if (err)
223 goto error;
224 if (Py_VerboseFlag)
225 PySys_WriteStderr(
226 "# installed zipimport hook\n");
229 Py_DECREF(path_hooks);
232 void
233 _PyImport_Fini(void)
235 Py_XDECREF(extensions);
236 extensions = NULL;
237 PyMem_DEL(_PyImport_Filetab);
238 _PyImport_Filetab = NULL;
242 /* Locking primitives to prevent parallel imports of the same module
243 in different threads to return with a partially loaded module.
244 These calls are serialized by the global interpreter lock. */
246 #ifdef WITH_THREAD
248 #include "pythread.h"
250 static PyThread_type_lock import_lock = 0;
251 static long import_lock_thread = -1;
252 static int import_lock_level = 0;
254 static void
255 lock_import(void)
257 long me = PyThread_get_thread_ident();
258 if (me == -1)
259 return; /* Too bad */
260 if (import_lock == NULL) {
261 import_lock = PyThread_allocate_lock();
262 if (import_lock == NULL)
263 return; /* Nothing much we can do. */
265 if (import_lock_thread == me) {
266 import_lock_level++;
267 return;
269 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
271 PyThreadState *tstate = PyEval_SaveThread();
272 PyThread_acquire_lock(import_lock, 1);
273 PyEval_RestoreThread(tstate);
275 import_lock_thread = me;
276 import_lock_level = 1;
279 static int
280 unlock_import(void)
282 long me = PyThread_get_thread_ident();
283 if (me == -1 || import_lock == NULL)
284 return 0; /* Too bad */
285 if (import_lock_thread != me)
286 return -1;
287 import_lock_level--;
288 if (import_lock_level == 0) {
289 import_lock_thread = -1;
290 PyThread_release_lock(import_lock);
292 return 1;
295 /* This function is called from PyOS_AfterFork to ensure that newly
296 created child processes do not share locks with the parent. */
298 void
299 _PyImport_ReInitLock(void)
301 #ifdef _AIX
302 if (import_lock != NULL)
303 import_lock = PyThread_allocate_lock();
304 #endif
307 #else
309 #define lock_import()
310 #define unlock_import() 0
312 #endif
314 static PyObject *
315 imp_lock_held(PyObject *self, PyObject *noargs)
317 #ifdef WITH_THREAD
318 return PyBool_FromLong(import_lock_thread != -1);
319 #else
320 return PyBool_FromLong(0);
321 #endif
324 static PyObject *
325 imp_acquire_lock(PyObject *self, PyObject *noargs)
327 #ifdef WITH_THREAD
328 lock_import();
329 #endif
330 Py_INCREF(Py_None);
331 return Py_None;
334 static PyObject *
335 imp_release_lock(PyObject *self, PyObject *noargs)
337 #ifdef WITH_THREAD
338 if (unlock_import() < 0) {
339 PyErr_SetString(PyExc_RuntimeError,
340 "not holding the import lock");
341 return NULL;
343 #endif
344 Py_INCREF(Py_None);
345 return Py_None;
348 static void
349 imp_modules_reloading_clear(void)
351 PyInterpreterState *interp = PyThreadState_Get()->interp;
352 if (interp->modules_reloading != NULL)
353 PyDict_Clear(interp->modules_reloading);
356 /* Helper for sys */
358 PyObject *
359 PyImport_GetModuleDict(void)
361 PyInterpreterState *interp = PyThreadState_GET()->interp;
362 if (interp->modules == NULL)
363 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
364 return interp->modules;
368 /* List of names to clear in sys */
369 static char* sys_deletes[] = {
370 "path", "argv", "ps1", "ps2", "exitfunc",
371 "exc_type", "exc_value", "exc_traceback",
372 "last_type", "last_value", "last_traceback",
373 "path_hooks", "path_importer_cache", "meta_path",
374 NULL
377 static char* sys_files[] = {
378 "stdin", "__stdin__",
379 "stdout", "__stdout__",
380 "stderr", "__stderr__",
381 NULL
385 /* Un-initialize things, as good as we can */
387 void
388 PyImport_Cleanup(void)
390 Py_ssize_t pos, ndone;
391 char *name;
392 PyObject *key, *value, *dict;
393 PyInterpreterState *interp = PyThreadState_GET()->interp;
394 PyObject *modules = interp->modules;
396 if (modules == NULL)
397 return; /* Already done */
399 /* Delete some special variables first. These are common
400 places where user values hide and people complain when their
401 destructors fail. Since the modules containing them are
402 deleted *last* of all, they would come too late in the normal
403 destruction order. Sigh. */
405 value = PyDict_GetItemString(modules, "__builtin__");
406 if (value != NULL && PyModule_Check(value)) {
407 dict = PyModule_GetDict(value);
408 if (Py_VerboseFlag)
409 PySys_WriteStderr("# clear __builtin__._\n");
410 PyDict_SetItemString(dict, "_", Py_None);
412 value = PyDict_GetItemString(modules, "sys");
413 if (value != NULL && PyModule_Check(value)) {
414 char **p;
415 PyObject *v;
416 dict = PyModule_GetDict(value);
417 for (p = sys_deletes; *p != NULL; p++) {
418 if (Py_VerboseFlag)
419 PySys_WriteStderr("# clear sys.%s\n", *p);
420 PyDict_SetItemString(dict, *p, Py_None);
422 for (p = sys_files; *p != NULL; p+=2) {
423 if (Py_VerboseFlag)
424 PySys_WriteStderr("# restore sys.%s\n", *p);
425 v = PyDict_GetItemString(dict, *(p+1));
426 if (v == NULL)
427 v = Py_None;
428 PyDict_SetItemString(dict, *p, v);
432 /* First, delete __main__ */
433 value = PyDict_GetItemString(modules, "__main__");
434 if (value != NULL && PyModule_Check(value)) {
435 if (Py_VerboseFlag)
436 PySys_WriteStderr("# cleanup __main__\n");
437 _PyModule_Clear(value);
438 PyDict_SetItemString(modules, "__main__", Py_None);
441 /* The special treatment of __builtin__ here is because even
442 when it's not referenced as a module, its dictionary is
443 referenced by almost every module's __builtins__. Since
444 deleting a module clears its dictionary (even if there are
445 references left to it), we need to delete the __builtin__
446 module last. Likewise, we don't delete sys until the very
447 end because it is implicitly referenced (e.g. by print).
449 Also note that we 'delete' modules by replacing their entry
450 in the modules dict with None, rather than really deleting
451 them; this avoids a rehash of the modules dictionary and
452 also marks them as "non existent" so they won't be
453 re-imported. */
455 /* Next, repeatedly delete modules with a reference count of
456 one (skipping __builtin__ and sys) and delete them */
457 do {
458 ndone = 0;
459 pos = 0;
460 while (PyDict_Next(modules, &pos, &key, &value)) {
461 if (value->ob_refcnt != 1)
462 continue;
463 if (PyString_Check(key) && PyModule_Check(value)) {
464 name = PyString_AS_STRING(key);
465 if (strcmp(name, "__builtin__") == 0)
466 continue;
467 if (strcmp(name, "sys") == 0)
468 continue;
469 if (Py_VerboseFlag)
470 PySys_WriteStderr(
471 "# cleanup[1] %s\n", name);
472 _PyModule_Clear(value);
473 PyDict_SetItem(modules, key, Py_None);
474 ndone++;
477 } while (ndone > 0);
479 /* Next, delete all modules (still skipping __builtin__ and sys) */
480 pos = 0;
481 while (PyDict_Next(modules, &pos, &key, &value)) {
482 if (PyString_Check(key) && PyModule_Check(value)) {
483 name = PyString_AS_STRING(key);
484 if (strcmp(name, "__builtin__") == 0)
485 continue;
486 if (strcmp(name, "sys") == 0)
487 continue;
488 if (Py_VerboseFlag)
489 PySys_WriteStderr("# cleanup[2] %s\n", name);
490 _PyModule_Clear(value);
491 PyDict_SetItem(modules, key, Py_None);
495 /* Next, delete sys and __builtin__ (in that order) */
496 value = PyDict_GetItemString(modules, "sys");
497 if (value != NULL && PyModule_Check(value)) {
498 if (Py_VerboseFlag)
499 PySys_WriteStderr("# cleanup sys\n");
500 _PyModule_Clear(value);
501 PyDict_SetItemString(modules, "sys", Py_None);
503 value = PyDict_GetItemString(modules, "__builtin__");
504 if (value != NULL && PyModule_Check(value)) {
505 if (Py_VerboseFlag)
506 PySys_WriteStderr("# cleanup __builtin__\n");
507 _PyModule_Clear(value);
508 PyDict_SetItemString(modules, "__builtin__", Py_None);
511 /* Finally, clear and delete the modules directory */
512 PyDict_Clear(modules);
513 interp->modules = NULL;
514 Py_DECREF(modules);
515 Py_CLEAR(interp->modules_reloading);
519 /* Helper for pythonrun.c -- return magic number */
521 long
522 PyImport_GetMagicNumber(void)
524 return pyc_magic;
528 /* Magic for extension modules (built-in as well as dynamically
529 loaded). To prevent initializing an extension module more than
530 once, we keep a static dictionary 'extensions' keyed by module name
531 (for built-in modules) or by filename (for dynamically loaded
532 modules), containing these modules. A copy of the module's
533 dictionary is stored by calling _PyImport_FixupExtension()
534 immediately after the module initialization function succeeds. A
535 copy can be retrieved from there by calling
536 _PyImport_FindExtension(). */
538 PyObject *
539 _PyImport_FixupExtension(char *name, char *filename)
541 PyObject *modules, *mod, *dict, *copy;
542 if (extensions == NULL) {
543 extensions = PyDict_New();
544 if (extensions == NULL)
545 return NULL;
547 modules = PyImport_GetModuleDict();
548 mod = PyDict_GetItemString(modules, name);
549 if (mod == NULL || !PyModule_Check(mod)) {
550 PyErr_Format(PyExc_SystemError,
551 "_PyImport_FixupExtension: module %.200s not loaded", name);
552 return NULL;
554 dict = PyModule_GetDict(mod);
555 if (dict == NULL)
556 return NULL;
557 copy = PyDict_Copy(dict);
558 if (copy == NULL)
559 return NULL;
560 PyDict_SetItemString(extensions, filename, copy);
561 Py_DECREF(copy);
562 return copy;
565 PyObject *
566 _PyImport_FindExtension(char *name, char *filename)
568 PyObject *dict, *mod, *mdict;
569 if (extensions == NULL)
570 return NULL;
571 dict = PyDict_GetItemString(extensions, filename);
572 if (dict == NULL)
573 return NULL;
574 mod = PyImport_AddModule(name);
575 if (mod == NULL)
576 return NULL;
577 mdict = PyModule_GetDict(mod);
578 if (mdict == NULL)
579 return NULL;
580 if (PyDict_Update(mdict, dict))
581 return NULL;
582 if (Py_VerboseFlag)
583 PySys_WriteStderr("import %s # previously loaded (%s)\n",
584 name, filename);
585 return mod;
589 /* Get the module object corresponding to a module name.
590 First check the modules dictionary if there's one there,
591 if not, create a new one and insert it in the modules dictionary.
592 Because the former action is most common, THIS DOES NOT RETURN A
593 'NEW' REFERENCE! */
595 PyObject *
596 PyImport_AddModule(const char *name)
598 PyObject *modules = PyImport_GetModuleDict();
599 PyObject *m;
601 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
602 PyModule_Check(m))
603 return m;
604 m = PyModule_New(name);
605 if (m == NULL)
606 return NULL;
607 if (PyDict_SetItemString(modules, name, m) != 0) {
608 Py_DECREF(m);
609 return NULL;
611 Py_DECREF(m); /* Yes, it still exists, in modules! */
613 return m;
616 /* Remove name from sys.modules, if it's there. */
617 static void
618 _RemoveModule(const char *name)
620 PyObject *modules = PyImport_GetModuleDict();
621 if (PyDict_GetItemString(modules, name) == NULL)
622 return;
623 if (PyDict_DelItemString(modules, name) < 0)
624 Py_FatalError("import: deleting existing key in"
625 "sys.modules failed");
628 /* Execute a code object in a module and return the module object
629 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
630 * removed from sys.modules, to avoid leaving damaged module objects
631 * in sys.modules. The caller may wish to restore the original
632 * module object (if any) in this case; PyImport_ReloadModule is an
633 * example.
635 PyObject *
636 PyImport_ExecCodeModule(char *name, PyObject *co)
638 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
641 PyObject *
642 PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
644 PyObject *modules = PyImport_GetModuleDict();
645 PyObject *m, *d, *v;
647 m = PyImport_AddModule(name);
648 if (m == NULL)
649 return NULL;
650 /* If the module is being reloaded, we get the old module back
651 and re-use its dict to exec the new code. */
652 d = PyModule_GetDict(m);
653 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
654 if (PyDict_SetItemString(d, "__builtins__",
655 PyEval_GetBuiltins()) != 0)
656 goto error;
658 /* Remember the filename as the __file__ attribute */
659 v = NULL;
660 if (pathname != NULL) {
661 v = PyString_FromString(pathname);
662 if (v == NULL)
663 PyErr_Clear();
665 if (v == NULL) {
666 v = ((PyCodeObject *)co)->co_filename;
667 Py_INCREF(v);
669 if (PyDict_SetItemString(d, "__file__", v) != 0)
670 PyErr_Clear(); /* Not important enough to report */
671 Py_DECREF(v);
673 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
674 if (v == NULL)
675 goto error;
676 Py_DECREF(v);
678 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
679 PyErr_Format(PyExc_ImportError,
680 "Loaded module %.200s not found in sys.modules",
681 name);
682 return NULL;
685 Py_INCREF(m);
687 return m;
689 error:
690 _RemoveModule(name);
691 return NULL;
695 /* Given a pathname for a Python source file, fill a buffer with the
696 pathname for the corresponding compiled file. Return the pathname
697 for the compiled file, or NULL if there's no space in the buffer.
698 Doesn't set an exception. */
700 static char *
701 make_compiled_pathname(char *pathname, char *buf, size_t buflen)
703 size_t len = strlen(pathname);
704 if (len+2 > buflen)
705 return NULL;
707 #ifdef MS_WINDOWS
708 /* Treat .pyw as if it were .py. The case of ".pyw" must match
709 that used in _PyImport_StandardFiletab. */
710 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
711 --len; /* pretend 'w' isn't there */
712 #endif
713 memcpy(buf, pathname, len);
714 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
715 buf[len+1] = '\0';
717 return buf;
721 /* Given a pathname for a Python source file, its time of last
722 modification, and a pathname for a compiled file, check whether the
723 compiled file represents the same version of the source. If so,
724 return a FILE pointer for the compiled file, positioned just after
725 the header; if not, return NULL.
726 Doesn't set an exception. */
728 static FILE *
729 check_compiled_module(char *pathname, time_t mtime, char *cpathname)
731 FILE *fp;
732 long magic;
733 long pyc_mtime;
735 fp = fopen(cpathname, "rb");
736 if (fp == NULL)
737 return NULL;
738 magic = PyMarshal_ReadLongFromFile(fp);
739 if (magic != pyc_magic) {
740 if (Py_VerboseFlag)
741 PySys_WriteStderr("# %s has bad magic\n", cpathname);
742 fclose(fp);
743 return NULL;
745 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
746 if (pyc_mtime != mtime) {
747 if (Py_VerboseFlag)
748 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
749 fclose(fp);
750 return NULL;
752 if (Py_VerboseFlag)
753 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
754 return fp;
758 /* Read a code object from a file and check it for validity */
760 static PyCodeObject *
761 read_compiled_module(char *cpathname, FILE *fp)
763 PyObject *co;
765 co = PyMarshal_ReadLastObjectFromFile(fp);
766 if (co == NULL)
767 return NULL;
768 if (!PyCode_Check(co)) {
769 PyErr_Format(PyExc_ImportError,
770 "Non-code object in %.200s", cpathname);
771 Py_DECREF(co);
772 return NULL;
774 return (PyCodeObject *)co;
778 /* Load a module from a compiled file, execute it, and return its
779 module object WITH INCREMENTED REFERENCE COUNT */
781 static PyObject *
782 load_compiled_module(char *name, char *cpathname, FILE *fp)
784 long magic;
785 PyCodeObject *co;
786 PyObject *m;
788 magic = PyMarshal_ReadLongFromFile(fp);
789 if (magic != pyc_magic) {
790 PyErr_Format(PyExc_ImportError,
791 "Bad magic number in %.200s", cpathname);
792 return NULL;
794 (void) PyMarshal_ReadLongFromFile(fp);
795 co = read_compiled_module(cpathname, fp);
796 if (co == NULL)
797 return NULL;
798 if (Py_VerboseFlag)
799 PySys_WriteStderr("import %s # precompiled from %s\n",
800 name, cpathname);
801 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
802 Py_DECREF(co);
804 return m;
807 /* Parse a source file and return the corresponding code object */
809 static PyCodeObject *
810 parse_source_module(const char *pathname, FILE *fp)
812 PyCodeObject *co = NULL;
813 mod_ty mod;
814 PyArena *arena = PyArena_New();
815 if (arena == NULL)
816 return NULL;
818 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, 0,
819 NULL, arena);
820 if (mod) {
821 co = PyAST_Compile(mod, pathname, NULL, arena);
823 PyArena_Free(arena);
824 return co;
828 /* Helper to open a bytecode file for writing in exclusive mode */
830 static FILE *
831 open_exclusive(char *filename)
833 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
834 /* Use O_EXCL to avoid a race condition when another process tries to
835 write the same file. When that happens, our open() call fails,
836 which is just fine (since it's only a cache).
837 XXX If the file exists and is writable but the directory is not
838 writable, the file will never be written. Oh well.
840 int fd;
841 (void) unlink(filename);
842 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
843 #ifdef O_BINARY
844 |O_BINARY /* necessary for Windows */
845 #endif
846 #ifdef __VMS
847 , 0666, "ctxt=bin", "shr=nil"
848 #else
849 , 0666
850 #endif
852 if (fd < 0)
853 return NULL;
854 return fdopen(fd, "wb");
855 #else
856 /* Best we can do -- on Windows this can't happen anyway */
857 return fopen(filename, "wb");
858 #endif
862 /* Write a compiled module to a file, placing the time of last
863 modification of its source into the header.
864 Errors are ignored, if a write error occurs an attempt is made to
865 remove the file. */
867 static void
868 write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime)
870 FILE *fp;
872 fp = open_exclusive(cpathname);
873 if (fp == NULL) {
874 if (Py_VerboseFlag)
875 PySys_WriteStderr(
876 "# can't create %s\n", cpathname);
877 return;
879 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
880 /* First write a 0 for mtime */
881 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
882 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
883 if (fflush(fp) != 0 || ferror(fp)) {
884 if (Py_VerboseFlag)
885 PySys_WriteStderr("# can't write %s\n", cpathname);
886 /* Don't keep partial file */
887 fclose(fp);
888 (void) unlink(cpathname);
889 return;
891 /* Now write the true mtime */
892 fseek(fp, 4L, 0);
893 assert(mtime < LONG_MAX);
894 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
895 fflush(fp);
896 fclose(fp);
897 if (Py_VerboseFlag)
898 PySys_WriteStderr("# wrote %s\n", cpathname);
902 /* Load a source module from a given file and return its module
903 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
904 byte-compiled file, use that instead. */
906 static PyObject *
907 load_source_module(char *name, char *pathname, FILE *fp)
909 time_t mtime;
910 FILE *fpc;
911 char buf[MAXPATHLEN+1];
912 char *cpathname;
913 PyCodeObject *co;
914 PyObject *m;
916 mtime = PyOS_GetLastModificationTime(pathname, fp);
917 if (mtime == (time_t)(-1)) {
918 PyErr_Format(PyExc_RuntimeError,
919 "unable to get modification time from '%s'",
920 pathname);
921 return NULL;
923 #if SIZEOF_TIME_T > 4
924 /* Python's .pyc timestamp handling presumes that the timestamp fits
925 in 4 bytes. This will be fine until sometime in the year 2038,
926 when a 4-byte signed time_t will overflow.
928 if (mtime >> 32) {
929 PyErr_SetString(PyExc_OverflowError,
930 "modification time overflows a 4 byte field");
931 return NULL;
933 #endif
934 cpathname = make_compiled_pathname(pathname, buf,
935 (size_t)MAXPATHLEN + 1);
936 if (cpathname != NULL &&
937 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
938 co = read_compiled_module(cpathname, fpc);
939 fclose(fpc);
940 if (co == NULL)
941 return NULL;
942 if (Py_VerboseFlag)
943 PySys_WriteStderr("import %s # precompiled from %s\n",
944 name, cpathname);
945 pathname = cpathname;
947 else {
948 co = parse_source_module(pathname, fp);
949 if (co == NULL)
950 return NULL;
951 if (Py_VerboseFlag)
952 PySys_WriteStderr("import %s # from %s\n",
953 name, pathname);
954 if (cpathname)
955 write_compiled_module(co, cpathname, mtime);
957 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
958 Py_DECREF(co);
960 return m;
964 /* Forward */
965 static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
966 static struct filedescr *find_module(char *, char *, PyObject *,
967 char *, size_t, FILE **, PyObject **);
968 static struct _frozen *find_frozen(char *name);
970 /* Load a package and return its module object WITH INCREMENTED
971 REFERENCE COUNT */
973 static PyObject *
974 load_package(char *name, char *pathname)
976 PyObject *m, *d;
977 PyObject *file = NULL;
978 PyObject *path = NULL;
979 int err;
980 char buf[MAXPATHLEN+1];
981 FILE *fp = NULL;
982 struct filedescr *fdp;
984 m = PyImport_AddModule(name);
985 if (m == NULL)
986 return NULL;
987 if (Py_VerboseFlag)
988 PySys_WriteStderr("import %s # directory %s\n",
989 name, pathname);
990 d = PyModule_GetDict(m);
991 file = PyString_FromString(pathname);
992 if (file == NULL)
993 goto error;
994 path = Py_BuildValue("[O]", file);
995 if (path == NULL)
996 goto error;
997 err = PyDict_SetItemString(d, "__file__", file);
998 if (err == 0)
999 err = PyDict_SetItemString(d, "__path__", path);
1000 if (err != 0)
1001 goto error;
1002 buf[0] = '\0';
1003 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1004 if (fdp == NULL) {
1005 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1006 PyErr_Clear();
1007 Py_INCREF(m);
1009 else
1010 m = NULL;
1011 goto cleanup;
1013 m = load_module(name, fp, buf, fdp->type, NULL);
1014 if (fp != NULL)
1015 fclose(fp);
1016 goto cleanup;
1018 error:
1019 m = NULL;
1020 cleanup:
1021 Py_XDECREF(path);
1022 Py_XDECREF(file);
1023 return m;
1027 /* Helper to test for built-in module */
1029 static int
1030 is_builtin(char *name)
1032 int i;
1033 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1034 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1035 if (PyImport_Inittab[i].initfunc == NULL)
1036 return -1;
1037 else
1038 return 1;
1041 return 0;
1045 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
1046 possibly by fetching it from the path_importer_cache dict. If it
1047 wasn't yet cached, traverse path_hooks until a hook is found
1048 that can handle the path item. Return None if no hook could;
1049 this tells our caller it should fall back to the builtin
1050 import mechanism. Cache the result in path_importer_cache.
1051 Returns a borrowed reference. */
1053 static PyObject *
1054 get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1055 PyObject *p)
1057 PyObject *importer;
1058 Py_ssize_t j, nhooks;
1060 /* These conditions are the caller's responsibility: */
1061 assert(PyList_Check(path_hooks));
1062 assert(PyDict_Check(path_importer_cache));
1064 nhooks = PyList_Size(path_hooks);
1065 if (nhooks < 0)
1066 return NULL; /* Shouldn't happen */
1068 importer = PyDict_GetItem(path_importer_cache, p);
1069 if (importer != NULL)
1070 return importer;
1072 /* set path_importer_cache[p] to None to avoid recursion */
1073 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1074 return NULL;
1076 for (j = 0; j < nhooks; j++) {
1077 PyObject *hook = PyList_GetItem(path_hooks, j);
1078 if (hook == NULL)
1079 return NULL;
1080 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1081 if (importer != NULL)
1082 break;
1084 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1085 return NULL;
1087 PyErr_Clear();
1089 if (importer == NULL) {
1090 importer = PyObject_CallFunctionObjArgs(
1091 (PyObject *)&NullImporterType, p, NULL
1093 if (importer == NULL) {
1094 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1095 PyErr_Clear();
1096 return Py_None;
1100 if (importer != NULL) {
1101 int err = PyDict_SetItem(path_importer_cache, p, importer);
1102 Py_DECREF(importer);
1103 if (err != 0)
1104 return NULL;
1106 return importer;
1109 /* Search the path (default sys.path) for a module. Return the
1110 corresponding filedescr struct, and (via return arguments) the
1111 pathname and an open file. Return NULL if the module is not found. */
1113 #ifdef MS_COREDLL
1114 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
1115 char *, Py_ssize_t);
1116 #endif
1118 static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
1119 static int find_init_module(char *); /* Forward */
1120 static struct filedescr importhookdescr = {"", "", IMP_HOOK};
1122 static struct filedescr *
1123 find_module(char *fullname, char *subname, PyObject *path, char *buf,
1124 size_t buflen, FILE **p_fp, PyObject **p_loader)
1126 Py_ssize_t i, npath;
1127 size_t len, namelen;
1128 struct filedescr *fdp = NULL;
1129 char *filemode;
1130 FILE *fp = NULL;
1131 PyObject *path_hooks, *path_importer_cache;
1132 #ifndef RISCOS
1133 struct stat statbuf;
1134 #endif
1135 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1136 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1137 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1138 char name[MAXPATHLEN+1];
1139 #if defined(PYOS_OS2)
1140 size_t saved_len;
1141 size_t saved_namelen;
1142 char *saved_buf = NULL;
1143 #endif
1144 if (p_loader != NULL)
1145 *p_loader = NULL;
1147 if (strlen(subname) > MAXPATHLEN) {
1148 PyErr_SetString(PyExc_OverflowError,
1149 "module name is too long");
1150 return NULL;
1152 strcpy(name, subname);
1154 /* sys.meta_path import hook */
1155 if (p_loader != NULL) {
1156 PyObject *meta_path;
1158 meta_path = PySys_GetObject("meta_path");
1159 if (meta_path == NULL || !PyList_Check(meta_path)) {
1160 PyErr_SetString(PyExc_ImportError,
1161 "sys.meta_path must be a list of "
1162 "import hooks");
1163 return NULL;
1165 Py_INCREF(meta_path); /* zap guard */
1166 npath = PyList_Size(meta_path);
1167 for (i = 0; i < npath; i++) {
1168 PyObject *loader;
1169 PyObject *hook = PyList_GetItem(meta_path, i);
1170 loader = PyObject_CallMethod(hook, "find_module",
1171 "sO", fullname,
1172 path != NULL ?
1173 path : Py_None);
1174 if (loader == NULL) {
1175 Py_DECREF(meta_path);
1176 return NULL; /* true error */
1178 if (loader != Py_None) {
1179 /* a loader was found */
1180 *p_loader = loader;
1181 Py_DECREF(meta_path);
1182 return &importhookdescr;
1184 Py_DECREF(loader);
1186 Py_DECREF(meta_path);
1189 if (path != NULL && PyString_Check(path)) {
1190 /* The only type of submodule allowed inside a "frozen"
1191 package are other frozen modules or packages. */
1192 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1193 PyErr_SetString(PyExc_ImportError,
1194 "full frozen module name too long");
1195 return NULL;
1197 strcpy(buf, PyString_AsString(path));
1198 strcat(buf, ".");
1199 strcat(buf, name);
1200 strcpy(name, buf);
1201 if (find_frozen(name) != NULL) {
1202 strcpy(buf, name);
1203 return &fd_frozen;
1205 PyErr_Format(PyExc_ImportError,
1206 "No frozen submodule named %.200s", name);
1207 return NULL;
1209 if (path == NULL) {
1210 if (is_builtin(name)) {
1211 strcpy(buf, name);
1212 return &fd_builtin;
1214 if ((find_frozen(name)) != NULL) {
1215 strcpy(buf, name);
1216 return &fd_frozen;
1219 #ifdef MS_COREDLL
1220 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1221 if (fp != NULL) {
1222 *p_fp = fp;
1223 return fdp;
1225 #endif
1226 path = PySys_GetObject("path");
1228 if (path == NULL || !PyList_Check(path)) {
1229 PyErr_SetString(PyExc_ImportError,
1230 "sys.path must be a list of directory names");
1231 return NULL;
1234 path_hooks = PySys_GetObject("path_hooks");
1235 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1236 PyErr_SetString(PyExc_ImportError,
1237 "sys.path_hooks must be a list of "
1238 "import hooks");
1239 return NULL;
1241 path_importer_cache = PySys_GetObject("path_importer_cache");
1242 if (path_importer_cache == NULL ||
1243 !PyDict_Check(path_importer_cache)) {
1244 PyErr_SetString(PyExc_ImportError,
1245 "sys.path_importer_cache must be a dict");
1246 return NULL;
1249 npath = PyList_Size(path);
1250 namelen = strlen(name);
1251 for (i = 0; i < npath; i++) {
1252 PyObject *copy = NULL;
1253 PyObject *v = PyList_GetItem(path, i);
1254 if (!v)
1255 return NULL;
1256 #ifdef Py_USING_UNICODE
1257 if (PyUnicode_Check(v)) {
1258 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1259 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1260 if (copy == NULL)
1261 return NULL;
1262 v = copy;
1264 else
1265 #endif
1266 if (!PyString_Check(v))
1267 continue;
1268 len = PyString_GET_SIZE(v);
1269 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1270 Py_XDECREF(copy);
1271 continue; /* Too long */
1273 strcpy(buf, PyString_AS_STRING(v));
1274 if (strlen(buf) != len) {
1275 Py_XDECREF(copy);
1276 continue; /* v contains '\0' */
1279 /* sys.path_hooks import hook */
1280 if (p_loader != NULL) {
1281 PyObject *importer;
1283 importer = get_path_importer(path_importer_cache,
1284 path_hooks, v);
1285 if (importer == NULL) {
1286 Py_XDECREF(copy);
1287 return NULL;
1289 /* Note: importer is a borrowed reference */
1290 if (importer != Py_None) {
1291 PyObject *loader;
1292 loader = PyObject_CallMethod(importer,
1293 "find_module",
1294 "s", fullname);
1295 Py_XDECREF(copy);
1296 if (loader == NULL)
1297 return NULL; /* error */
1298 if (loader != Py_None) {
1299 /* a loader was found */
1300 *p_loader = loader;
1301 return &importhookdescr;
1303 Py_DECREF(loader);
1304 continue;
1307 /* no hook was found, use builtin import */
1309 if (len > 0 && buf[len-1] != SEP
1310 #ifdef ALTSEP
1311 && buf[len-1] != ALTSEP
1312 #endif
1314 buf[len++] = SEP;
1315 strcpy(buf+len, name);
1316 len += namelen;
1318 /* Check for package import (buf holds a directory name,
1319 and there's an __init__ module in that directory */
1320 #ifdef HAVE_STAT
1321 if (stat(buf, &statbuf) == 0 && /* it exists */
1322 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1323 case_ok(buf, len, namelen, name)) { /* case matches */
1324 if (find_init_module(buf)) { /* and has __init__.py */
1325 Py_XDECREF(copy);
1326 return &fd_package;
1328 else {
1329 char warnstr[MAXPATHLEN+80];
1330 sprintf(warnstr, "Not importing directory "
1331 "'%.*s': missing __init__.py",
1332 MAXPATHLEN, buf);
1333 if (PyErr_Warn(PyExc_ImportWarning,
1334 warnstr)) {
1335 Py_XDECREF(copy);
1336 return NULL;
1340 #else
1341 /* XXX How are you going to test for directories? */
1342 #ifdef RISCOS
1343 if (isdir(buf) &&
1344 case_ok(buf, len, namelen, name)) {
1345 if (find_init_module(buf)) {
1346 Py_XDECREF(copy);
1347 return &fd_package;
1349 else {
1350 char warnstr[MAXPATHLEN+80];
1351 sprintf(warnstr, "Not importing directory "
1352 "'%.*s': missing __init__.py",
1353 MAXPATHLEN, buf);
1354 if (PyErr_Warn(PyExc_ImportWarning,
1355 warnstr)) {
1356 Py_XDECREF(copy);
1357 return NULL;
1360 #endif
1361 #endif
1362 #if defined(PYOS_OS2)
1363 /* take a snapshot of the module spec for restoration
1364 * after the 8 character DLL hackery
1366 saved_buf = strdup(buf);
1367 saved_len = len;
1368 saved_namelen = namelen;
1369 #endif /* PYOS_OS2 */
1370 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1371 #if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
1372 /* OS/2 limits DLLs to 8 character names (w/o
1373 extension)
1374 * so if the name is longer than that and its a
1375 * dynamically loaded module we're going to try,
1376 * truncate the name before trying
1378 if (strlen(subname) > 8) {
1379 /* is this an attempt to load a C extension? */
1380 const struct filedescr *scan;
1381 scan = _PyImport_DynLoadFiletab;
1382 while (scan->suffix != NULL) {
1383 if (!strcmp(scan->suffix, fdp->suffix))
1384 break;
1385 else
1386 scan++;
1388 if (scan->suffix != NULL) {
1389 /* yes, so truncate the name */
1390 namelen = 8;
1391 len -= strlen(subname) - namelen;
1392 buf[len] = '\0';
1395 #endif /* PYOS_OS2 */
1396 strcpy(buf+len, fdp->suffix);
1397 if (Py_VerboseFlag > 1)
1398 PySys_WriteStderr("# trying %s\n", buf);
1399 filemode = fdp->mode;
1400 if (filemode[0] == 'U')
1401 filemode = "r" PY_STDIOTEXTMODE;
1402 fp = fopen(buf, filemode);
1403 if (fp != NULL) {
1404 if (case_ok(buf, len, namelen, name))
1405 break;
1406 else { /* continue search */
1407 fclose(fp);
1408 fp = NULL;
1411 #if defined(PYOS_OS2)
1412 /* restore the saved snapshot */
1413 strcpy(buf, saved_buf);
1414 len = saved_len;
1415 namelen = saved_namelen;
1416 #endif
1418 #if defined(PYOS_OS2)
1419 /* don't need/want the module name snapshot anymore */
1420 if (saved_buf)
1422 free(saved_buf);
1423 saved_buf = NULL;
1425 #endif
1426 Py_XDECREF(copy);
1427 if (fp != NULL)
1428 break;
1430 if (fp == NULL) {
1431 PyErr_Format(PyExc_ImportError,
1432 "No module named %.200s", name);
1433 return NULL;
1435 *p_fp = fp;
1436 return fdp;
1439 /* Helpers for main.c
1440 * Find the source file corresponding to a named module
1442 struct filedescr *
1443 _PyImport_FindModule(const char *name, PyObject *path, char *buf,
1444 size_t buflen, FILE **p_fp, PyObject **p_loader)
1446 return find_module((char *) name, (char *) name, path,
1447 buf, buflen, p_fp, p_loader);
1450 PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1452 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1455 /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
1456 * The arguments here are tricky, best shown by example:
1457 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1458 * ^ ^ ^ ^
1459 * |--------------------- buf ---------------------|
1460 * |------------------- len ------------------|
1461 * |------ name -------|
1462 * |----- namelen -----|
1463 * buf is the full path, but len only counts up to (& exclusive of) the
1464 * extension. name is the module name, also exclusive of extension.
1466 * We've already done a successful stat() or fopen() on buf, so know that
1467 * there's some match, possibly case-insensitive.
1469 * case_ok() is to return 1 if there's a case-sensitive match for
1470 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1471 * exists.
1473 * case_ok() is used to implement case-sensitive import semantics even
1474 * on platforms with case-insensitive filesystems. It's trivial to implement
1475 * for case-sensitive filesystems. It's pretty much a cross-platform
1476 * nightmare for systems with case-insensitive filesystems.
1479 /* First we may need a pile of platform-specific header files; the sequence
1480 * of #if's here should match the sequence in the body of case_ok().
1482 #if defined(MS_WINDOWS)
1483 #include <windows.h>
1485 #elif defined(DJGPP)
1486 #include <dir.h>
1488 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1489 #include <sys/types.h>
1490 #include <dirent.h>
1492 #elif defined(PYOS_OS2)
1493 #define INCL_DOS
1494 #define INCL_DOSERRORS
1495 #define INCL_NOPMAPI
1496 #include <os2.h>
1498 #elif defined(RISCOS)
1499 #include "oslib/osfscontrol.h"
1500 #endif
1502 static int
1503 case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
1505 /* Pick a platform-specific implementation; the sequence of #if's here should
1506 * match the sequence just above.
1509 /* MS_WINDOWS */
1510 #if defined(MS_WINDOWS)
1511 WIN32_FIND_DATA data;
1512 HANDLE h;
1514 if (Py_GETENV("PYTHONCASEOK") != NULL)
1515 return 1;
1517 h = FindFirstFile(buf, &data);
1518 if (h == INVALID_HANDLE_VALUE) {
1519 PyErr_Format(PyExc_NameError,
1520 "Can't find file for module %.100s\n(filename %.300s)",
1521 name, buf);
1522 return 0;
1524 FindClose(h);
1525 return strncmp(data.cFileName, name, namelen) == 0;
1527 /* DJGPP */
1528 #elif defined(DJGPP)
1529 struct ffblk ffblk;
1530 int done;
1532 if (Py_GETENV("PYTHONCASEOK") != NULL)
1533 return 1;
1535 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1536 if (done) {
1537 PyErr_Format(PyExc_NameError,
1538 "Can't find file for module %.100s\n(filename %.300s)",
1539 name, buf);
1540 return 0;
1542 return strncmp(ffblk.ff_name, name, namelen) == 0;
1544 /* new-fangled macintosh (macosx) or Cygwin */
1545 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1546 DIR *dirp;
1547 struct dirent *dp;
1548 char dirname[MAXPATHLEN + 1];
1549 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
1551 if (Py_GETENV("PYTHONCASEOK") != NULL)
1552 return 1;
1554 /* Copy the dir component into dirname; substitute "." if empty */
1555 if (dirlen <= 0) {
1556 dirname[0] = '.';
1557 dirname[1] = '\0';
1559 else {
1560 assert(dirlen <= MAXPATHLEN);
1561 memcpy(dirname, buf, dirlen);
1562 dirname[dirlen] = '\0';
1564 /* Open the directory and search the entries for an exact match. */
1565 dirp = opendir(dirname);
1566 if (dirp) {
1567 char *nameWithExt = buf + len - namelen;
1568 while ((dp = readdir(dirp)) != NULL) {
1569 const int thislen =
1570 #ifdef _DIRENT_HAVE_D_NAMELEN
1571 dp->d_namlen;
1572 #else
1573 strlen(dp->d_name);
1574 #endif
1575 if (thislen >= namelen &&
1576 strcmp(dp->d_name, nameWithExt) == 0) {
1577 (void)closedir(dirp);
1578 return 1; /* Found */
1581 (void)closedir(dirp);
1583 return 0 ; /* Not found */
1585 /* RISC OS */
1586 #elif defined(RISCOS)
1587 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1588 char buf2[MAXPATHLEN+2];
1589 char *nameWithExt = buf+len-namelen;
1590 int canonlen;
1591 os_error *e;
1593 if (Py_GETENV("PYTHONCASEOK") != NULL)
1594 return 1;
1596 /* workaround:
1597 append wildcard, otherwise case of filename wouldn't be touched */
1598 strcpy(buf2, buf);
1599 strcat(buf2, "*");
1601 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1602 canonlen = MAXPATHLEN+1-canonlen;
1603 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1604 return 0;
1605 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1606 return 1; /* match */
1608 return 0;
1610 /* OS/2 */
1611 #elif defined(PYOS_OS2)
1612 HDIR hdir = 1;
1613 ULONG srchcnt = 1;
1614 FILEFINDBUF3 ffbuf;
1615 APIRET rc;
1617 if (getenv("PYTHONCASEOK") != NULL)
1618 return 1;
1620 rc = DosFindFirst(buf,
1621 &hdir,
1622 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1623 &ffbuf, sizeof(ffbuf),
1624 &srchcnt,
1625 FIL_STANDARD);
1626 if (rc != NO_ERROR)
1627 return 0;
1628 return strncmp(ffbuf.achName, name, namelen) == 0;
1630 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1631 #else
1632 return 1;
1634 #endif
1638 #ifdef HAVE_STAT
1639 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1640 static int
1641 find_init_module(char *buf)
1643 const size_t save_len = strlen(buf);
1644 size_t i = save_len;
1645 char *pname; /* pointer to start of __init__ */
1646 struct stat statbuf;
1648 /* For calling case_ok(buf, len, namelen, name):
1649 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1650 * ^ ^ ^ ^
1651 * |--------------------- buf ---------------------|
1652 * |------------------- len ------------------|
1653 * |------ name -------|
1654 * |----- namelen -----|
1656 if (save_len + 13 >= MAXPATHLEN)
1657 return 0;
1658 buf[i++] = SEP;
1659 pname = buf + i;
1660 strcpy(pname, "__init__.py");
1661 if (stat(buf, &statbuf) == 0) {
1662 if (case_ok(buf,
1663 save_len + 9, /* len("/__init__") */
1664 8, /* len("__init__") */
1665 pname)) {
1666 buf[save_len] = '\0';
1667 return 1;
1670 i += strlen(pname);
1671 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1672 if (stat(buf, &statbuf) == 0) {
1673 if (case_ok(buf,
1674 save_len + 9, /* len("/__init__") */
1675 8, /* len("__init__") */
1676 pname)) {
1677 buf[save_len] = '\0';
1678 return 1;
1681 buf[save_len] = '\0';
1682 return 0;
1685 #else
1687 #ifdef RISCOS
1688 static int
1689 find_init_module(buf)
1690 char *buf;
1692 int save_len = strlen(buf);
1693 int i = save_len;
1695 if (save_len + 13 >= MAXPATHLEN)
1696 return 0;
1697 buf[i++] = SEP;
1698 strcpy(buf+i, "__init__/py");
1699 if (isfile(buf)) {
1700 buf[save_len] = '\0';
1701 return 1;
1704 if (Py_OptimizeFlag)
1705 strcpy(buf+i, "o");
1706 else
1707 strcpy(buf+i, "c");
1708 if (isfile(buf)) {
1709 buf[save_len] = '\0';
1710 return 1;
1712 buf[save_len] = '\0';
1713 return 0;
1715 #endif /*RISCOS*/
1717 #endif /* HAVE_STAT */
1720 static int init_builtin(char *); /* Forward */
1722 /* Load an external module using the default search path and return
1723 its module object WITH INCREMENTED REFERENCE COUNT */
1725 static PyObject *
1726 load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
1728 PyObject *modules;
1729 PyObject *m;
1730 int err;
1732 /* First check that there's an open file (if we need one) */
1733 switch (type) {
1734 case PY_SOURCE:
1735 case PY_COMPILED:
1736 if (fp == NULL) {
1737 PyErr_Format(PyExc_ValueError,
1738 "file object required for import (type code %d)",
1739 type);
1740 return NULL;
1744 switch (type) {
1746 case PY_SOURCE:
1747 m = load_source_module(name, buf, fp);
1748 break;
1750 case PY_COMPILED:
1751 m = load_compiled_module(name, buf, fp);
1752 break;
1754 #ifdef HAVE_DYNAMIC_LOADING
1755 case C_EXTENSION:
1756 m = _PyImport_LoadDynamicModule(name, buf, fp);
1757 break;
1758 #endif
1760 case PKG_DIRECTORY:
1761 m = load_package(name, buf);
1762 break;
1764 case C_BUILTIN:
1765 case PY_FROZEN:
1766 if (buf != NULL && buf[0] != '\0')
1767 name = buf;
1768 if (type == C_BUILTIN)
1769 err = init_builtin(name);
1770 else
1771 err = PyImport_ImportFrozenModule(name);
1772 if (err < 0)
1773 return NULL;
1774 if (err == 0) {
1775 PyErr_Format(PyExc_ImportError,
1776 "Purported %s module %.200s not found",
1777 type == C_BUILTIN ?
1778 "builtin" : "frozen",
1779 name);
1780 return NULL;
1782 modules = PyImport_GetModuleDict();
1783 m = PyDict_GetItemString(modules, name);
1784 if (m == NULL) {
1785 PyErr_Format(
1786 PyExc_ImportError,
1787 "%s module %.200s not properly initialized",
1788 type == C_BUILTIN ?
1789 "builtin" : "frozen",
1790 name);
1791 return NULL;
1793 Py_INCREF(m);
1794 break;
1796 case IMP_HOOK: {
1797 if (loader == NULL) {
1798 PyErr_SetString(PyExc_ImportError,
1799 "import hook without loader");
1800 return NULL;
1802 m = PyObject_CallMethod(loader, "load_module", "s", name);
1803 break;
1806 default:
1807 PyErr_Format(PyExc_ImportError,
1808 "Don't know how to import %.200s (type code %d)",
1809 name, type);
1810 m = NULL;
1814 return m;
1818 /* Initialize a built-in module.
1819 Return 1 for success, 0 if the module is not found, and -1 with
1820 an exception set if the initialization failed. */
1822 static int
1823 init_builtin(char *name)
1825 struct _inittab *p;
1827 if (_PyImport_FindExtension(name, name) != NULL)
1828 return 1;
1830 for (p = PyImport_Inittab; p->name != NULL; p++) {
1831 if (strcmp(name, p->name) == 0) {
1832 if (p->initfunc == NULL) {
1833 PyErr_Format(PyExc_ImportError,
1834 "Cannot re-init internal module %.200s",
1835 name);
1836 return -1;
1838 if (Py_VerboseFlag)
1839 PySys_WriteStderr("import %s # builtin\n", name);
1840 (*p->initfunc)();
1841 if (PyErr_Occurred())
1842 return -1;
1843 if (_PyImport_FixupExtension(name, name) == NULL)
1844 return -1;
1845 return 1;
1848 return 0;
1852 /* Frozen modules */
1854 static struct _frozen *
1855 find_frozen(char *name)
1857 struct _frozen *p;
1859 for (p = PyImport_FrozenModules; ; p++) {
1860 if (p->name == NULL)
1861 return NULL;
1862 if (strcmp(p->name, name) == 0)
1863 break;
1865 return p;
1868 static PyObject *
1869 get_frozen_object(char *name)
1871 struct _frozen *p = find_frozen(name);
1872 int size;
1874 if (p == NULL) {
1875 PyErr_Format(PyExc_ImportError,
1876 "No such frozen object named %.200s",
1877 name);
1878 return NULL;
1880 if (p->code == NULL) {
1881 PyErr_Format(PyExc_ImportError,
1882 "Excluded frozen object named %.200s",
1883 name);
1884 return NULL;
1886 size = p->size;
1887 if (size < 0)
1888 size = -size;
1889 return PyMarshal_ReadObjectFromString((char *)p->code, size);
1892 /* Initialize a frozen module.
1893 Return 1 for succes, 0 if the module is not found, and -1 with
1894 an exception set if the initialization failed.
1895 This function is also used from frozenmain.c */
1898 PyImport_ImportFrozenModule(char *name)
1900 struct _frozen *p = find_frozen(name);
1901 PyObject *co;
1902 PyObject *m;
1903 int ispackage;
1904 int size;
1906 if (p == NULL)
1907 return 0;
1908 if (p->code == NULL) {
1909 PyErr_Format(PyExc_ImportError,
1910 "Excluded frozen object named %.200s",
1911 name);
1912 return -1;
1914 size = p->size;
1915 ispackage = (size < 0);
1916 if (ispackage)
1917 size = -size;
1918 if (Py_VerboseFlag)
1919 PySys_WriteStderr("import %s # frozen%s\n",
1920 name, ispackage ? " package" : "");
1921 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1922 if (co == NULL)
1923 return -1;
1924 if (!PyCode_Check(co)) {
1925 PyErr_Format(PyExc_TypeError,
1926 "frozen object %.200s is not a code object",
1927 name);
1928 goto err_return;
1930 if (ispackage) {
1931 /* Set __path__ to the package name */
1932 PyObject *d, *s;
1933 int err;
1934 m = PyImport_AddModule(name);
1935 if (m == NULL)
1936 goto err_return;
1937 d = PyModule_GetDict(m);
1938 s = PyString_InternFromString(name);
1939 if (s == NULL)
1940 goto err_return;
1941 err = PyDict_SetItemString(d, "__path__", s);
1942 Py_DECREF(s);
1943 if (err != 0)
1944 goto err_return;
1946 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
1947 if (m == NULL)
1948 goto err_return;
1949 Py_DECREF(co);
1950 Py_DECREF(m);
1951 return 1;
1952 err_return:
1953 Py_DECREF(co);
1954 return -1;
1958 /* Import a module, either built-in, frozen, or external, and return
1959 its module object WITH INCREMENTED REFERENCE COUNT */
1961 PyObject *
1962 PyImport_ImportModule(const char *name)
1964 PyObject *pname;
1965 PyObject *result;
1967 pname = PyString_FromString(name);
1968 if (pname == NULL)
1969 return NULL;
1970 result = PyImport_Import(pname);
1971 Py_DECREF(pname);
1972 return result;
1975 /* Forward declarations for helper routines */
1976 static PyObject *get_parent(PyObject *globals, char *buf,
1977 Py_ssize_t *p_buflen, int level);
1978 static PyObject *load_next(PyObject *mod, PyObject *altmod,
1979 char **p_name, char *buf, Py_ssize_t *p_buflen);
1980 static int mark_miss(char *name);
1981 static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1982 char *buf, Py_ssize_t buflen, int recursive);
1983 static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
1985 /* The Magnum Opus of dotted-name import :-) */
1987 static PyObject *
1988 import_module_level(char *name, PyObject *globals, PyObject *locals,
1989 PyObject *fromlist, int level)
1991 char buf[MAXPATHLEN+1];
1992 Py_ssize_t buflen = 0;
1993 PyObject *parent, *head, *next, *tail;
1995 parent = get_parent(globals, buf, &buflen, level);
1996 if (parent == NULL)
1997 return NULL;
1999 head = load_next(parent, Py_None, &name, buf, &buflen);
2000 if (head == NULL)
2001 return NULL;
2003 tail = head;
2004 Py_INCREF(tail);
2005 while (name) {
2006 next = load_next(tail, tail, &name, buf, &buflen);
2007 Py_DECREF(tail);
2008 if (next == NULL) {
2009 Py_DECREF(head);
2010 return NULL;
2012 tail = next;
2014 if (tail == Py_None) {
2015 /* If tail is Py_None, both get_parent and load_next found
2016 an empty module name: someone called __import__("") or
2017 doctored faulty bytecode */
2018 Py_DECREF(tail);
2019 Py_DECREF(head);
2020 PyErr_SetString(PyExc_ValueError,
2021 "Empty module name");
2022 return NULL;
2025 if (fromlist != NULL) {
2026 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2027 fromlist = NULL;
2030 if (fromlist == NULL) {
2031 Py_DECREF(tail);
2032 return head;
2035 Py_DECREF(head);
2036 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2037 Py_DECREF(tail);
2038 return NULL;
2041 return tail;
2044 /* For DLL compatibility */
2045 #undef PyImport_ImportModuleEx
2046 PyObject *
2047 PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
2048 PyObject *fromlist)
2050 PyObject *result;
2051 lock_import();
2052 result = import_module_level(name, globals, locals, fromlist, -1);
2053 if (unlock_import() < 0) {
2054 Py_XDECREF(result);
2055 PyErr_SetString(PyExc_RuntimeError,
2056 "not holding the import lock");
2057 return NULL;
2059 return result;
2061 #define PyImport_ImportModuleEx(n, g, l, f) \
2062 PyImport_ImportModuleLevel(n, g, l, f, -1);
2064 PyObject *
2065 PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2066 PyObject *fromlist, int level)
2068 PyObject *result;
2069 lock_import();
2070 result = import_module_level(name, globals, locals, fromlist, level);
2071 if (unlock_import() < 0) {
2072 Py_XDECREF(result);
2073 PyErr_SetString(PyExc_RuntimeError,
2074 "not holding the import lock");
2075 return NULL;
2077 return result;
2080 /* Return the package that an import is being performed in. If globals comes
2081 from the module foo.bar.bat (not itself a package), this returns the
2082 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
2083 the package's entry in sys.modules is returned, as a borrowed reference.
2085 The *name* of the returned package is returned in buf, with the length of
2086 the name in *p_buflen.
2088 If globals doesn't come from a package or a module in a package, or a
2089 corresponding entry is not found in sys.modules, Py_None is returned.
2091 static PyObject *
2092 get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
2094 static PyObject *namestr = NULL;
2095 static PyObject *pathstr = NULL;
2096 PyObject *modname, *modpath, *modules, *parent;
2098 if (globals == NULL || !PyDict_Check(globals) || !level)
2099 return Py_None;
2101 if (namestr == NULL) {
2102 namestr = PyString_InternFromString("__name__");
2103 if (namestr == NULL)
2104 return NULL;
2106 if (pathstr == NULL) {
2107 pathstr = PyString_InternFromString("__path__");
2108 if (pathstr == NULL)
2109 return NULL;
2112 *buf = '\0';
2113 *p_buflen = 0;
2114 modname = PyDict_GetItem(globals, namestr);
2115 if (modname == NULL || !PyString_Check(modname))
2116 return Py_None;
2118 modpath = PyDict_GetItem(globals, pathstr);
2119 if (modpath != NULL) {
2120 Py_ssize_t len = PyString_GET_SIZE(modname);
2121 if (len > MAXPATHLEN) {
2122 PyErr_SetString(PyExc_ValueError,
2123 "Module name too long");
2124 return NULL;
2126 strcpy(buf, PyString_AS_STRING(modname));
2128 else {
2129 char *start = PyString_AS_STRING(modname);
2130 char *lastdot = strrchr(start, '.');
2131 size_t len;
2132 if (lastdot == NULL && level > 0) {
2133 PyErr_SetString(PyExc_ValueError,
2134 "Attempted relative import in non-package");
2135 return NULL;
2137 if (lastdot == NULL)
2138 return Py_None;
2139 len = lastdot - start;
2140 if (len >= MAXPATHLEN) {
2141 PyErr_SetString(PyExc_ValueError,
2142 "Module name too long");
2143 return NULL;
2145 strncpy(buf, start, len);
2146 buf[len] = '\0';
2149 while (--level > 0) {
2150 char *dot = strrchr(buf, '.');
2151 if (dot == NULL) {
2152 PyErr_SetString(PyExc_ValueError,
2153 "Attempted relative import beyond "
2154 "toplevel package");
2155 return NULL;
2157 *dot = '\0';
2159 *p_buflen = strlen(buf);
2161 modules = PyImport_GetModuleDict();
2162 parent = PyDict_GetItemString(modules, buf);
2163 if (parent == NULL)
2164 PyErr_Format(PyExc_SystemError,
2165 "Parent module '%.200s' not loaded", buf);
2166 return parent;
2167 /* We expect, but can't guarantee, if parent != None, that:
2168 - parent.__name__ == buf
2169 - parent.__dict__ is globals
2170 If this is violated... Who cares? */
2173 /* altmod is either None or same as mod */
2174 static PyObject *
2175 load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
2176 Py_ssize_t *p_buflen)
2178 char *name = *p_name;
2179 char *dot = strchr(name, '.');
2180 size_t len;
2181 char *p;
2182 PyObject *result;
2184 if (strlen(name) == 0) {
2185 /* completely empty module name should only happen in
2186 'from . import' (or '__import__("")')*/
2187 Py_INCREF(mod);
2188 *p_name = NULL;
2189 return mod;
2192 if (dot == NULL) {
2193 *p_name = NULL;
2194 len = strlen(name);
2196 else {
2197 *p_name = dot+1;
2198 len = dot-name;
2200 if (len == 0) {
2201 PyErr_SetString(PyExc_ValueError,
2202 "Empty module name");
2203 return NULL;
2206 p = buf + *p_buflen;
2207 if (p != buf)
2208 *p++ = '.';
2209 if (p+len-buf >= MAXPATHLEN) {
2210 PyErr_SetString(PyExc_ValueError,
2211 "Module name too long");
2212 return NULL;
2214 strncpy(p, name, len);
2215 p[len] = '\0';
2216 *p_buflen = p+len-buf;
2218 result = import_submodule(mod, p, buf);
2219 if (result == Py_None && altmod != mod) {
2220 Py_DECREF(result);
2221 /* Here, altmod must be None and mod must not be None */
2222 result = import_submodule(altmod, p, p);
2223 if (result != NULL && result != Py_None) {
2224 if (mark_miss(buf) != 0) {
2225 Py_DECREF(result);
2226 return NULL;
2228 strncpy(buf, name, len);
2229 buf[len] = '\0';
2230 *p_buflen = len;
2233 if (result == NULL)
2234 return NULL;
2236 if (result == Py_None) {
2237 Py_DECREF(result);
2238 PyErr_Format(PyExc_ImportError,
2239 "No module named %.200s", name);
2240 return NULL;
2243 return result;
2246 static int
2247 mark_miss(char *name)
2249 PyObject *modules = PyImport_GetModuleDict();
2250 return PyDict_SetItemString(modules, name, Py_None);
2253 static int
2254 ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
2255 int recursive)
2257 int i;
2259 if (!PyObject_HasAttrString(mod, "__path__"))
2260 return 1;
2262 for (i = 0; ; i++) {
2263 PyObject *item = PySequence_GetItem(fromlist, i);
2264 int hasit;
2265 if (item == NULL) {
2266 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2267 PyErr_Clear();
2268 return 1;
2270 return 0;
2272 if (!PyString_Check(item)) {
2273 PyErr_SetString(PyExc_TypeError,
2274 "Item in ``from list'' not a string");
2275 Py_DECREF(item);
2276 return 0;
2278 if (PyString_AS_STRING(item)[0] == '*') {
2279 PyObject *all;
2280 Py_DECREF(item);
2281 /* See if the package defines __all__ */
2282 if (recursive)
2283 continue; /* Avoid endless recursion */
2284 all = PyObject_GetAttrString(mod, "__all__");
2285 if (all == NULL)
2286 PyErr_Clear();
2287 else {
2288 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2289 Py_DECREF(all);
2290 if (!ret)
2291 return 0;
2293 continue;
2295 hasit = PyObject_HasAttr(mod, item);
2296 if (!hasit) {
2297 char *subname = PyString_AS_STRING(item);
2298 PyObject *submod;
2299 char *p;
2300 if (buflen + strlen(subname) >= MAXPATHLEN) {
2301 PyErr_SetString(PyExc_ValueError,
2302 "Module name too long");
2303 Py_DECREF(item);
2304 return 0;
2306 p = buf + buflen;
2307 *p++ = '.';
2308 strcpy(p, subname);
2309 submod = import_submodule(mod, subname, buf);
2310 Py_XDECREF(submod);
2311 if (submod == NULL) {
2312 Py_DECREF(item);
2313 return 0;
2316 Py_DECREF(item);
2319 /* NOTREACHED */
2322 static int
2323 add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2324 PyObject *modules)
2326 if (mod == Py_None)
2327 return 1;
2328 /* Irrespective of the success of this load, make a
2329 reference to it in the parent package module. A copy gets
2330 saved in the modules dictionary under the full name, so get a
2331 reference from there, if need be. (The exception is when the
2332 load failed with a SyntaxError -- then there's no trace in
2333 sys.modules. In that case, of course, do nothing extra.) */
2334 if (submod == NULL) {
2335 submod = PyDict_GetItemString(modules, fullname);
2336 if (submod == NULL)
2337 return 1;
2339 if (PyModule_Check(mod)) {
2340 /* We can't use setattr here since it can give a
2341 * spurious warning if the submodule name shadows a
2342 * builtin name */
2343 PyObject *dict = PyModule_GetDict(mod);
2344 if (!dict)
2345 return 0;
2346 if (PyDict_SetItemString(dict, subname, submod) < 0)
2347 return 0;
2349 else {
2350 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2351 return 0;
2353 return 1;
2356 static PyObject *
2357 import_submodule(PyObject *mod, char *subname, char *fullname)
2359 PyObject *modules = PyImport_GetModuleDict();
2360 PyObject *m = NULL;
2362 /* Require:
2363 if mod == None: subname == fullname
2364 else: mod.__name__ + "." + subname == fullname
2367 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2368 Py_INCREF(m);
2370 else {
2371 PyObject *path, *loader = NULL;
2372 char buf[MAXPATHLEN+1];
2373 struct filedescr *fdp;
2374 FILE *fp = NULL;
2376 if (mod == Py_None)
2377 path = NULL;
2378 else {
2379 path = PyObject_GetAttrString(mod, "__path__");
2380 if (path == NULL) {
2381 PyErr_Clear();
2382 Py_INCREF(Py_None);
2383 return Py_None;
2387 buf[0] = '\0';
2388 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2389 &fp, &loader);
2390 Py_XDECREF(path);
2391 if (fdp == NULL) {
2392 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2393 return NULL;
2394 PyErr_Clear();
2395 Py_INCREF(Py_None);
2396 return Py_None;
2398 m = load_module(fullname, fp, buf, fdp->type, loader);
2399 Py_XDECREF(loader);
2400 if (fp)
2401 fclose(fp);
2402 if (!add_submodule(mod, m, fullname, subname, modules)) {
2403 Py_XDECREF(m);
2404 m = NULL;
2408 return m;
2412 /* Re-import a module of any kind and return its module object, WITH
2413 INCREMENTED REFERENCE COUNT */
2415 PyObject *
2416 PyImport_ReloadModule(PyObject *m)
2418 PyInterpreterState *interp = PyThreadState_Get()->interp;
2419 PyObject *modules_reloading = interp->modules_reloading;
2420 PyObject *modules = PyImport_GetModuleDict();
2421 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2422 char *name, *subname;
2423 char buf[MAXPATHLEN+1];
2424 struct filedescr *fdp;
2425 FILE *fp = NULL;
2426 PyObject *newm;
2428 if (modules_reloading == NULL) {
2429 Py_FatalError("PyImport_ReloadModule: "
2430 "no modules_reloading dictionary!");
2431 return NULL;
2434 if (m == NULL || !PyModule_Check(m)) {
2435 PyErr_SetString(PyExc_TypeError,
2436 "reload() argument must be module");
2437 return NULL;
2439 name = PyModule_GetName(m);
2440 if (name == NULL)
2441 return NULL;
2442 if (m != PyDict_GetItemString(modules, name)) {
2443 PyErr_Format(PyExc_ImportError,
2444 "reload(): module %.200s not in sys.modules",
2445 name);
2446 return NULL;
2448 existing_m = PyDict_GetItemString(modules_reloading, name);
2449 if (existing_m != NULL) {
2450 /* Due to a recursive reload, this module is already
2451 being reloaded. */
2452 Py_INCREF(existing_m);
2453 return existing_m;
2455 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2456 return NULL;
2458 subname = strrchr(name, '.');
2459 if (subname == NULL)
2460 subname = name;
2461 else {
2462 PyObject *parentname, *parent;
2463 parentname = PyString_FromStringAndSize(name, (subname-name));
2464 if (parentname == NULL) {
2465 imp_modules_reloading_clear();
2466 return NULL;
2468 parent = PyDict_GetItem(modules, parentname);
2469 if (parent == NULL) {
2470 PyErr_Format(PyExc_ImportError,
2471 "reload(): parent %.200s not in sys.modules",
2472 PyString_AS_STRING(parentname));
2473 Py_DECREF(parentname);
2474 imp_modules_reloading_clear();
2475 return NULL;
2477 Py_DECREF(parentname);
2478 subname++;
2479 path = PyObject_GetAttrString(parent, "__path__");
2480 if (path == NULL)
2481 PyErr_Clear();
2483 buf[0] = '\0';
2484 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2485 Py_XDECREF(path);
2487 if (fdp == NULL) {
2488 Py_XDECREF(loader);
2489 imp_modules_reloading_clear();
2490 return NULL;
2493 newm = load_module(name, fp, buf, fdp->type, loader);
2494 Py_XDECREF(loader);
2496 if (fp)
2497 fclose(fp);
2498 if (newm == NULL) {
2499 /* load_module probably removed name from modules because of
2500 * the error. Put back the original module object. We're
2501 * going to return NULL in this case regardless of whether
2502 * replacing name succeeds, so the return value is ignored.
2504 PyDict_SetItemString(modules, name, m);
2506 imp_modules_reloading_clear();
2507 return newm;
2511 /* Higher-level import emulator which emulates the "import" statement
2512 more accurately -- it invokes the __import__() function from the
2513 builtins of the current globals. This means that the import is
2514 done using whatever import hooks are installed in the current
2515 environment, e.g. by "rexec".
2516 A dummy list ["__doc__"] is passed as the 4th argument so that
2517 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2518 will return <module "gencache"> instead of <module "win32com">. */
2520 PyObject *
2521 PyImport_Import(PyObject *module_name)
2523 static PyObject *silly_list = NULL;
2524 static PyObject *builtins_str = NULL;
2525 static PyObject *import_str = NULL;
2526 PyObject *globals = NULL;
2527 PyObject *import = NULL;
2528 PyObject *builtins = NULL;
2529 PyObject *r = NULL;
2531 /* Initialize constant string objects */
2532 if (silly_list == NULL) {
2533 import_str = PyString_InternFromString("__import__");
2534 if (import_str == NULL)
2535 return NULL;
2536 builtins_str = PyString_InternFromString("__builtins__");
2537 if (builtins_str == NULL)
2538 return NULL;
2539 silly_list = Py_BuildValue("[s]", "__doc__");
2540 if (silly_list == NULL)
2541 return NULL;
2544 /* Get the builtins from current globals */
2545 globals = PyEval_GetGlobals();
2546 if (globals != NULL) {
2547 Py_INCREF(globals);
2548 builtins = PyObject_GetItem(globals, builtins_str);
2549 if (builtins == NULL)
2550 goto err;
2552 else {
2553 /* No globals -- use standard builtins, and fake globals */
2554 PyErr_Clear();
2556 builtins = PyImport_ImportModuleLevel("__builtin__",
2557 NULL, NULL, NULL, 0);
2558 if (builtins == NULL)
2559 return NULL;
2560 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2561 if (globals == NULL)
2562 goto err;
2565 /* Get the __import__ function from the builtins */
2566 if (PyDict_Check(builtins)) {
2567 import = PyObject_GetItem(builtins, import_str);
2568 if (import == NULL)
2569 PyErr_SetObject(PyExc_KeyError, import_str);
2571 else
2572 import = PyObject_GetAttr(builtins, import_str);
2573 if (import == NULL)
2574 goto err;
2576 /* Call the __import__ function with the proper argument list */
2577 r = PyObject_CallFunctionObjArgs(import, module_name, globals,
2578 globals, silly_list, NULL);
2580 err:
2581 Py_XDECREF(globals);
2582 Py_XDECREF(builtins);
2583 Py_XDECREF(import);
2585 return r;
2589 /* Module 'imp' provides Python access to the primitives used for
2590 importing modules.
2593 static PyObject *
2594 imp_get_magic(PyObject *self, PyObject *noargs)
2596 char buf[4];
2598 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2599 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2600 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2601 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
2603 return PyString_FromStringAndSize(buf, 4);
2606 static PyObject *
2607 imp_get_suffixes(PyObject *self, PyObject *noargs)
2609 PyObject *list;
2610 struct filedescr *fdp;
2612 list = PyList_New(0);
2613 if (list == NULL)
2614 return NULL;
2615 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2616 PyObject *item = Py_BuildValue("ssi",
2617 fdp->suffix, fdp->mode, fdp->type);
2618 if (item == NULL) {
2619 Py_DECREF(list);
2620 return NULL;
2622 if (PyList_Append(list, item) < 0) {
2623 Py_DECREF(list);
2624 Py_DECREF(item);
2625 return NULL;
2627 Py_DECREF(item);
2629 return list;
2632 static PyObject *
2633 call_find_module(char *name, PyObject *path)
2635 extern int fclose(FILE *);
2636 PyObject *fob, *ret;
2637 struct filedescr *fdp;
2638 char pathname[MAXPATHLEN+1];
2639 FILE *fp = NULL;
2641 pathname[0] = '\0';
2642 if (path == Py_None)
2643 path = NULL;
2644 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
2645 if (fdp == NULL)
2646 return NULL;
2647 if (fp != NULL) {
2648 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2649 if (fob == NULL) {
2650 fclose(fp);
2651 return NULL;
2654 else {
2655 fob = Py_None;
2656 Py_INCREF(fob);
2658 ret = Py_BuildValue("Os(ssi)",
2659 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
2660 Py_DECREF(fob);
2661 return ret;
2664 static PyObject *
2665 imp_find_module(PyObject *self, PyObject *args)
2667 char *name;
2668 PyObject *path = NULL;
2669 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
2670 return NULL;
2671 return call_find_module(name, path);
2674 static PyObject *
2675 imp_init_builtin(PyObject *self, PyObject *args)
2677 char *name;
2678 int ret;
2679 PyObject *m;
2680 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
2681 return NULL;
2682 ret = init_builtin(name);
2683 if (ret < 0)
2684 return NULL;
2685 if (ret == 0) {
2686 Py_INCREF(Py_None);
2687 return Py_None;
2689 m = PyImport_AddModule(name);
2690 Py_XINCREF(m);
2691 return m;
2694 static PyObject *
2695 imp_init_frozen(PyObject *self, PyObject *args)
2697 char *name;
2698 int ret;
2699 PyObject *m;
2700 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
2701 return NULL;
2702 ret = PyImport_ImportFrozenModule(name);
2703 if (ret < 0)
2704 return NULL;
2705 if (ret == 0) {
2706 Py_INCREF(Py_None);
2707 return Py_None;
2709 m = PyImport_AddModule(name);
2710 Py_XINCREF(m);
2711 return m;
2714 static PyObject *
2715 imp_get_frozen_object(PyObject *self, PyObject *args)
2717 char *name;
2719 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2720 return NULL;
2721 return get_frozen_object(name);
2724 static PyObject *
2725 imp_is_builtin(PyObject *self, PyObject *args)
2727 char *name;
2728 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2729 return NULL;
2730 return PyInt_FromLong(is_builtin(name));
2733 static PyObject *
2734 imp_is_frozen(PyObject *self, PyObject *args)
2736 char *name;
2737 struct _frozen *p;
2738 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
2739 return NULL;
2740 p = find_frozen(name);
2741 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
2744 static FILE *
2745 get_file(char *pathname, PyObject *fob, char *mode)
2747 FILE *fp;
2748 if (fob == NULL) {
2749 if (mode[0] == 'U')
2750 mode = "r" PY_STDIOTEXTMODE;
2751 fp = fopen(pathname, mode);
2752 if (fp == NULL)
2753 PyErr_SetFromErrno(PyExc_IOError);
2755 else {
2756 fp = PyFile_AsFile(fob);
2757 if (fp == NULL)
2758 PyErr_SetString(PyExc_ValueError,
2759 "bad/closed file object");
2761 return fp;
2764 static PyObject *
2765 imp_load_compiled(PyObject *self, PyObject *args)
2767 char *name;
2768 char *pathname;
2769 PyObject *fob = NULL;
2770 PyObject *m;
2771 FILE *fp;
2772 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
2773 &PyFile_Type, &fob))
2774 return NULL;
2775 fp = get_file(pathname, fob, "rb");
2776 if (fp == NULL)
2777 return NULL;
2778 m = load_compiled_module(name, pathname, fp);
2779 if (fob == NULL)
2780 fclose(fp);
2781 return m;
2784 #ifdef HAVE_DYNAMIC_LOADING
2786 static PyObject *
2787 imp_load_dynamic(PyObject *self, PyObject *args)
2789 char *name;
2790 char *pathname;
2791 PyObject *fob = NULL;
2792 PyObject *m;
2793 FILE *fp = NULL;
2794 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
2795 &PyFile_Type, &fob))
2796 return NULL;
2797 if (fob) {
2798 fp = get_file(pathname, fob, "r");
2799 if (fp == NULL)
2800 return NULL;
2802 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2803 return m;
2806 #endif /* HAVE_DYNAMIC_LOADING */
2808 static PyObject *
2809 imp_load_source(PyObject *self, PyObject *args)
2811 char *name;
2812 char *pathname;
2813 PyObject *fob = NULL;
2814 PyObject *m;
2815 FILE *fp;
2816 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
2817 &PyFile_Type, &fob))
2818 return NULL;
2819 fp = get_file(pathname, fob, "r");
2820 if (fp == NULL)
2821 return NULL;
2822 m = load_source_module(name, pathname, fp);
2823 if (fob == NULL)
2824 fclose(fp);
2825 return m;
2828 static PyObject *
2829 imp_load_module(PyObject *self, PyObject *args)
2831 char *name;
2832 PyObject *fob;
2833 char *pathname;
2834 char *suffix; /* Unused */
2835 char *mode;
2836 int type;
2837 FILE *fp;
2839 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
2840 &name, &fob, &pathname,
2841 &suffix, &mode, &type))
2842 return NULL;
2843 if (*mode) {
2844 /* Mode must start with 'r' or 'U' and must not contain '+'.
2845 Implicit in this test is the assumption that the mode
2846 may contain other modifiers like 'b' or 't'. */
2848 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
2849 PyErr_Format(PyExc_ValueError,
2850 "invalid file open mode %.200s", mode);
2851 return NULL;
2854 if (fob == Py_None)
2855 fp = NULL;
2856 else {
2857 if (!PyFile_Check(fob)) {
2858 PyErr_SetString(PyExc_ValueError,
2859 "load_module arg#2 should be a file or None");
2860 return NULL;
2862 fp = get_file(pathname, fob, mode);
2863 if (fp == NULL)
2864 return NULL;
2866 return load_module(name, fp, pathname, type, NULL);
2869 static PyObject *
2870 imp_load_package(PyObject *self, PyObject *args)
2872 char *name;
2873 char *pathname;
2874 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
2875 return NULL;
2876 return load_package(name, pathname);
2879 static PyObject *
2880 imp_new_module(PyObject *self, PyObject *args)
2882 char *name;
2883 if (!PyArg_ParseTuple(args, "s:new_module", &name))
2884 return NULL;
2885 return PyModule_New(name);
2888 /* Doc strings */
2890 PyDoc_STRVAR(doc_imp,
2891 "This module provides the components needed to build your own\n\
2892 __import__ function. Undocumented functions are obsolete.");
2894 PyDoc_STRVAR(doc_find_module,
2895 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2896 Search for a module. If path is omitted or None, search for a\n\
2897 built-in, frozen or special module and continue search in sys.path.\n\
2898 The module name cannot contain '.'; to search for a submodule of a\n\
2899 package, pass the submodule name and the package's __path__.");
2901 PyDoc_STRVAR(doc_load_module,
2902 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2903 Load a module, given information returned by find_module().\n\
2904 The module name must include the full package name, if any.");
2906 PyDoc_STRVAR(doc_get_magic,
2907 "get_magic() -> string\n\
2908 Return the magic number for .pyc or .pyo files.");
2910 PyDoc_STRVAR(doc_get_suffixes,
2911 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2912 Return a list of (suffix, mode, type) tuples describing the files\n\
2913 that find_module() looks for.");
2915 PyDoc_STRVAR(doc_new_module,
2916 "new_module(name) -> module\n\
2917 Create a new module. Do not enter it in sys.modules.\n\
2918 The module name must include the full package name, if any.");
2920 PyDoc_STRVAR(doc_lock_held,
2921 "lock_held() -> boolean\n\
2922 Return True if the import lock is currently held, else False.\n\
2923 On platforms without threads, return False.");
2925 PyDoc_STRVAR(doc_acquire_lock,
2926 "acquire_lock() -> None\n\
2927 Acquires the interpreter's import lock for the current thread.\n\
2928 This lock should be used by import hooks to ensure thread-safety\n\
2929 when importing modules.\n\
2930 On platforms without threads, this function does nothing.");
2932 PyDoc_STRVAR(doc_release_lock,
2933 "release_lock() -> None\n\
2934 Release the interpreter's import lock.\n\
2935 On platforms without threads, this function does nothing.");
2937 static PyMethodDef imp_methods[] = {
2938 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2939 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2940 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2941 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2942 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2943 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2944 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2945 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
2946 /* The rest are obsolete */
2947 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2948 {"init_builtin", imp_init_builtin, METH_VARARGS},
2949 {"init_frozen", imp_init_frozen, METH_VARARGS},
2950 {"is_builtin", imp_is_builtin, METH_VARARGS},
2951 {"is_frozen", imp_is_frozen, METH_VARARGS},
2952 {"load_compiled", imp_load_compiled, METH_VARARGS},
2953 #ifdef HAVE_DYNAMIC_LOADING
2954 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
2955 #endif
2956 {"load_package", imp_load_package, METH_VARARGS},
2957 {"load_source", imp_load_source, METH_VARARGS},
2958 {NULL, NULL} /* sentinel */
2961 static int
2962 setint(PyObject *d, char *name, int value)
2964 PyObject *v;
2965 int err;
2967 v = PyInt_FromLong((long)value);
2968 err = PyDict_SetItemString(d, name, v);
2969 Py_XDECREF(v);
2970 return err;
2973 typedef struct {
2974 PyObject_HEAD
2975 } NullImporter;
2977 static int
2978 NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
2980 char *path;
2982 if (!_PyArg_NoKeywords("NullImporter()", kwds))
2983 return -1;
2985 if (!PyArg_ParseTuple(args, "s:NullImporter",
2986 &path))
2987 return -1;
2989 if (strlen(path) == 0) {
2990 PyErr_SetString(PyExc_ImportError, "empty pathname");
2991 return -1;
2992 } else {
2993 #ifndef RISCOS
2994 struct stat statbuf;
2995 int rv;
2997 rv = stat(path, &statbuf);
2998 if (rv == 0) {
2999 /* it exists */
3000 if (S_ISDIR(statbuf.st_mode)) {
3001 /* it's a directory */
3002 PyErr_SetString(PyExc_ImportError,
3003 "existing directory");
3004 return -1;
3007 #else
3008 if (object_exists(path)) {
3009 /* it exists */
3010 if (isdir(path)) {
3011 /* it's a directory */
3012 PyErr_SetString(PyExc_ImportError,
3013 "existing directory");
3014 return -1;
3017 #endif
3019 return 0;
3022 static PyObject *
3023 NullImporter_find_module(NullImporter *self, PyObject *args)
3025 Py_RETURN_NONE;
3028 static PyMethodDef NullImporter_methods[] = {
3029 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3030 "Always return None"
3032 {NULL} /* Sentinel */
3036 static PyTypeObject NullImporterType = {
3037 PyVarObject_HEAD_INIT(NULL, 0)
3038 "imp.NullImporter", /*tp_name*/
3039 sizeof(NullImporter), /*tp_basicsize*/
3040 0, /*tp_itemsize*/
3041 0, /*tp_dealloc*/
3042 0, /*tp_print*/
3043 0, /*tp_getattr*/
3044 0, /*tp_setattr*/
3045 0, /*tp_compare*/
3046 0, /*tp_repr*/
3047 0, /*tp_as_number*/
3048 0, /*tp_as_sequence*/
3049 0, /*tp_as_mapping*/
3050 0, /*tp_hash */
3051 0, /*tp_call*/
3052 0, /*tp_str*/
3053 0, /*tp_getattro*/
3054 0, /*tp_setattro*/
3055 0, /*tp_as_buffer*/
3056 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3057 "Null importer object", /* tp_doc */
3058 0, /* tp_traverse */
3059 0, /* tp_clear */
3060 0, /* tp_richcompare */
3061 0, /* tp_weaklistoffset */
3062 0, /* tp_iter */
3063 0, /* tp_iternext */
3064 NullImporter_methods, /* tp_methods */
3065 0, /* tp_members */
3066 0, /* tp_getset */
3067 0, /* tp_base */
3068 0, /* tp_dict */
3069 0, /* tp_descr_get */
3070 0, /* tp_descr_set */
3071 0, /* tp_dictoffset */
3072 (initproc)NullImporter_init, /* tp_init */
3073 0, /* tp_alloc */
3074 PyType_GenericNew /* tp_new */
3078 PyMODINIT_FUNC
3079 initimp(void)
3081 PyObject *m, *d;
3083 if (PyType_Ready(&NullImporterType) < 0)
3084 goto failure;
3086 m = Py_InitModule4("imp", imp_methods, doc_imp,
3087 NULL, PYTHON_API_VERSION);
3088 if (m == NULL)
3089 goto failure;
3090 d = PyModule_GetDict(m);
3091 if (d == NULL)
3092 goto failure;
3094 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3095 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3096 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3097 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3098 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3099 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3100 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3101 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3102 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3103 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
3105 Py_INCREF(&NullImporterType);
3106 PyModule_AddObject(m, "NullImporter", (PyObject *)&NullImporterType);
3107 failure:
3112 /* API for embedding applications that want to add their own entries
3113 to the table of built-in modules. This should normally be called
3114 *before* Py_Initialize(). When the table resize fails, -1 is
3115 returned and the existing table is unchanged.
3117 After a similar function by Just van Rossum. */
3120 PyImport_ExtendInittab(struct _inittab *newtab)
3122 static struct _inittab *our_copy = NULL;
3123 struct _inittab *p;
3124 int i, n;
3126 /* Count the number of entries in both tables */
3127 for (n = 0; newtab[n].name != NULL; n++)
3129 if (n == 0)
3130 return 0; /* Nothing to do */
3131 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3134 /* Allocate new memory for the combined table */
3135 p = our_copy;
3136 PyMem_RESIZE(p, struct _inittab, i+n+1);
3137 if (p == NULL)
3138 return -1;
3140 /* Copy the tables into the new memory */
3141 if (our_copy != PyImport_Inittab)
3142 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3143 PyImport_Inittab = our_copy = p;
3144 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3146 return 0;
3149 /* Shorthand to add a single entry given a name and a function */
3152 PyImport_AppendInittab(char *name, void (*initfunc)(void))
3154 struct _inittab newtab[2];
3156 memset(newtab, '\0', sizeof newtab);
3158 newtab[0].name = name;
3159 newtab[0].initfunc = initfunc;
3161 return PyImport_ExtendInittab(newtab);
3164 #ifdef __cplusplus
3166 #endif