Updated documentation for SysLogHandler (#1720726).
[python.git] / Python / import.c
blob383b6b20b1cb249d8b16ea55e0027ca18939c05e
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 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
123 ++countD;
124 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
125 ++countS;
126 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
127 if (filetab == NULL)
128 Py_FatalError("Can't initialize import file table.");
129 memcpy(filetab, _PyImport_DynLoadFiletab,
130 countD * sizeof(struct filedescr));
131 memcpy(filetab + countD, _PyImport_StandardFiletab,
132 countS * sizeof(struct filedescr));
133 filetab[countD + countS].suffix = NULL;
135 _PyImport_Filetab = filetab;
137 if (Py_OptimizeFlag) {
138 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
139 for (; filetab->suffix != NULL; filetab++) {
140 #ifndef RISCOS
141 if (strcmp(filetab->suffix, ".pyc") == 0)
142 filetab->suffix = ".pyo";
143 #else
144 if (strcmp(filetab->suffix, "/pyc") == 0)
145 filetab->suffix = "/pyo";
146 #endif
150 if (Py_UnicodeFlag) {
151 /* Fix the pyc_magic so that byte compiled code created
152 using the all-Unicode method doesn't interfere with
153 code created in normal operation mode. */
154 pyc_magic = MAGIC + 1;
158 void
159 _PyImportHooks_Init(void)
161 PyObject *v, *path_hooks = NULL, *zimpimport;
162 int err = 0;
164 /* adding sys.path_hooks and sys.path_importer_cache, setting up
165 zipimport */
166 if (PyType_Ready(&NullImporterType) < 0)
167 goto error;
169 if (Py_VerboseFlag)
170 PySys_WriteStderr("# installing zipimport hook\n");
172 v = PyList_New(0);
173 if (v == NULL)
174 goto error;
175 err = PySys_SetObject("meta_path", v);
176 Py_DECREF(v);
177 if (err)
178 goto error;
179 v = PyDict_New();
180 if (v == NULL)
181 goto error;
182 err = PySys_SetObject("path_importer_cache", v);
183 Py_DECREF(v);
184 if (err)
185 goto error;
186 path_hooks = PyList_New(0);
187 if (path_hooks == NULL)
188 goto error;
189 err = PySys_SetObject("path_hooks", path_hooks);
190 if (err) {
191 error:
192 PyErr_Print();
193 Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
194 "path_importer_cache, or NullImporter failed"
198 zimpimport = PyImport_ImportModule("zipimport");
199 if (zimpimport == NULL) {
200 PyErr_Clear(); /* No zip import module -- okay */
201 if (Py_VerboseFlag)
202 PySys_WriteStderr("# can't import zipimport\n");
204 else {
205 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
206 "zipimporter");
207 Py_DECREF(zimpimport);
208 if (zipimporter == NULL) {
209 PyErr_Clear(); /* No zipimporter object -- okay */
210 if (Py_VerboseFlag)
211 PySys_WriteStderr(
212 "# can't import zipimport.zipimporter\n");
214 else {
215 /* sys.path_hooks.append(zipimporter) */
216 err = PyList_Append(path_hooks, zipimporter);
217 Py_DECREF(zipimporter);
218 if (err)
219 goto error;
220 if (Py_VerboseFlag)
221 PySys_WriteStderr(
222 "# installed zipimport hook\n");
225 Py_DECREF(path_hooks);
228 void
229 _PyImport_Fini(void)
231 Py_XDECREF(extensions);
232 extensions = NULL;
233 PyMem_DEL(_PyImport_Filetab);
234 _PyImport_Filetab = NULL;
238 /* Locking primitives to prevent parallel imports of the same module
239 in different threads to return with a partially loaded module.
240 These calls are serialized by the global interpreter lock. */
242 #ifdef WITH_THREAD
244 #include "pythread.h"
246 static PyThread_type_lock import_lock = 0;
247 static long import_lock_thread = -1;
248 static int import_lock_level = 0;
250 static void
251 lock_import(void)
253 long me = PyThread_get_thread_ident();
254 if (me == -1)
255 return; /* Too bad */
256 if (import_lock == NULL) {
257 import_lock = PyThread_allocate_lock();
258 if (import_lock == NULL)
259 return; /* Nothing much we can do. */
261 if (import_lock_thread == me) {
262 import_lock_level++;
263 return;
265 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
267 PyThreadState *tstate = PyEval_SaveThread();
268 PyThread_acquire_lock(import_lock, 1);
269 PyEval_RestoreThread(tstate);
271 import_lock_thread = me;
272 import_lock_level = 1;
275 static int
276 unlock_import(void)
278 long me = PyThread_get_thread_ident();
279 if (me == -1 || import_lock == NULL)
280 return 0; /* Too bad */
281 if (import_lock_thread != me)
282 return -1;
283 import_lock_level--;
284 if (import_lock_level == 0) {
285 import_lock_thread = -1;
286 PyThread_release_lock(import_lock);
288 return 1;
291 /* This function is called from PyOS_AfterFork to ensure that newly
292 created child processes do not share locks with the parent. */
294 void
295 _PyImport_ReInitLock(void)
297 #ifdef _AIX
298 if (import_lock != NULL)
299 import_lock = PyThread_allocate_lock();
300 #endif
303 #else
305 #define lock_import()
306 #define unlock_import() 0
308 #endif
310 static PyObject *
311 imp_lock_held(PyObject *self, PyObject *noargs)
313 #ifdef WITH_THREAD
314 return PyBool_FromLong(import_lock_thread != -1);
315 #else
316 return PyBool_FromLong(0);
317 #endif
320 static PyObject *
321 imp_acquire_lock(PyObject *self, PyObject *noargs)
323 #ifdef WITH_THREAD
324 lock_import();
325 #endif
326 Py_INCREF(Py_None);
327 return Py_None;
330 static PyObject *
331 imp_release_lock(PyObject *self, PyObject *noargs)
333 #ifdef WITH_THREAD
334 if (unlock_import() < 0) {
335 PyErr_SetString(PyExc_RuntimeError,
336 "not holding the import lock");
337 return NULL;
339 #endif
340 Py_INCREF(Py_None);
341 return Py_None;
344 static void
345 imp_modules_reloading_clear(void)
347 PyInterpreterState *interp = PyThreadState_Get()->interp;
348 if (interp->modules_reloading != NULL)
349 PyDict_Clear(interp->modules_reloading);
352 /* Helper for sys */
354 PyObject *
355 PyImport_GetModuleDict(void)
357 PyInterpreterState *interp = PyThreadState_GET()->interp;
358 if (interp->modules == NULL)
359 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
360 return interp->modules;
364 /* List of names to clear in sys */
365 static char* sys_deletes[] = {
366 "path", "argv", "ps1", "ps2", "exitfunc",
367 "exc_type", "exc_value", "exc_traceback",
368 "last_type", "last_value", "last_traceback",
369 "path_hooks", "path_importer_cache", "meta_path",
370 NULL
373 static char* sys_files[] = {
374 "stdin", "__stdin__",
375 "stdout", "__stdout__",
376 "stderr", "__stderr__",
377 NULL
381 /* Un-initialize things, as good as we can */
383 void
384 PyImport_Cleanup(void)
386 Py_ssize_t pos, ndone;
387 char *name;
388 PyObject *key, *value, *dict;
389 PyInterpreterState *interp = PyThreadState_GET()->interp;
390 PyObject *modules = interp->modules;
392 if (modules == NULL)
393 return; /* Already done */
395 /* Delete some special variables first. These are common
396 places where user values hide and people complain when their
397 destructors fail. Since the modules containing them are
398 deleted *last* of all, they would come too late in the normal
399 destruction order. Sigh. */
401 value = PyDict_GetItemString(modules, "__builtin__");
402 if (value != NULL && PyModule_Check(value)) {
403 dict = PyModule_GetDict(value);
404 if (Py_VerboseFlag)
405 PySys_WriteStderr("# clear __builtin__._\n");
406 PyDict_SetItemString(dict, "_", Py_None);
408 value = PyDict_GetItemString(modules, "sys");
409 if (value != NULL && PyModule_Check(value)) {
410 char **p;
411 PyObject *v;
412 dict = PyModule_GetDict(value);
413 for (p = sys_deletes; *p != NULL; p++) {
414 if (Py_VerboseFlag)
415 PySys_WriteStderr("# clear sys.%s\n", *p);
416 PyDict_SetItemString(dict, *p, Py_None);
418 for (p = sys_files; *p != NULL; p+=2) {
419 if (Py_VerboseFlag)
420 PySys_WriteStderr("# restore sys.%s\n", *p);
421 v = PyDict_GetItemString(dict, *(p+1));
422 if (v == NULL)
423 v = Py_None;
424 PyDict_SetItemString(dict, *p, v);
428 /* First, delete __main__ */
429 value = PyDict_GetItemString(modules, "__main__");
430 if (value != NULL && PyModule_Check(value)) {
431 if (Py_VerboseFlag)
432 PySys_WriteStderr("# cleanup __main__\n");
433 _PyModule_Clear(value);
434 PyDict_SetItemString(modules, "__main__", Py_None);
437 /* The special treatment of __builtin__ here is because even
438 when it's not referenced as a module, its dictionary is
439 referenced by almost every module's __builtins__. Since
440 deleting a module clears its dictionary (even if there are
441 references left to it), we need to delete the __builtin__
442 module last. Likewise, we don't delete sys until the very
443 end because it is implicitly referenced (e.g. by print).
445 Also note that we 'delete' modules by replacing their entry
446 in the modules dict with None, rather than really deleting
447 them; this avoids a rehash of the modules dictionary and
448 also marks them as "non existent" so they won't be
449 re-imported. */
451 /* Next, repeatedly delete modules with a reference count of
452 one (skipping __builtin__ and sys) and delete them */
453 do {
454 ndone = 0;
455 pos = 0;
456 while (PyDict_Next(modules, &pos, &key, &value)) {
457 if (value->ob_refcnt != 1)
458 continue;
459 if (PyString_Check(key) && PyModule_Check(value)) {
460 name = PyString_AS_STRING(key);
461 if (strcmp(name, "__builtin__") == 0)
462 continue;
463 if (strcmp(name, "sys") == 0)
464 continue;
465 if (Py_VerboseFlag)
466 PySys_WriteStderr(
467 "# cleanup[1] %s\n", name);
468 _PyModule_Clear(value);
469 PyDict_SetItem(modules, key, Py_None);
470 ndone++;
473 } while (ndone > 0);
475 /* Next, delete all modules (still skipping __builtin__ and sys) */
476 pos = 0;
477 while (PyDict_Next(modules, &pos, &key, &value)) {
478 if (PyString_Check(key) && PyModule_Check(value)) {
479 name = PyString_AS_STRING(key);
480 if (strcmp(name, "__builtin__") == 0)
481 continue;
482 if (strcmp(name, "sys") == 0)
483 continue;
484 if (Py_VerboseFlag)
485 PySys_WriteStderr("# cleanup[2] %s\n", name);
486 _PyModule_Clear(value);
487 PyDict_SetItem(modules, key, Py_None);
491 /* Next, delete sys and __builtin__ (in that order) */
492 value = PyDict_GetItemString(modules, "sys");
493 if (value != NULL && PyModule_Check(value)) {
494 if (Py_VerboseFlag)
495 PySys_WriteStderr("# cleanup sys\n");
496 _PyModule_Clear(value);
497 PyDict_SetItemString(modules, "sys", Py_None);
499 value = PyDict_GetItemString(modules, "__builtin__");
500 if (value != NULL && PyModule_Check(value)) {
501 if (Py_VerboseFlag)
502 PySys_WriteStderr("# cleanup __builtin__\n");
503 _PyModule_Clear(value);
504 PyDict_SetItemString(modules, "__builtin__", Py_None);
507 /* Finally, clear and delete the modules directory */
508 PyDict_Clear(modules);
509 interp->modules = NULL;
510 Py_DECREF(modules);
511 Py_CLEAR(interp->modules_reloading);
515 /* Helper for pythonrun.c -- return magic number */
517 long
518 PyImport_GetMagicNumber(void)
520 return pyc_magic;
524 /* Magic for extension modules (built-in as well as dynamically
525 loaded). To prevent initializing an extension module more than
526 once, we keep a static dictionary 'extensions' keyed by module name
527 (for built-in modules) or by filename (for dynamically loaded
528 modules), containing these modules. A copy of the module's
529 dictionary is stored by calling _PyImport_FixupExtension()
530 immediately after the module initialization function succeeds. A
531 copy can be retrieved from there by calling
532 _PyImport_FindExtension(). */
534 PyObject *
535 _PyImport_FixupExtension(char *name, char *filename)
537 PyObject *modules, *mod, *dict, *copy;
538 if (extensions == NULL) {
539 extensions = PyDict_New();
540 if (extensions == NULL)
541 return NULL;
543 modules = PyImport_GetModuleDict();
544 mod = PyDict_GetItemString(modules, name);
545 if (mod == NULL || !PyModule_Check(mod)) {
546 PyErr_Format(PyExc_SystemError,
547 "_PyImport_FixupExtension: module %.200s not loaded", name);
548 return NULL;
550 dict = PyModule_GetDict(mod);
551 if (dict == NULL)
552 return NULL;
553 copy = PyDict_Copy(dict);
554 if (copy == NULL)
555 return NULL;
556 PyDict_SetItemString(extensions, filename, copy);
557 Py_DECREF(copy);
558 return copy;
561 PyObject *
562 _PyImport_FindExtension(char *name, char *filename)
564 PyObject *dict, *mod, *mdict;
565 if (extensions == NULL)
566 return NULL;
567 dict = PyDict_GetItemString(extensions, filename);
568 if (dict == NULL)
569 return NULL;
570 mod = PyImport_AddModule(name);
571 if (mod == NULL)
572 return NULL;
573 mdict = PyModule_GetDict(mod);
574 if (mdict == NULL)
575 return NULL;
576 if (PyDict_Update(mdict, dict))
577 return NULL;
578 if (Py_VerboseFlag)
579 PySys_WriteStderr("import %s # previously loaded (%s)\n",
580 name, filename);
581 return mod;
585 /* Get the module object corresponding to a module name.
586 First check the modules dictionary if there's one there,
587 if not, create a new one and insert it in the modules dictionary.
588 Because the former action is most common, THIS DOES NOT RETURN A
589 'NEW' REFERENCE! */
591 PyObject *
592 PyImport_AddModule(const char *name)
594 PyObject *modules = PyImport_GetModuleDict();
595 PyObject *m;
597 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
598 PyModule_Check(m))
599 return m;
600 m = PyModule_New(name);
601 if (m == NULL)
602 return NULL;
603 if (PyDict_SetItemString(modules, name, m) != 0) {
604 Py_DECREF(m);
605 return NULL;
607 Py_DECREF(m); /* Yes, it still exists, in modules! */
609 return m;
612 /* Remove name from sys.modules, if it's there. */
613 static void
614 _RemoveModule(const char *name)
616 PyObject *modules = PyImport_GetModuleDict();
617 if (PyDict_GetItemString(modules, name) == NULL)
618 return;
619 if (PyDict_DelItemString(modules, name) < 0)
620 Py_FatalError("import: deleting existing key in"
621 "sys.modules failed");
624 /* Execute a code object in a module and return the module object
625 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
626 * removed from sys.modules, to avoid leaving damaged module objects
627 * in sys.modules. The caller may wish to restore the original
628 * module object (if any) in this case; PyImport_ReloadModule is an
629 * example.
631 PyObject *
632 PyImport_ExecCodeModule(char *name, PyObject *co)
634 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
637 PyObject *
638 PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
640 PyObject *modules = PyImport_GetModuleDict();
641 PyObject *m, *d, *v;
643 m = PyImport_AddModule(name);
644 if (m == NULL)
645 return NULL;
646 /* If the module is being reloaded, we get the old module back
647 and re-use its dict to exec the new code. */
648 d = PyModule_GetDict(m);
649 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
650 if (PyDict_SetItemString(d, "__builtins__",
651 PyEval_GetBuiltins()) != 0)
652 goto error;
654 /* Remember the filename as the __file__ attribute */
655 v = NULL;
656 if (pathname != NULL) {
657 v = PyString_FromString(pathname);
658 if (v == NULL)
659 PyErr_Clear();
661 if (v == NULL) {
662 v = ((PyCodeObject *)co)->co_filename;
663 Py_INCREF(v);
665 if (PyDict_SetItemString(d, "__file__", v) != 0)
666 PyErr_Clear(); /* Not important enough to report */
667 Py_DECREF(v);
669 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
670 if (v == NULL)
671 goto error;
672 Py_DECREF(v);
674 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
675 PyErr_Format(PyExc_ImportError,
676 "Loaded module %.200s not found in sys.modules",
677 name);
678 return NULL;
681 Py_INCREF(m);
683 return m;
685 error:
686 _RemoveModule(name);
687 return NULL;
691 /* Given a pathname for a Python source file, fill a buffer with the
692 pathname for the corresponding compiled file. Return the pathname
693 for the compiled file, or NULL if there's no space in the buffer.
694 Doesn't set an exception. */
696 static char *
697 make_compiled_pathname(char *pathname, char *buf, size_t buflen)
699 size_t len = strlen(pathname);
700 if (len+2 > buflen)
701 return NULL;
703 #ifdef MS_WINDOWS
704 /* Treat .pyw as if it were .py. The case of ".pyw" must match
705 that used in _PyImport_StandardFiletab. */
706 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
707 --len; /* pretend 'w' isn't there */
708 #endif
709 memcpy(buf, pathname, len);
710 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
711 buf[len+1] = '\0';
713 return buf;
717 /* Given a pathname for a Python source file, its time of last
718 modification, and a pathname for a compiled file, check whether the
719 compiled file represents the same version of the source. If so,
720 return a FILE pointer for the compiled file, positioned just after
721 the header; if not, return NULL.
722 Doesn't set an exception. */
724 static FILE *
725 check_compiled_module(char *pathname, time_t mtime, char *cpathname)
727 FILE *fp;
728 long magic;
729 long pyc_mtime;
731 fp = fopen(cpathname, "rb");
732 if (fp == NULL)
733 return NULL;
734 magic = PyMarshal_ReadLongFromFile(fp);
735 if (magic != pyc_magic) {
736 if (Py_VerboseFlag)
737 PySys_WriteStderr("# %s has bad magic\n", cpathname);
738 fclose(fp);
739 return NULL;
741 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
742 if (pyc_mtime != mtime) {
743 if (Py_VerboseFlag)
744 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
745 fclose(fp);
746 return NULL;
748 if (Py_VerboseFlag)
749 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
750 return fp;
754 /* Read a code object from a file and check it for validity */
756 static PyCodeObject *
757 read_compiled_module(char *cpathname, FILE *fp)
759 PyObject *co;
761 co = PyMarshal_ReadLastObjectFromFile(fp);
762 if (co == NULL)
763 return NULL;
764 if (!PyCode_Check(co)) {
765 PyErr_Format(PyExc_ImportError,
766 "Non-code object in %.200s", cpathname);
767 Py_DECREF(co);
768 return NULL;
770 return (PyCodeObject *)co;
774 /* Load a module from a compiled file, execute it, and return its
775 module object WITH INCREMENTED REFERENCE COUNT */
777 static PyObject *
778 load_compiled_module(char *name, char *cpathname, FILE *fp)
780 long magic;
781 PyCodeObject *co;
782 PyObject *m;
784 magic = PyMarshal_ReadLongFromFile(fp);
785 if (magic != pyc_magic) {
786 PyErr_Format(PyExc_ImportError,
787 "Bad magic number in %.200s", cpathname);
788 return NULL;
790 (void) PyMarshal_ReadLongFromFile(fp);
791 co = read_compiled_module(cpathname, fp);
792 if (co == NULL)
793 return NULL;
794 if (Py_VerboseFlag)
795 PySys_WriteStderr("import %s # precompiled from %s\n",
796 name, cpathname);
797 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
798 Py_DECREF(co);
800 return m;
803 /* Parse a source file and return the corresponding code object */
805 static PyCodeObject *
806 parse_source_module(const char *pathname, FILE *fp)
808 PyCodeObject *co = NULL;
809 mod_ty mod;
810 PyArena *arena = PyArena_New();
811 if (arena == NULL)
812 return NULL;
814 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, 0,
815 NULL, arena);
816 if (mod) {
817 co = PyAST_Compile(mod, pathname, NULL, arena);
819 PyArena_Free(arena);
820 return co;
824 /* Helper to open a bytecode file for writing in exclusive mode */
826 static FILE *
827 open_exclusive(char *filename)
829 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
830 /* Use O_EXCL to avoid a race condition when another process tries to
831 write the same file. When that happens, our open() call fails,
832 which is just fine (since it's only a cache).
833 XXX If the file exists and is writable but the directory is not
834 writable, the file will never be written. Oh well.
836 int fd;
837 (void) unlink(filename);
838 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
839 #ifdef O_BINARY
840 |O_BINARY /* necessary for Windows */
841 #endif
842 #ifdef __VMS
843 , 0666, "ctxt=bin", "shr=nil"
844 #else
845 , 0666
846 #endif
848 if (fd < 0)
849 return NULL;
850 return fdopen(fd, "wb");
851 #else
852 /* Best we can do -- on Windows this can't happen anyway */
853 return fopen(filename, "wb");
854 #endif
858 /* Write a compiled module to a file, placing the time of last
859 modification of its source into the header.
860 Errors are ignored, if a write error occurs an attempt is made to
861 remove the file. */
863 static void
864 write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime)
866 FILE *fp;
868 fp = open_exclusive(cpathname);
869 if (fp == NULL) {
870 if (Py_VerboseFlag)
871 PySys_WriteStderr(
872 "# can't create %s\n", cpathname);
873 return;
875 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
876 /* First write a 0 for mtime */
877 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
878 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
879 if (fflush(fp) != 0 || ferror(fp)) {
880 if (Py_VerboseFlag)
881 PySys_WriteStderr("# can't write %s\n", cpathname);
882 /* Don't keep partial file */
883 fclose(fp);
884 (void) unlink(cpathname);
885 return;
887 /* Now write the true mtime */
888 fseek(fp, 4L, 0);
889 assert(mtime < LONG_MAX);
890 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
891 fflush(fp);
892 fclose(fp);
893 if (Py_VerboseFlag)
894 PySys_WriteStderr("# wrote %s\n", cpathname);
898 /* Load a source module from a given file and return its module
899 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
900 byte-compiled file, use that instead. */
902 static PyObject *
903 load_source_module(char *name, char *pathname, FILE *fp)
905 time_t mtime;
906 FILE *fpc;
907 char buf[MAXPATHLEN+1];
908 char *cpathname;
909 PyCodeObject *co;
910 PyObject *m;
912 mtime = PyOS_GetLastModificationTime(pathname, fp);
913 if (mtime == (time_t)(-1)) {
914 PyErr_Format(PyExc_RuntimeError,
915 "unable to get modification time from '%s'",
916 pathname);
917 return NULL;
919 #if SIZEOF_TIME_T > 4
920 /* Python's .pyc timestamp handling presumes that the timestamp fits
921 in 4 bytes. This will be fine until sometime in the year 2038,
922 when a 4-byte signed time_t will overflow.
924 if (mtime >> 32) {
925 PyErr_SetString(PyExc_OverflowError,
926 "modification time overflows a 4 byte field");
927 return NULL;
929 #endif
930 cpathname = make_compiled_pathname(pathname, buf,
931 (size_t)MAXPATHLEN + 1);
932 if (cpathname != NULL &&
933 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
934 co = read_compiled_module(cpathname, fpc);
935 fclose(fpc);
936 if (co == NULL)
937 return NULL;
938 if (Py_VerboseFlag)
939 PySys_WriteStderr("import %s # precompiled from %s\n",
940 name, cpathname);
941 pathname = cpathname;
943 else {
944 co = parse_source_module(pathname, fp);
945 if (co == NULL)
946 return NULL;
947 if (Py_VerboseFlag)
948 PySys_WriteStderr("import %s # from %s\n",
949 name, pathname);
950 if (cpathname)
951 write_compiled_module(co, cpathname, mtime);
953 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
954 Py_DECREF(co);
956 return m;
960 /* Forward */
961 static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
962 static struct filedescr *find_module(char *, char *, PyObject *,
963 char *, size_t, FILE **, PyObject **);
964 static struct _frozen *find_frozen(char *name);
966 /* Load a package and return its module object WITH INCREMENTED
967 REFERENCE COUNT */
969 static PyObject *
970 load_package(char *name, char *pathname)
972 PyObject *m, *d;
973 PyObject *file = NULL;
974 PyObject *path = NULL;
975 int err;
976 char buf[MAXPATHLEN+1];
977 FILE *fp = NULL;
978 struct filedescr *fdp;
980 m = PyImport_AddModule(name);
981 if (m == NULL)
982 return NULL;
983 if (Py_VerboseFlag)
984 PySys_WriteStderr("import %s # directory %s\n",
985 name, pathname);
986 d = PyModule_GetDict(m);
987 file = PyString_FromString(pathname);
988 if (file == NULL)
989 goto error;
990 path = Py_BuildValue("[O]", file);
991 if (path == NULL)
992 goto error;
993 err = PyDict_SetItemString(d, "__file__", file);
994 if (err == 0)
995 err = PyDict_SetItemString(d, "__path__", path);
996 if (err != 0)
997 goto error;
998 buf[0] = '\0';
999 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
1000 if (fdp == NULL) {
1001 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1002 PyErr_Clear();
1003 Py_INCREF(m);
1005 else
1006 m = NULL;
1007 goto cleanup;
1009 m = load_module(name, fp, buf, fdp->type, NULL);
1010 if (fp != NULL)
1011 fclose(fp);
1012 goto cleanup;
1014 error:
1015 m = NULL;
1016 cleanup:
1017 Py_XDECREF(path);
1018 Py_XDECREF(file);
1019 return m;
1023 /* Helper to test for built-in module */
1025 static int
1026 is_builtin(char *name)
1028 int i;
1029 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1030 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1031 if (PyImport_Inittab[i].initfunc == NULL)
1032 return -1;
1033 else
1034 return 1;
1037 return 0;
1041 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
1042 possibly by fetching it from the path_importer_cache dict. If it
1043 wasn't yet cached, traverse path_hooks until a hook is found
1044 that can handle the path item. Return None if no hook could;
1045 this tells our caller it should fall back to the builtin
1046 import mechanism. Cache the result in path_importer_cache.
1047 Returns a borrowed reference. */
1049 static PyObject *
1050 get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1051 PyObject *p)
1053 PyObject *importer;
1054 Py_ssize_t j, nhooks;
1056 /* These conditions are the caller's responsibility: */
1057 assert(PyList_Check(path_hooks));
1058 assert(PyDict_Check(path_importer_cache));
1060 nhooks = PyList_Size(path_hooks);
1061 if (nhooks < 0)
1062 return NULL; /* Shouldn't happen */
1064 importer = PyDict_GetItem(path_importer_cache, p);
1065 if (importer != NULL)
1066 return importer;
1068 /* set path_importer_cache[p] to None to avoid recursion */
1069 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1070 return NULL;
1072 for (j = 0; j < nhooks; j++) {
1073 PyObject *hook = PyList_GetItem(path_hooks, j);
1074 if (hook == NULL)
1075 return NULL;
1076 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1077 if (importer != NULL)
1078 break;
1080 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1081 return NULL;
1083 PyErr_Clear();
1085 if (importer == NULL) {
1086 importer = PyObject_CallFunctionObjArgs(
1087 (PyObject *)&NullImporterType, p, NULL
1089 if (importer == NULL) {
1090 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
1091 PyErr_Clear();
1092 return Py_None;
1096 if (importer != NULL) {
1097 int err = PyDict_SetItem(path_importer_cache, p, importer);
1098 Py_DECREF(importer);
1099 if (err != 0)
1100 return NULL;
1102 return importer;
1105 /* Search the path (default sys.path) for a module. Return the
1106 corresponding filedescr struct, and (via return arguments) the
1107 pathname and an open file. Return NULL if the module is not found. */
1109 #ifdef MS_COREDLL
1110 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
1111 char *, Py_ssize_t);
1112 #endif
1114 static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
1115 static int find_init_module(char *); /* Forward */
1116 static struct filedescr importhookdescr = {"", "", IMP_HOOK};
1118 static struct filedescr *
1119 find_module(char *fullname, char *subname, PyObject *path, char *buf,
1120 size_t buflen, FILE **p_fp, PyObject **p_loader)
1122 Py_ssize_t i, npath;
1123 size_t len, namelen;
1124 struct filedescr *fdp = NULL;
1125 char *filemode;
1126 FILE *fp = NULL;
1127 PyObject *path_hooks, *path_importer_cache;
1128 #ifndef RISCOS
1129 struct stat statbuf;
1130 #endif
1131 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1132 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1133 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1134 char name[MAXPATHLEN+1];
1135 #if defined(PYOS_OS2)
1136 size_t saved_len;
1137 size_t saved_namelen;
1138 char *saved_buf = NULL;
1139 #endif
1140 if (p_loader != NULL)
1141 *p_loader = NULL;
1143 if (strlen(subname) > MAXPATHLEN) {
1144 PyErr_SetString(PyExc_OverflowError,
1145 "module name is too long");
1146 return NULL;
1148 strcpy(name, subname);
1150 /* sys.meta_path import hook */
1151 if (p_loader != NULL) {
1152 PyObject *meta_path;
1154 meta_path = PySys_GetObject("meta_path");
1155 if (meta_path == NULL || !PyList_Check(meta_path)) {
1156 PyErr_SetString(PyExc_ImportError,
1157 "sys.meta_path must be a list of "
1158 "import hooks");
1159 return NULL;
1161 Py_INCREF(meta_path); /* zap guard */
1162 npath = PyList_Size(meta_path);
1163 for (i = 0; i < npath; i++) {
1164 PyObject *loader;
1165 PyObject *hook = PyList_GetItem(meta_path, i);
1166 loader = PyObject_CallMethod(hook, "find_module",
1167 "sO", fullname,
1168 path != NULL ?
1169 path : Py_None);
1170 if (loader == NULL) {
1171 Py_DECREF(meta_path);
1172 return NULL; /* true error */
1174 if (loader != Py_None) {
1175 /* a loader was found */
1176 *p_loader = loader;
1177 Py_DECREF(meta_path);
1178 return &importhookdescr;
1180 Py_DECREF(loader);
1182 Py_DECREF(meta_path);
1185 if (path != NULL && PyString_Check(path)) {
1186 /* The only type of submodule allowed inside a "frozen"
1187 package are other frozen modules or packages. */
1188 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1189 PyErr_SetString(PyExc_ImportError,
1190 "full frozen module name too long");
1191 return NULL;
1193 strcpy(buf, PyString_AsString(path));
1194 strcat(buf, ".");
1195 strcat(buf, name);
1196 strcpy(name, buf);
1197 if (find_frozen(name) != NULL) {
1198 strcpy(buf, name);
1199 return &fd_frozen;
1201 PyErr_Format(PyExc_ImportError,
1202 "No frozen submodule named %.200s", name);
1203 return NULL;
1205 if (path == NULL) {
1206 if (is_builtin(name)) {
1207 strcpy(buf, name);
1208 return &fd_builtin;
1210 if ((find_frozen(name)) != NULL) {
1211 strcpy(buf, name);
1212 return &fd_frozen;
1215 #ifdef MS_COREDLL
1216 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1217 if (fp != NULL) {
1218 *p_fp = fp;
1219 return fdp;
1221 #endif
1222 path = PySys_GetObject("path");
1224 if (path == NULL || !PyList_Check(path)) {
1225 PyErr_SetString(PyExc_ImportError,
1226 "sys.path must be a list of directory names");
1227 return NULL;
1230 path_hooks = PySys_GetObject("path_hooks");
1231 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1232 PyErr_SetString(PyExc_ImportError,
1233 "sys.path_hooks must be a list of "
1234 "import hooks");
1235 return NULL;
1237 path_importer_cache = PySys_GetObject("path_importer_cache");
1238 if (path_importer_cache == NULL ||
1239 !PyDict_Check(path_importer_cache)) {
1240 PyErr_SetString(PyExc_ImportError,
1241 "sys.path_importer_cache must be a dict");
1242 return NULL;
1245 npath = PyList_Size(path);
1246 namelen = strlen(name);
1247 for (i = 0; i < npath; i++) {
1248 PyObject *copy = NULL;
1249 PyObject *v = PyList_GetItem(path, i);
1250 if (!v)
1251 return NULL;
1252 #ifdef Py_USING_UNICODE
1253 if (PyUnicode_Check(v)) {
1254 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1255 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1256 if (copy == NULL)
1257 return NULL;
1258 v = copy;
1260 else
1261 #endif
1262 if (!PyString_Check(v))
1263 continue;
1264 len = PyString_GET_SIZE(v);
1265 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1266 Py_XDECREF(copy);
1267 continue; /* Too long */
1269 strcpy(buf, PyString_AS_STRING(v));
1270 if (strlen(buf) != len) {
1271 Py_XDECREF(copy);
1272 continue; /* v contains '\0' */
1275 /* sys.path_hooks import hook */
1276 if (p_loader != NULL) {
1277 PyObject *importer;
1279 importer = get_path_importer(path_importer_cache,
1280 path_hooks, v);
1281 if (importer == NULL) {
1282 Py_XDECREF(copy);
1283 return NULL;
1285 /* Note: importer is a borrowed reference */
1286 if (importer != Py_None) {
1287 PyObject *loader;
1288 loader = PyObject_CallMethod(importer,
1289 "find_module",
1290 "s", fullname);
1291 Py_XDECREF(copy);
1292 if (loader == NULL)
1293 return NULL; /* error */
1294 if (loader != Py_None) {
1295 /* a loader was found */
1296 *p_loader = loader;
1297 return &importhookdescr;
1299 Py_DECREF(loader);
1300 continue;
1303 /* no hook was found, use builtin import */
1305 if (len > 0 && buf[len-1] != SEP
1306 #ifdef ALTSEP
1307 && buf[len-1] != ALTSEP
1308 #endif
1310 buf[len++] = SEP;
1311 strcpy(buf+len, name);
1312 len += namelen;
1314 /* Check for package import (buf holds a directory name,
1315 and there's an __init__ module in that directory */
1316 #ifdef HAVE_STAT
1317 if (stat(buf, &statbuf) == 0 && /* it exists */
1318 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1319 case_ok(buf, len, namelen, name)) { /* case matches */
1320 if (find_init_module(buf)) { /* and has __init__.py */
1321 Py_XDECREF(copy);
1322 return &fd_package;
1324 else {
1325 char warnstr[MAXPATHLEN+80];
1326 sprintf(warnstr, "Not importing directory "
1327 "'%.*s': missing __init__.py",
1328 MAXPATHLEN, buf);
1329 if (PyErr_Warn(PyExc_ImportWarning,
1330 warnstr)) {
1331 Py_XDECREF(copy);
1332 return NULL;
1336 #else
1337 /* XXX How are you going to test for directories? */
1338 #ifdef RISCOS
1339 if (isdir(buf) &&
1340 case_ok(buf, len, namelen, name)) {
1341 if (find_init_module(buf)) {
1342 Py_XDECREF(copy);
1343 return &fd_package;
1345 else {
1346 char warnstr[MAXPATHLEN+80];
1347 sprintf(warnstr, "Not importing directory "
1348 "'%.*s': missing __init__.py",
1349 MAXPATHLEN, buf);
1350 if (PyErr_Warn(PyExc_ImportWarning,
1351 warnstr)) {
1352 Py_XDECREF(copy);
1353 return NULL;
1356 #endif
1357 #endif
1358 #if defined(PYOS_OS2)
1359 /* take a snapshot of the module spec for restoration
1360 * after the 8 character DLL hackery
1362 saved_buf = strdup(buf);
1363 saved_len = len;
1364 saved_namelen = namelen;
1365 #endif /* PYOS_OS2 */
1366 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1367 #if defined(PYOS_OS2)
1368 /* OS/2 limits DLLs to 8 character names (w/o
1369 extension)
1370 * so if the name is longer than that and its a
1371 * dynamically loaded module we're going to try,
1372 * truncate the name before trying
1374 if (strlen(subname) > 8) {
1375 /* is this an attempt to load a C extension? */
1376 const struct filedescr *scan;
1377 scan = _PyImport_DynLoadFiletab;
1378 while (scan->suffix != NULL) {
1379 if (!strcmp(scan->suffix, fdp->suffix))
1380 break;
1381 else
1382 scan++;
1384 if (scan->suffix != NULL) {
1385 /* yes, so truncate the name */
1386 namelen = 8;
1387 len -= strlen(subname) - namelen;
1388 buf[len] = '\0';
1391 #endif /* PYOS_OS2 */
1392 strcpy(buf+len, fdp->suffix);
1393 if (Py_VerboseFlag > 1)
1394 PySys_WriteStderr("# trying %s\n", buf);
1395 filemode = fdp->mode;
1396 if (filemode[0] == 'U')
1397 filemode = "r" PY_STDIOTEXTMODE;
1398 fp = fopen(buf, filemode);
1399 if (fp != NULL) {
1400 if (case_ok(buf, len, namelen, name))
1401 break;
1402 else { /* continue search */
1403 fclose(fp);
1404 fp = NULL;
1407 #if defined(PYOS_OS2)
1408 /* restore the saved snapshot */
1409 strcpy(buf, saved_buf);
1410 len = saved_len;
1411 namelen = saved_namelen;
1412 #endif
1414 #if defined(PYOS_OS2)
1415 /* don't need/want the module name snapshot anymore */
1416 if (saved_buf)
1418 free(saved_buf);
1419 saved_buf = NULL;
1421 #endif
1422 Py_XDECREF(copy);
1423 if (fp != NULL)
1424 break;
1426 if (fp == NULL) {
1427 PyErr_Format(PyExc_ImportError,
1428 "No module named %.200s", name);
1429 return NULL;
1431 *p_fp = fp;
1432 return fdp;
1435 /* Helpers for main.c
1436 * Find the source file corresponding to a named module
1438 struct filedescr *
1439 _PyImport_FindModule(const char *name, PyObject *path, char *buf,
1440 size_t buflen, FILE **p_fp, PyObject **p_loader)
1442 return find_module((char *) name, (char *) name, path,
1443 buf, buflen, p_fp, p_loader);
1446 PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1448 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1451 /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
1452 * The arguments here are tricky, best shown by example:
1453 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1454 * ^ ^ ^ ^
1455 * |--------------------- buf ---------------------|
1456 * |------------------- len ------------------|
1457 * |------ name -------|
1458 * |----- namelen -----|
1459 * buf is the full path, but len only counts up to (& exclusive of) the
1460 * extension. name is the module name, also exclusive of extension.
1462 * We've already done a successful stat() or fopen() on buf, so know that
1463 * there's some match, possibly case-insensitive.
1465 * case_ok() is to return 1 if there's a case-sensitive match for
1466 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1467 * exists.
1469 * case_ok() is used to implement case-sensitive import semantics even
1470 * on platforms with case-insensitive filesystems. It's trivial to implement
1471 * for case-sensitive filesystems. It's pretty much a cross-platform
1472 * nightmare for systems with case-insensitive filesystems.
1475 /* First we may need a pile of platform-specific header files; the sequence
1476 * of #if's here should match the sequence in the body of case_ok().
1478 #if defined(MS_WINDOWS)
1479 #include <windows.h>
1481 #elif defined(DJGPP)
1482 #include <dir.h>
1484 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1485 #include <sys/types.h>
1486 #include <dirent.h>
1488 #elif defined(PYOS_OS2)
1489 #define INCL_DOS
1490 #define INCL_DOSERRORS
1491 #define INCL_NOPMAPI
1492 #include <os2.h>
1494 #elif defined(RISCOS)
1495 #include "oslib/osfscontrol.h"
1496 #endif
1498 static int
1499 case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
1501 /* Pick a platform-specific implementation; the sequence of #if's here should
1502 * match the sequence just above.
1505 /* MS_WINDOWS */
1506 #if defined(MS_WINDOWS)
1507 WIN32_FIND_DATA data;
1508 HANDLE h;
1510 if (Py_GETENV("PYTHONCASEOK") != NULL)
1511 return 1;
1513 h = FindFirstFile(buf, &data);
1514 if (h == INVALID_HANDLE_VALUE) {
1515 PyErr_Format(PyExc_NameError,
1516 "Can't find file for module %.100s\n(filename %.300s)",
1517 name, buf);
1518 return 0;
1520 FindClose(h);
1521 return strncmp(data.cFileName, name, namelen) == 0;
1523 /* DJGPP */
1524 #elif defined(DJGPP)
1525 struct ffblk ffblk;
1526 int done;
1528 if (Py_GETENV("PYTHONCASEOK") != NULL)
1529 return 1;
1531 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1532 if (done) {
1533 PyErr_Format(PyExc_NameError,
1534 "Can't find file for module %.100s\n(filename %.300s)",
1535 name, buf);
1536 return 0;
1538 return strncmp(ffblk.ff_name, name, namelen) == 0;
1540 /* new-fangled macintosh (macosx) or Cygwin */
1541 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1542 DIR *dirp;
1543 struct dirent *dp;
1544 char dirname[MAXPATHLEN + 1];
1545 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
1547 if (Py_GETENV("PYTHONCASEOK") != NULL)
1548 return 1;
1550 /* Copy the dir component into dirname; substitute "." if empty */
1551 if (dirlen <= 0) {
1552 dirname[0] = '.';
1553 dirname[1] = '\0';
1555 else {
1556 assert(dirlen <= MAXPATHLEN);
1557 memcpy(dirname, buf, dirlen);
1558 dirname[dirlen] = '\0';
1560 /* Open the directory and search the entries for an exact match. */
1561 dirp = opendir(dirname);
1562 if (dirp) {
1563 char *nameWithExt = buf + len - namelen;
1564 while ((dp = readdir(dirp)) != NULL) {
1565 const int thislen =
1566 #ifdef _DIRENT_HAVE_D_NAMELEN
1567 dp->d_namlen;
1568 #else
1569 strlen(dp->d_name);
1570 #endif
1571 if (thislen >= namelen &&
1572 strcmp(dp->d_name, nameWithExt) == 0) {
1573 (void)closedir(dirp);
1574 return 1; /* Found */
1577 (void)closedir(dirp);
1579 return 0 ; /* Not found */
1581 /* RISC OS */
1582 #elif defined(RISCOS)
1583 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1584 char buf2[MAXPATHLEN+2];
1585 char *nameWithExt = buf+len-namelen;
1586 int canonlen;
1587 os_error *e;
1589 if (Py_GETENV("PYTHONCASEOK") != NULL)
1590 return 1;
1592 /* workaround:
1593 append wildcard, otherwise case of filename wouldn't be touched */
1594 strcpy(buf2, buf);
1595 strcat(buf2, "*");
1597 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1598 canonlen = MAXPATHLEN+1-canonlen;
1599 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1600 return 0;
1601 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1602 return 1; /* match */
1604 return 0;
1606 /* OS/2 */
1607 #elif defined(PYOS_OS2)
1608 HDIR hdir = 1;
1609 ULONG srchcnt = 1;
1610 FILEFINDBUF3 ffbuf;
1611 APIRET rc;
1613 if (getenv("PYTHONCASEOK") != NULL)
1614 return 1;
1616 rc = DosFindFirst(buf,
1617 &hdir,
1618 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1619 &ffbuf, sizeof(ffbuf),
1620 &srchcnt,
1621 FIL_STANDARD);
1622 if (rc != NO_ERROR)
1623 return 0;
1624 return strncmp(ffbuf.achName, name, namelen) == 0;
1626 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1627 #else
1628 return 1;
1630 #endif
1634 #ifdef HAVE_STAT
1635 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1636 static int
1637 find_init_module(char *buf)
1639 const size_t save_len = strlen(buf);
1640 size_t i = save_len;
1641 char *pname; /* pointer to start of __init__ */
1642 struct stat statbuf;
1644 /* For calling case_ok(buf, len, namelen, name):
1645 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1646 * ^ ^ ^ ^
1647 * |--------------------- buf ---------------------|
1648 * |------------------- len ------------------|
1649 * |------ name -------|
1650 * |----- namelen -----|
1652 if (save_len + 13 >= MAXPATHLEN)
1653 return 0;
1654 buf[i++] = SEP;
1655 pname = buf + i;
1656 strcpy(pname, "__init__.py");
1657 if (stat(buf, &statbuf) == 0) {
1658 if (case_ok(buf,
1659 save_len + 9, /* len("/__init__") */
1660 8, /* len("__init__") */
1661 pname)) {
1662 buf[save_len] = '\0';
1663 return 1;
1666 i += strlen(pname);
1667 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1668 if (stat(buf, &statbuf) == 0) {
1669 if (case_ok(buf,
1670 save_len + 9, /* len("/__init__") */
1671 8, /* len("__init__") */
1672 pname)) {
1673 buf[save_len] = '\0';
1674 return 1;
1677 buf[save_len] = '\0';
1678 return 0;
1681 #else
1683 #ifdef RISCOS
1684 static int
1685 find_init_module(buf)
1686 char *buf;
1688 int save_len = strlen(buf);
1689 int i = save_len;
1691 if (save_len + 13 >= MAXPATHLEN)
1692 return 0;
1693 buf[i++] = SEP;
1694 strcpy(buf+i, "__init__/py");
1695 if (isfile(buf)) {
1696 buf[save_len] = '\0';
1697 return 1;
1700 if (Py_OptimizeFlag)
1701 strcpy(buf+i, "o");
1702 else
1703 strcpy(buf+i, "c");
1704 if (isfile(buf)) {
1705 buf[save_len] = '\0';
1706 return 1;
1708 buf[save_len] = '\0';
1709 return 0;
1711 #endif /*RISCOS*/
1713 #endif /* HAVE_STAT */
1716 static int init_builtin(char *); /* Forward */
1718 /* Load an external module using the default search path and return
1719 its module object WITH INCREMENTED REFERENCE COUNT */
1721 static PyObject *
1722 load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
1724 PyObject *modules;
1725 PyObject *m;
1726 int err;
1728 /* First check that there's an open file (if we need one) */
1729 switch (type) {
1730 case PY_SOURCE:
1731 case PY_COMPILED:
1732 if (fp == NULL) {
1733 PyErr_Format(PyExc_ValueError,
1734 "file object required for import (type code %d)",
1735 type);
1736 return NULL;
1740 switch (type) {
1742 case PY_SOURCE:
1743 m = load_source_module(name, buf, fp);
1744 break;
1746 case PY_COMPILED:
1747 m = load_compiled_module(name, buf, fp);
1748 break;
1750 #ifdef HAVE_DYNAMIC_LOADING
1751 case C_EXTENSION:
1752 m = _PyImport_LoadDynamicModule(name, buf, fp);
1753 break;
1754 #endif
1756 case PKG_DIRECTORY:
1757 m = load_package(name, buf);
1758 break;
1760 case C_BUILTIN:
1761 case PY_FROZEN:
1762 if (buf != NULL && buf[0] != '\0')
1763 name = buf;
1764 if (type == C_BUILTIN)
1765 err = init_builtin(name);
1766 else
1767 err = PyImport_ImportFrozenModule(name);
1768 if (err < 0)
1769 return NULL;
1770 if (err == 0) {
1771 PyErr_Format(PyExc_ImportError,
1772 "Purported %s module %.200s not found",
1773 type == C_BUILTIN ?
1774 "builtin" : "frozen",
1775 name);
1776 return NULL;
1778 modules = PyImport_GetModuleDict();
1779 m = PyDict_GetItemString(modules, name);
1780 if (m == NULL) {
1781 PyErr_Format(
1782 PyExc_ImportError,
1783 "%s module %.200s not properly initialized",
1784 type == C_BUILTIN ?
1785 "builtin" : "frozen",
1786 name);
1787 return NULL;
1789 Py_INCREF(m);
1790 break;
1792 case IMP_HOOK: {
1793 if (loader == NULL) {
1794 PyErr_SetString(PyExc_ImportError,
1795 "import hook without loader");
1796 return NULL;
1798 m = PyObject_CallMethod(loader, "load_module", "s", name);
1799 break;
1802 default:
1803 PyErr_Format(PyExc_ImportError,
1804 "Don't know how to import %.200s (type code %d)",
1805 name, type);
1806 m = NULL;
1810 return m;
1814 /* Initialize a built-in module.
1815 Return 1 for success, 0 if the module is not found, and -1 with
1816 an exception set if the initialization failed. */
1818 static int
1819 init_builtin(char *name)
1821 struct _inittab *p;
1823 if (_PyImport_FindExtension(name, name) != NULL)
1824 return 1;
1826 for (p = PyImport_Inittab; p->name != NULL; p++) {
1827 if (strcmp(name, p->name) == 0) {
1828 if (p->initfunc == NULL) {
1829 PyErr_Format(PyExc_ImportError,
1830 "Cannot re-init internal module %.200s",
1831 name);
1832 return -1;
1834 if (Py_VerboseFlag)
1835 PySys_WriteStderr("import %s # builtin\n", name);
1836 (*p->initfunc)();
1837 if (PyErr_Occurred())
1838 return -1;
1839 if (_PyImport_FixupExtension(name, name) == NULL)
1840 return -1;
1841 return 1;
1844 return 0;
1848 /* Frozen modules */
1850 static struct _frozen *
1851 find_frozen(char *name)
1853 struct _frozen *p;
1855 for (p = PyImport_FrozenModules; ; p++) {
1856 if (p->name == NULL)
1857 return NULL;
1858 if (strcmp(p->name, name) == 0)
1859 break;
1861 return p;
1864 static PyObject *
1865 get_frozen_object(char *name)
1867 struct _frozen *p = find_frozen(name);
1868 int size;
1870 if (p == NULL) {
1871 PyErr_Format(PyExc_ImportError,
1872 "No such frozen object named %.200s",
1873 name);
1874 return NULL;
1876 if (p->code == NULL) {
1877 PyErr_Format(PyExc_ImportError,
1878 "Excluded frozen object named %.200s",
1879 name);
1880 return NULL;
1882 size = p->size;
1883 if (size < 0)
1884 size = -size;
1885 return PyMarshal_ReadObjectFromString((char *)p->code, size);
1888 /* Initialize a frozen module.
1889 Return 1 for succes, 0 if the module is not found, and -1 with
1890 an exception set if the initialization failed.
1891 This function is also used from frozenmain.c */
1894 PyImport_ImportFrozenModule(char *name)
1896 struct _frozen *p = find_frozen(name);
1897 PyObject *co;
1898 PyObject *m;
1899 int ispackage;
1900 int size;
1902 if (p == NULL)
1903 return 0;
1904 if (p->code == NULL) {
1905 PyErr_Format(PyExc_ImportError,
1906 "Excluded frozen object named %.200s",
1907 name);
1908 return -1;
1910 size = p->size;
1911 ispackage = (size < 0);
1912 if (ispackage)
1913 size = -size;
1914 if (Py_VerboseFlag)
1915 PySys_WriteStderr("import %s # frozen%s\n",
1916 name, ispackage ? " package" : "");
1917 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1918 if (co == NULL)
1919 return -1;
1920 if (!PyCode_Check(co)) {
1921 PyErr_Format(PyExc_TypeError,
1922 "frozen object %.200s is not a code object",
1923 name);
1924 goto err_return;
1926 if (ispackage) {
1927 /* Set __path__ to the package name */
1928 PyObject *d, *s;
1929 int err;
1930 m = PyImport_AddModule(name);
1931 if (m == NULL)
1932 goto err_return;
1933 d = PyModule_GetDict(m);
1934 s = PyString_InternFromString(name);
1935 if (s == NULL)
1936 goto err_return;
1937 err = PyDict_SetItemString(d, "__path__", s);
1938 Py_DECREF(s);
1939 if (err != 0)
1940 goto err_return;
1942 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
1943 if (m == NULL)
1944 goto err_return;
1945 Py_DECREF(co);
1946 Py_DECREF(m);
1947 return 1;
1948 err_return:
1949 Py_DECREF(co);
1950 return -1;
1954 /* Import a module, either built-in, frozen, or external, and return
1955 its module object WITH INCREMENTED REFERENCE COUNT */
1957 PyObject *
1958 PyImport_ImportModule(const char *name)
1960 PyObject *pname;
1961 PyObject *result;
1963 pname = PyString_FromString(name);
1964 if (pname == NULL)
1965 return NULL;
1966 result = PyImport_Import(pname);
1967 Py_DECREF(pname);
1968 return result;
1971 /* Forward declarations for helper routines */
1972 static PyObject *get_parent(PyObject *globals, char *buf,
1973 Py_ssize_t *p_buflen, int level);
1974 static PyObject *load_next(PyObject *mod, PyObject *altmod,
1975 char **p_name, char *buf, Py_ssize_t *p_buflen);
1976 static int mark_miss(char *name);
1977 static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1978 char *buf, Py_ssize_t buflen, int recursive);
1979 static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
1981 /* The Magnum Opus of dotted-name import :-) */
1983 static PyObject *
1984 import_module_level(char *name, PyObject *globals, PyObject *locals,
1985 PyObject *fromlist, int level)
1987 char buf[MAXPATHLEN+1];
1988 Py_ssize_t buflen = 0;
1989 PyObject *parent, *head, *next, *tail;
1991 parent = get_parent(globals, buf, &buflen, level);
1992 if (parent == NULL)
1993 return NULL;
1995 head = load_next(parent, Py_None, &name, buf, &buflen);
1996 if (head == NULL)
1997 return NULL;
1999 tail = head;
2000 Py_INCREF(tail);
2001 while (name) {
2002 next = load_next(tail, tail, &name, buf, &buflen);
2003 Py_DECREF(tail);
2004 if (next == NULL) {
2005 Py_DECREF(head);
2006 return NULL;
2008 tail = next;
2010 if (tail == Py_None) {
2011 /* If tail is Py_None, both get_parent and load_next found
2012 an empty module name: someone called __import__("") or
2013 doctored faulty bytecode */
2014 Py_DECREF(tail);
2015 Py_DECREF(head);
2016 PyErr_SetString(PyExc_ValueError,
2017 "Empty module name");
2018 return NULL;
2021 if (fromlist != NULL) {
2022 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2023 fromlist = NULL;
2026 if (fromlist == NULL) {
2027 Py_DECREF(tail);
2028 return head;
2031 Py_DECREF(head);
2032 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2033 Py_DECREF(tail);
2034 return NULL;
2037 return tail;
2040 /* For DLL compatibility */
2041 #undef PyImport_ImportModuleEx
2042 PyObject *
2043 PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
2044 PyObject *fromlist)
2046 PyObject *result;
2047 lock_import();
2048 result = import_module_level(name, globals, locals, fromlist, -1);
2049 if (unlock_import() < 0) {
2050 Py_XDECREF(result);
2051 PyErr_SetString(PyExc_RuntimeError,
2052 "not holding the import lock");
2053 return NULL;
2055 return result;
2057 #define PyImport_ImportModuleEx(n, g, l, f) \
2058 PyImport_ImportModuleLevel(n, g, l, f, -1);
2060 PyObject *
2061 PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2062 PyObject *fromlist, int level)
2064 PyObject *result;
2065 lock_import();
2066 result = import_module_level(name, globals, locals, fromlist, level);
2067 if (unlock_import() < 0) {
2068 Py_XDECREF(result);
2069 PyErr_SetString(PyExc_RuntimeError,
2070 "not holding the import lock");
2071 return NULL;
2073 return result;
2076 /* Return the package that an import is being performed in. If globals comes
2077 from the module foo.bar.bat (not itself a package), this returns the
2078 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
2079 the package's entry in sys.modules is returned, as a borrowed reference.
2081 The *name* of the returned package is returned in buf, with the length of
2082 the name in *p_buflen.
2084 If globals doesn't come from a package or a module in a package, or a
2085 corresponding entry is not found in sys.modules, Py_None is returned.
2087 static PyObject *
2088 get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
2090 static PyObject *namestr = NULL;
2091 static PyObject *pathstr = NULL;
2092 PyObject *modname, *modpath, *modules, *parent;
2094 if (globals == NULL || !PyDict_Check(globals) || !level)
2095 return Py_None;
2097 if (namestr == NULL) {
2098 namestr = PyString_InternFromString("__name__");
2099 if (namestr == NULL)
2100 return NULL;
2102 if (pathstr == NULL) {
2103 pathstr = PyString_InternFromString("__path__");
2104 if (pathstr == NULL)
2105 return NULL;
2108 *buf = '\0';
2109 *p_buflen = 0;
2110 modname = PyDict_GetItem(globals, namestr);
2111 if (modname == NULL || !PyString_Check(modname))
2112 return Py_None;
2114 modpath = PyDict_GetItem(globals, pathstr);
2115 if (modpath != NULL) {
2116 Py_ssize_t len = PyString_GET_SIZE(modname);
2117 if (len > MAXPATHLEN) {
2118 PyErr_SetString(PyExc_ValueError,
2119 "Module name too long");
2120 return NULL;
2122 strcpy(buf, PyString_AS_STRING(modname));
2124 else {
2125 char *start = PyString_AS_STRING(modname);
2126 char *lastdot = strrchr(start, '.');
2127 size_t len;
2128 if (lastdot == NULL && level > 0) {
2129 PyErr_SetString(PyExc_ValueError,
2130 "Attempted relative import in non-package");
2131 return NULL;
2133 if (lastdot == NULL)
2134 return Py_None;
2135 len = lastdot - start;
2136 if (len >= MAXPATHLEN) {
2137 PyErr_SetString(PyExc_ValueError,
2138 "Module name too long");
2139 return NULL;
2141 strncpy(buf, start, len);
2142 buf[len] = '\0';
2145 while (--level > 0) {
2146 char *dot = strrchr(buf, '.');
2147 if (dot == NULL) {
2148 PyErr_SetString(PyExc_ValueError,
2149 "Attempted relative import beyond "
2150 "toplevel package");
2151 return NULL;
2153 *dot = '\0';
2155 *p_buflen = strlen(buf);
2157 modules = PyImport_GetModuleDict();
2158 parent = PyDict_GetItemString(modules, buf);
2159 if (parent == NULL)
2160 PyErr_Format(PyExc_SystemError,
2161 "Parent module '%.200s' not loaded", buf);
2162 return parent;
2163 /* We expect, but can't guarantee, if parent != None, that:
2164 - parent.__name__ == buf
2165 - parent.__dict__ is globals
2166 If this is violated... Who cares? */
2169 /* altmod is either None or same as mod */
2170 static PyObject *
2171 load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
2172 Py_ssize_t *p_buflen)
2174 char *name = *p_name;
2175 char *dot = strchr(name, '.');
2176 size_t len;
2177 char *p;
2178 PyObject *result;
2180 if (strlen(name) == 0) {
2181 /* completely empty module name should only happen in
2182 'from . import' (or '__import__("")')*/
2183 Py_INCREF(mod);
2184 *p_name = NULL;
2185 return mod;
2188 if (dot == NULL) {
2189 *p_name = NULL;
2190 len = strlen(name);
2192 else {
2193 *p_name = dot+1;
2194 len = dot-name;
2196 if (len == 0) {
2197 PyErr_SetString(PyExc_ValueError,
2198 "Empty module name");
2199 return NULL;
2202 p = buf + *p_buflen;
2203 if (p != buf)
2204 *p++ = '.';
2205 if (p+len-buf >= MAXPATHLEN) {
2206 PyErr_SetString(PyExc_ValueError,
2207 "Module name too long");
2208 return NULL;
2210 strncpy(p, name, len);
2211 p[len] = '\0';
2212 *p_buflen = p+len-buf;
2214 result = import_submodule(mod, p, buf);
2215 if (result == Py_None && altmod != mod) {
2216 Py_DECREF(result);
2217 /* Here, altmod must be None and mod must not be None */
2218 result = import_submodule(altmod, p, p);
2219 if (result != NULL && result != Py_None) {
2220 if (mark_miss(buf) != 0) {
2221 Py_DECREF(result);
2222 return NULL;
2224 strncpy(buf, name, len);
2225 buf[len] = '\0';
2226 *p_buflen = len;
2229 if (result == NULL)
2230 return NULL;
2232 if (result == Py_None) {
2233 Py_DECREF(result);
2234 PyErr_Format(PyExc_ImportError,
2235 "No module named %.200s", name);
2236 return NULL;
2239 return result;
2242 static int
2243 mark_miss(char *name)
2245 PyObject *modules = PyImport_GetModuleDict();
2246 return PyDict_SetItemString(modules, name, Py_None);
2249 static int
2250 ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
2251 int recursive)
2253 int i;
2255 if (!PyObject_HasAttrString(mod, "__path__"))
2256 return 1;
2258 for (i = 0; ; i++) {
2259 PyObject *item = PySequence_GetItem(fromlist, i);
2260 int hasit;
2261 if (item == NULL) {
2262 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2263 PyErr_Clear();
2264 return 1;
2266 return 0;
2268 if (!PyString_Check(item)) {
2269 PyErr_SetString(PyExc_TypeError,
2270 "Item in ``from list'' not a string");
2271 Py_DECREF(item);
2272 return 0;
2274 if (PyString_AS_STRING(item)[0] == '*') {
2275 PyObject *all;
2276 Py_DECREF(item);
2277 /* See if the package defines __all__ */
2278 if (recursive)
2279 continue; /* Avoid endless recursion */
2280 all = PyObject_GetAttrString(mod, "__all__");
2281 if (all == NULL)
2282 PyErr_Clear();
2283 else {
2284 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2285 Py_DECREF(all);
2286 if (!ret)
2287 return 0;
2289 continue;
2291 hasit = PyObject_HasAttr(mod, item);
2292 if (!hasit) {
2293 char *subname = PyString_AS_STRING(item);
2294 PyObject *submod;
2295 char *p;
2296 if (buflen + strlen(subname) >= MAXPATHLEN) {
2297 PyErr_SetString(PyExc_ValueError,
2298 "Module name too long");
2299 Py_DECREF(item);
2300 return 0;
2302 p = buf + buflen;
2303 *p++ = '.';
2304 strcpy(p, subname);
2305 submod = import_submodule(mod, subname, buf);
2306 Py_XDECREF(submod);
2307 if (submod == NULL) {
2308 Py_DECREF(item);
2309 return 0;
2312 Py_DECREF(item);
2315 /* NOTREACHED */
2318 static int
2319 add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2320 PyObject *modules)
2322 if (mod == Py_None)
2323 return 1;
2324 /* Irrespective of the success of this load, make a
2325 reference to it in the parent package module. A copy gets
2326 saved in the modules dictionary under the full name, so get a
2327 reference from there, if need be. (The exception is when the
2328 load failed with a SyntaxError -- then there's no trace in
2329 sys.modules. In that case, of course, do nothing extra.) */
2330 if (submod == NULL) {
2331 submod = PyDict_GetItemString(modules, fullname);
2332 if (submod == NULL)
2333 return 1;
2335 if (PyModule_Check(mod)) {
2336 /* We can't use setattr here since it can give a
2337 * spurious warning if the submodule name shadows a
2338 * builtin name */
2339 PyObject *dict = PyModule_GetDict(mod);
2340 if (!dict)
2341 return 0;
2342 if (PyDict_SetItemString(dict, subname, submod) < 0)
2343 return 0;
2345 else {
2346 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2347 return 0;
2349 return 1;
2352 static PyObject *
2353 import_submodule(PyObject *mod, char *subname, char *fullname)
2355 PyObject *modules = PyImport_GetModuleDict();
2356 PyObject *m = NULL;
2358 /* Require:
2359 if mod == None: subname == fullname
2360 else: mod.__name__ + "." + subname == fullname
2363 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2364 Py_INCREF(m);
2366 else {
2367 PyObject *path, *loader = NULL;
2368 char buf[MAXPATHLEN+1];
2369 struct filedescr *fdp;
2370 FILE *fp = NULL;
2372 if (mod == Py_None)
2373 path = NULL;
2374 else {
2375 path = PyObject_GetAttrString(mod, "__path__");
2376 if (path == NULL) {
2377 PyErr_Clear();
2378 Py_INCREF(Py_None);
2379 return Py_None;
2383 buf[0] = '\0';
2384 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2385 &fp, &loader);
2386 Py_XDECREF(path);
2387 if (fdp == NULL) {
2388 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2389 return NULL;
2390 PyErr_Clear();
2391 Py_INCREF(Py_None);
2392 return Py_None;
2394 m = load_module(fullname, fp, buf, fdp->type, loader);
2395 Py_XDECREF(loader);
2396 if (fp)
2397 fclose(fp);
2398 if (!add_submodule(mod, m, fullname, subname, modules)) {
2399 Py_XDECREF(m);
2400 m = NULL;
2404 return m;
2408 /* Re-import a module of any kind and return its module object, WITH
2409 INCREMENTED REFERENCE COUNT */
2411 PyObject *
2412 PyImport_ReloadModule(PyObject *m)
2414 PyInterpreterState *interp = PyThreadState_Get()->interp;
2415 PyObject *modules_reloading = interp->modules_reloading;
2416 PyObject *modules = PyImport_GetModuleDict();
2417 PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
2418 char *name, *subname;
2419 char buf[MAXPATHLEN+1];
2420 struct filedescr *fdp;
2421 FILE *fp = NULL;
2422 PyObject *newm;
2424 if (modules_reloading == NULL) {
2425 Py_FatalError("PyImport_ReloadModule: "
2426 "no modules_reloading dictionary!");
2427 return NULL;
2430 if (m == NULL || !PyModule_Check(m)) {
2431 PyErr_SetString(PyExc_TypeError,
2432 "reload() argument must be module");
2433 return NULL;
2435 name = PyModule_GetName(m);
2436 if (name == NULL)
2437 return NULL;
2438 if (m != PyDict_GetItemString(modules, name)) {
2439 PyErr_Format(PyExc_ImportError,
2440 "reload(): module %.200s not in sys.modules",
2441 name);
2442 return NULL;
2444 existing_m = PyDict_GetItemString(modules_reloading, name);
2445 if (existing_m != NULL) {
2446 /* Due to a recursive reload, this module is already
2447 being reloaded. */
2448 Py_INCREF(existing_m);
2449 return existing_m;
2451 if (PyDict_SetItemString(modules_reloading, name, m) < 0)
2452 return NULL;
2454 subname = strrchr(name, '.');
2455 if (subname == NULL)
2456 subname = name;
2457 else {
2458 PyObject *parentname, *parent;
2459 parentname = PyString_FromStringAndSize(name, (subname-name));
2460 if (parentname == NULL) {
2461 imp_modules_reloading_clear();
2462 return NULL;
2464 parent = PyDict_GetItem(modules, parentname);
2465 if (parent == NULL) {
2466 PyErr_Format(PyExc_ImportError,
2467 "reload(): parent %.200s not in sys.modules",
2468 PyString_AS_STRING(parentname));
2469 Py_DECREF(parentname);
2470 imp_modules_reloading_clear();
2471 return NULL;
2473 Py_DECREF(parentname);
2474 subname++;
2475 path = PyObject_GetAttrString(parent, "__path__");
2476 if (path == NULL)
2477 PyErr_Clear();
2479 buf[0] = '\0';
2480 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2481 Py_XDECREF(path);
2483 if (fdp == NULL) {
2484 Py_XDECREF(loader);
2485 imp_modules_reloading_clear();
2486 return NULL;
2489 newm = load_module(name, fp, buf, fdp->type, loader);
2490 Py_XDECREF(loader);
2492 if (fp)
2493 fclose(fp);
2494 if (newm == NULL) {
2495 /* load_module probably removed name from modules because of
2496 * the error. Put back the original module object. We're
2497 * going to return NULL in this case regardless of whether
2498 * replacing name succeeds, so the return value is ignored.
2500 PyDict_SetItemString(modules, name, m);
2502 imp_modules_reloading_clear();
2503 return newm;
2507 /* Higher-level import emulator which emulates the "import" statement
2508 more accurately -- it invokes the __import__() function from the
2509 builtins of the current globals. This means that the import is
2510 done using whatever import hooks are installed in the current
2511 environment, e.g. by "rexec".
2512 A dummy list ["__doc__"] is passed as the 4th argument so that
2513 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2514 will return <module "gencache"> instead of <module "win32com">. */
2516 PyObject *
2517 PyImport_Import(PyObject *module_name)
2519 static PyObject *silly_list = NULL;
2520 static PyObject *builtins_str = NULL;
2521 static PyObject *import_str = NULL;
2522 PyObject *globals = NULL;
2523 PyObject *import = NULL;
2524 PyObject *builtins = NULL;
2525 PyObject *r = NULL;
2527 /* Initialize constant string objects */
2528 if (silly_list == NULL) {
2529 import_str = PyString_InternFromString("__import__");
2530 if (import_str == NULL)
2531 return NULL;
2532 builtins_str = PyString_InternFromString("__builtins__");
2533 if (builtins_str == NULL)
2534 return NULL;
2535 silly_list = Py_BuildValue("[s]", "__doc__");
2536 if (silly_list == NULL)
2537 return NULL;
2540 /* Get the builtins from current globals */
2541 globals = PyEval_GetGlobals();
2542 if (globals != NULL) {
2543 Py_INCREF(globals);
2544 builtins = PyObject_GetItem(globals, builtins_str);
2545 if (builtins == NULL)
2546 goto err;
2548 else {
2549 /* No globals -- use standard builtins, and fake globals */
2550 PyErr_Clear();
2552 builtins = PyImport_ImportModuleLevel("__builtin__",
2553 NULL, NULL, NULL, 0);
2554 if (builtins == NULL)
2555 return NULL;
2556 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2557 if (globals == NULL)
2558 goto err;
2561 /* Get the __import__ function from the builtins */
2562 if (PyDict_Check(builtins)) {
2563 import = PyObject_GetItem(builtins, import_str);
2564 if (import == NULL)
2565 PyErr_SetObject(PyExc_KeyError, import_str);
2567 else
2568 import = PyObject_GetAttr(builtins, import_str);
2569 if (import == NULL)
2570 goto err;
2572 /* Call the __import__ function with the proper argument list */
2573 r = PyObject_CallFunctionObjArgs(import, module_name, globals,
2574 globals, silly_list, NULL);
2576 err:
2577 Py_XDECREF(globals);
2578 Py_XDECREF(builtins);
2579 Py_XDECREF(import);
2581 return r;
2585 /* Module 'imp' provides Python access to the primitives used for
2586 importing modules.
2589 static PyObject *
2590 imp_get_magic(PyObject *self, PyObject *noargs)
2592 char buf[4];
2594 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2595 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2596 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2597 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
2599 return PyString_FromStringAndSize(buf, 4);
2602 static PyObject *
2603 imp_get_suffixes(PyObject *self, PyObject *noargs)
2605 PyObject *list;
2606 struct filedescr *fdp;
2608 list = PyList_New(0);
2609 if (list == NULL)
2610 return NULL;
2611 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2612 PyObject *item = Py_BuildValue("ssi",
2613 fdp->suffix, fdp->mode, fdp->type);
2614 if (item == NULL) {
2615 Py_DECREF(list);
2616 return NULL;
2618 if (PyList_Append(list, item) < 0) {
2619 Py_DECREF(list);
2620 Py_DECREF(item);
2621 return NULL;
2623 Py_DECREF(item);
2625 return list;
2628 static PyObject *
2629 call_find_module(char *name, PyObject *path)
2631 extern int fclose(FILE *);
2632 PyObject *fob, *ret;
2633 struct filedescr *fdp;
2634 char pathname[MAXPATHLEN+1];
2635 FILE *fp = NULL;
2637 pathname[0] = '\0';
2638 if (path == Py_None)
2639 path = NULL;
2640 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
2641 if (fdp == NULL)
2642 return NULL;
2643 if (fp != NULL) {
2644 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2645 if (fob == NULL) {
2646 fclose(fp);
2647 return NULL;
2650 else {
2651 fob = Py_None;
2652 Py_INCREF(fob);
2654 ret = Py_BuildValue("Os(ssi)",
2655 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
2656 Py_DECREF(fob);
2657 return ret;
2660 static PyObject *
2661 imp_find_module(PyObject *self, PyObject *args)
2663 char *name;
2664 PyObject *path = NULL;
2665 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
2666 return NULL;
2667 return call_find_module(name, path);
2670 static PyObject *
2671 imp_init_builtin(PyObject *self, PyObject *args)
2673 char *name;
2674 int ret;
2675 PyObject *m;
2676 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
2677 return NULL;
2678 ret = init_builtin(name);
2679 if (ret < 0)
2680 return NULL;
2681 if (ret == 0) {
2682 Py_INCREF(Py_None);
2683 return Py_None;
2685 m = PyImport_AddModule(name);
2686 Py_XINCREF(m);
2687 return m;
2690 static PyObject *
2691 imp_init_frozen(PyObject *self, PyObject *args)
2693 char *name;
2694 int ret;
2695 PyObject *m;
2696 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
2697 return NULL;
2698 ret = PyImport_ImportFrozenModule(name);
2699 if (ret < 0)
2700 return NULL;
2701 if (ret == 0) {
2702 Py_INCREF(Py_None);
2703 return Py_None;
2705 m = PyImport_AddModule(name);
2706 Py_XINCREF(m);
2707 return m;
2710 static PyObject *
2711 imp_get_frozen_object(PyObject *self, PyObject *args)
2713 char *name;
2715 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2716 return NULL;
2717 return get_frozen_object(name);
2720 static PyObject *
2721 imp_is_builtin(PyObject *self, PyObject *args)
2723 char *name;
2724 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2725 return NULL;
2726 return PyInt_FromLong(is_builtin(name));
2729 static PyObject *
2730 imp_is_frozen(PyObject *self, PyObject *args)
2732 char *name;
2733 struct _frozen *p;
2734 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
2735 return NULL;
2736 p = find_frozen(name);
2737 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
2740 static FILE *
2741 get_file(char *pathname, PyObject *fob, char *mode)
2743 FILE *fp;
2744 if (fob == NULL) {
2745 if (mode[0] == 'U')
2746 mode = "r" PY_STDIOTEXTMODE;
2747 fp = fopen(pathname, mode);
2748 if (fp == NULL)
2749 PyErr_SetFromErrno(PyExc_IOError);
2751 else {
2752 fp = PyFile_AsFile(fob);
2753 if (fp == NULL)
2754 PyErr_SetString(PyExc_ValueError,
2755 "bad/closed file object");
2757 return fp;
2760 static PyObject *
2761 imp_load_compiled(PyObject *self, PyObject *args)
2763 char *name;
2764 char *pathname;
2765 PyObject *fob = NULL;
2766 PyObject *m;
2767 FILE *fp;
2768 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
2769 &PyFile_Type, &fob))
2770 return NULL;
2771 fp = get_file(pathname, fob, "rb");
2772 if (fp == NULL)
2773 return NULL;
2774 m = load_compiled_module(name, pathname, fp);
2775 if (fob == NULL)
2776 fclose(fp);
2777 return m;
2780 #ifdef HAVE_DYNAMIC_LOADING
2782 static PyObject *
2783 imp_load_dynamic(PyObject *self, PyObject *args)
2785 char *name;
2786 char *pathname;
2787 PyObject *fob = NULL;
2788 PyObject *m;
2789 FILE *fp = NULL;
2790 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
2791 &PyFile_Type, &fob))
2792 return NULL;
2793 if (fob) {
2794 fp = get_file(pathname, fob, "r");
2795 if (fp == NULL)
2796 return NULL;
2798 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2799 return m;
2802 #endif /* HAVE_DYNAMIC_LOADING */
2804 static PyObject *
2805 imp_load_source(PyObject *self, PyObject *args)
2807 char *name;
2808 char *pathname;
2809 PyObject *fob = NULL;
2810 PyObject *m;
2811 FILE *fp;
2812 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
2813 &PyFile_Type, &fob))
2814 return NULL;
2815 fp = get_file(pathname, fob, "r");
2816 if (fp == NULL)
2817 return NULL;
2818 m = load_source_module(name, pathname, fp);
2819 if (fob == NULL)
2820 fclose(fp);
2821 return m;
2824 static PyObject *
2825 imp_load_module(PyObject *self, PyObject *args)
2827 char *name;
2828 PyObject *fob;
2829 char *pathname;
2830 char *suffix; /* Unused */
2831 char *mode;
2832 int type;
2833 FILE *fp;
2835 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
2836 &name, &fob, &pathname,
2837 &suffix, &mode, &type))
2838 return NULL;
2839 if (*mode) {
2840 /* Mode must start with 'r' or 'U' and must not contain '+'.
2841 Implicit in this test is the assumption that the mode
2842 may contain other modifiers like 'b' or 't'. */
2844 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
2845 PyErr_Format(PyExc_ValueError,
2846 "invalid file open mode %.200s", mode);
2847 return NULL;
2850 if (fob == Py_None)
2851 fp = NULL;
2852 else {
2853 if (!PyFile_Check(fob)) {
2854 PyErr_SetString(PyExc_ValueError,
2855 "load_module arg#2 should be a file or None");
2856 return NULL;
2858 fp = get_file(pathname, fob, mode);
2859 if (fp == NULL)
2860 return NULL;
2862 return load_module(name, fp, pathname, type, NULL);
2865 static PyObject *
2866 imp_load_package(PyObject *self, PyObject *args)
2868 char *name;
2869 char *pathname;
2870 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
2871 return NULL;
2872 return load_package(name, pathname);
2875 static PyObject *
2876 imp_new_module(PyObject *self, PyObject *args)
2878 char *name;
2879 if (!PyArg_ParseTuple(args, "s:new_module", &name))
2880 return NULL;
2881 return PyModule_New(name);
2884 /* Doc strings */
2886 PyDoc_STRVAR(doc_imp,
2887 "This module provides the components needed to build your own\n\
2888 __import__ function. Undocumented functions are obsolete.");
2890 PyDoc_STRVAR(doc_find_module,
2891 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2892 Search for a module. If path is omitted or None, search for a\n\
2893 built-in, frozen or special module and continue search in sys.path.\n\
2894 The module name cannot contain '.'; to search for a submodule of a\n\
2895 package, pass the submodule name and the package's __path__.");
2897 PyDoc_STRVAR(doc_load_module,
2898 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2899 Load a module, given information returned by find_module().\n\
2900 The module name must include the full package name, if any.");
2902 PyDoc_STRVAR(doc_get_magic,
2903 "get_magic() -> string\n\
2904 Return the magic number for .pyc or .pyo files.");
2906 PyDoc_STRVAR(doc_get_suffixes,
2907 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2908 Return a list of (suffix, mode, type) tuples describing the files\n\
2909 that find_module() looks for.");
2911 PyDoc_STRVAR(doc_new_module,
2912 "new_module(name) -> module\n\
2913 Create a new module. Do not enter it in sys.modules.\n\
2914 The module name must include the full package name, if any.");
2916 PyDoc_STRVAR(doc_lock_held,
2917 "lock_held() -> boolean\n\
2918 Return True if the import lock is currently held, else False.\n\
2919 On platforms without threads, return False.");
2921 PyDoc_STRVAR(doc_acquire_lock,
2922 "acquire_lock() -> None\n\
2923 Acquires the interpreter's import lock for the current thread.\n\
2924 This lock should be used by import hooks to ensure thread-safety\n\
2925 when importing modules.\n\
2926 On platforms without threads, this function does nothing.");
2928 PyDoc_STRVAR(doc_release_lock,
2929 "release_lock() -> None\n\
2930 Release the interpreter's import lock.\n\
2931 On platforms without threads, this function does nothing.");
2933 static PyMethodDef imp_methods[] = {
2934 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2935 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2936 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2937 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2938 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2939 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2940 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2941 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
2942 /* The rest are obsolete */
2943 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2944 {"init_builtin", imp_init_builtin, METH_VARARGS},
2945 {"init_frozen", imp_init_frozen, METH_VARARGS},
2946 {"is_builtin", imp_is_builtin, METH_VARARGS},
2947 {"is_frozen", imp_is_frozen, METH_VARARGS},
2948 {"load_compiled", imp_load_compiled, METH_VARARGS},
2949 #ifdef HAVE_DYNAMIC_LOADING
2950 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
2951 #endif
2952 {"load_package", imp_load_package, METH_VARARGS},
2953 {"load_source", imp_load_source, METH_VARARGS},
2954 {NULL, NULL} /* sentinel */
2957 static int
2958 setint(PyObject *d, char *name, int value)
2960 PyObject *v;
2961 int err;
2963 v = PyInt_FromLong((long)value);
2964 err = PyDict_SetItemString(d, name, v);
2965 Py_XDECREF(v);
2966 return err;
2969 typedef struct {
2970 PyObject_HEAD
2971 } NullImporter;
2973 static int
2974 NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
2976 char *path;
2978 if (!_PyArg_NoKeywords("NullImporter()", kwds))
2979 return -1;
2981 if (!PyArg_ParseTuple(args, "s:NullImporter",
2982 &path))
2983 return -1;
2985 if (strlen(path) == 0) {
2986 PyErr_SetString(PyExc_ImportError, "empty pathname");
2987 return -1;
2988 } else {
2989 #ifndef RISCOS
2990 struct stat statbuf;
2991 int rv;
2993 rv = stat(path, &statbuf);
2994 if (rv == 0) {
2995 /* it exists */
2996 if (S_ISDIR(statbuf.st_mode)) {
2997 /* it's a directory */
2998 PyErr_SetString(PyExc_ImportError,
2999 "existing directory");
3000 return -1;
3003 #else
3004 if (object_exists(path)) {
3005 /* it exists */
3006 if (isdir(path)) {
3007 /* it's a directory */
3008 PyErr_SetString(PyExc_ImportError,
3009 "existing directory");
3010 return -1;
3013 #endif
3015 return 0;
3018 static PyObject *
3019 NullImporter_find_module(NullImporter *self, PyObject *args)
3021 Py_RETURN_NONE;
3024 static PyMethodDef NullImporter_methods[] = {
3025 {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
3026 "Always return None"
3028 {NULL} /* Sentinel */
3032 static PyTypeObject NullImporterType = {
3033 PyObject_HEAD_INIT(NULL)
3034 0, /*ob_size*/
3035 "imp.NullImporter", /*tp_name*/
3036 sizeof(NullImporter), /*tp_basicsize*/
3037 0, /*tp_itemsize*/
3038 0, /*tp_dealloc*/
3039 0, /*tp_print*/
3040 0, /*tp_getattr*/
3041 0, /*tp_setattr*/
3042 0, /*tp_compare*/
3043 0, /*tp_repr*/
3044 0, /*tp_as_number*/
3045 0, /*tp_as_sequence*/
3046 0, /*tp_as_mapping*/
3047 0, /*tp_hash */
3048 0, /*tp_call*/
3049 0, /*tp_str*/
3050 0, /*tp_getattro*/
3051 0, /*tp_setattro*/
3052 0, /*tp_as_buffer*/
3053 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3054 "Null importer object", /* tp_doc */
3055 0, /* tp_traverse */
3056 0, /* tp_clear */
3057 0, /* tp_richcompare */
3058 0, /* tp_weaklistoffset */
3059 0, /* tp_iter */
3060 0, /* tp_iternext */
3061 NullImporter_methods, /* tp_methods */
3062 0, /* tp_members */
3063 0, /* tp_getset */
3064 0, /* tp_base */
3065 0, /* tp_dict */
3066 0, /* tp_descr_get */
3067 0, /* tp_descr_set */
3068 0, /* tp_dictoffset */
3069 (initproc)NullImporter_init, /* tp_init */
3070 0, /* tp_alloc */
3071 PyType_GenericNew /* tp_new */
3075 PyMODINIT_FUNC
3076 initimp(void)
3078 PyObject *m, *d;
3080 if (PyType_Ready(&NullImporterType) < 0)
3081 goto failure;
3083 m = Py_InitModule4("imp", imp_methods, doc_imp,
3084 NULL, PYTHON_API_VERSION);
3085 if (m == NULL)
3086 goto failure;
3087 d = PyModule_GetDict(m);
3088 if (d == NULL)
3089 goto failure;
3091 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
3092 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
3093 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
3094 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
3095 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
3096 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
3097 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
3098 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
3099 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
3100 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
3102 Py_INCREF(&NullImporterType);
3103 PyModule_AddObject(m, "NullImporter", (PyObject *)&NullImporterType);
3104 failure:
3109 /* API for embedding applications that want to add their own entries
3110 to the table of built-in modules. This should normally be called
3111 *before* Py_Initialize(). When the table resize fails, -1 is
3112 returned and the existing table is unchanged.
3114 After a similar function by Just van Rossum. */
3117 PyImport_ExtendInittab(struct _inittab *newtab)
3119 static struct _inittab *our_copy = NULL;
3120 struct _inittab *p;
3121 int i, n;
3123 /* Count the number of entries in both tables */
3124 for (n = 0; newtab[n].name != NULL; n++)
3126 if (n == 0)
3127 return 0; /* Nothing to do */
3128 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
3131 /* Allocate new memory for the combined table */
3132 p = our_copy;
3133 PyMem_RESIZE(p, struct _inittab, i+n+1);
3134 if (p == NULL)
3135 return -1;
3137 /* Copy the tables into the new memory */
3138 if (our_copy != PyImport_Inittab)
3139 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
3140 PyImport_Inittab = our_copy = p;
3141 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
3143 return 0;
3146 /* Shorthand to add a single entry given a name and a function */
3149 PyImport_AppendInittab(char *name, void (*initfunc)(void))
3151 struct _inittab newtab[2];
3153 memset(newtab, '\0', sizeof newtab);
3155 newtab[0].name = name;
3156 newtab[0].initfunc = initfunc;
3158 return PyImport_ExtendInittab(newtab);
3161 #ifdef __cplusplus
3163 #endif