Add missing period in comment.
[python.git] / Python / import.c
blobc49a91fc6a6ba02bbca83f9ac3daba604a5978a1
2 /* Module definition and import implementation */
4 #include "Python.h"
6 #include "Python-ast.h"
7 #include "pyarena.h"
8 #include "pythonrun.h"
9 #include "errcode.h"
10 #include "marshal.h"
11 #include "code.h"
12 #include "compile.h"
13 #include "eval.h"
14 #include "osdefs.h"
15 #include "importdl.h"
17 #ifdef HAVE_FCNTL_H
18 #include <fcntl.h>
19 #endif
20 #ifdef __cplusplus
21 extern "C" {
22 #endif
24 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
25 /* In getmtime.c */
27 /* Magic word to reject .pyc files generated by other Python versions.
28 It should change for each incompatible change to the bytecode.
30 The value of CR and LF is incorporated so if you ever read or write
31 a .pyc file in text mode the magic number will be wrong; also, the
32 Apple MPW compiler swaps their values, botching string constants.
34 The magic numbers must be spaced apart atleast 2 values, as the
35 -U interpeter flag will cause MAGIC+1 being used. They have been
36 odd numbers for some time now.
38 There were a variety of old schemes for setting the magic number.
39 The current working scheme is to increment the previous value by
40 10.
42 Known values:
43 Python 1.5: 20121
44 Python 1.5.1: 20121
45 Python 1.5.2: 20121
46 Python 1.6: 50428
47 Python 2.0: 50823
48 Python 2.0.1: 50823
49 Python 2.1: 60202
50 Python 2.1.1: 60202
51 Python 2.1.2: 60202
52 Python 2.2: 60717
53 Python 2.3a0: 62011
54 Python 2.3a0: 62021
55 Python 2.3a0: 62011 (!)
56 Python 2.4a0: 62041
57 Python 2.4a3: 62051
58 Python 2.4b1: 62061
59 Python 2.5a0: 62071
60 Python 2.5a0: 62081 (ast-branch)
61 Python 2.5a0: 62091 (with)
62 Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
65 #define MAGIC (62092 | ((long)'\r'<<16) | ((long)'\n'<<24))
67 /* Magic word as global; note that _PyImport_Init() can change the
68 value of this global to accommodate for alterations of how the
69 compiler works which are enabled by command line switches. */
70 static long pyc_magic = MAGIC;
72 /* See _PyImport_FixupExtension() below */
73 static PyObject *extensions = NULL;
75 /* This table is defined in config.c: */
76 extern struct _inittab _PyImport_Inittab[];
78 struct _inittab *PyImport_Inittab = _PyImport_Inittab;
80 /* these tables define the module suffixes that Python recognizes */
81 struct filedescr * _PyImport_Filetab = NULL;
83 #ifdef RISCOS
84 static const struct filedescr _PyImport_StandardFiletab[] = {
85 {"/py", "U", PY_SOURCE},
86 {"/pyc", "rb", PY_COMPILED},
87 {0, 0}
89 #else
90 static const struct filedescr _PyImport_StandardFiletab[] = {
91 {".py", "U", PY_SOURCE},
92 #ifdef MS_WINDOWS
93 {".pyw", "U", PY_SOURCE},
94 #endif
95 {".pyc", "rb", PY_COMPILED},
96 {0, 0}
98 #endif
100 /* Initialize things */
102 void
103 _PyImport_Init(void)
105 const struct filedescr *scan;
106 struct filedescr *filetab;
107 int countD = 0;
108 int countS = 0;
110 /* prepare _PyImport_Filetab: copy entries from
111 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
113 for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
114 ++countD;
115 for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
116 ++countS;
117 filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
118 memcpy(filetab, _PyImport_DynLoadFiletab,
119 countD * sizeof(struct filedescr));
120 memcpy(filetab + countD, _PyImport_StandardFiletab,
121 countS * sizeof(struct filedescr));
122 filetab[countD + countS].suffix = NULL;
124 _PyImport_Filetab = filetab;
126 if (Py_OptimizeFlag) {
127 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
128 for (; filetab->suffix != NULL; filetab++) {
129 #ifndef RISCOS
130 if (strcmp(filetab->suffix, ".pyc") == 0)
131 filetab->suffix = ".pyo";
132 #else
133 if (strcmp(filetab->suffix, "/pyc") == 0)
134 filetab->suffix = "/pyo";
135 #endif
139 if (Py_UnicodeFlag) {
140 /* Fix the pyc_magic so that byte compiled code created
141 using the all-Unicode method doesn't interfere with
142 code created in normal operation mode. */
143 pyc_magic = MAGIC + 1;
147 void
148 _PyImportHooks_Init(void)
150 PyObject *v, *path_hooks = NULL, *zimpimport;
151 int err = 0;
153 /* adding sys.path_hooks and sys.path_importer_cache, setting up
154 zipimport */
156 if (Py_VerboseFlag)
157 PySys_WriteStderr("# installing zipimport hook\n");
159 v = PyList_New(0);
160 if (v == NULL)
161 goto error;
162 err = PySys_SetObject("meta_path", v);
163 Py_DECREF(v);
164 if (err)
165 goto error;
166 v = PyDict_New();
167 if (v == NULL)
168 goto error;
169 err = PySys_SetObject("path_importer_cache", v);
170 Py_DECREF(v);
171 if (err)
172 goto error;
173 path_hooks = PyList_New(0);
174 if (path_hooks == NULL)
175 goto error;
176 err = PySys_SetObject("path_hooks", path_hooks);
177 if (err) {
178 error:
179 PyErr_Print();
180 Py_FatalError("initializing sys.meta_path, sys.path_hooks or "
181 "path_importer_cache failed");
183 zimpimport = PyImport_ImportModule("zipimport");
184 if (zimpimport == NULL) {
185 PyErr_Clear(); /* No zip import module -- okay */
186 if (Py_VerboseFlag)
187 PySys_WriteStderr("# can't import zipimport\n");
189 else {
190 PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
191 "zipimporter");
192 Py_DECREF(zimpimport);
193 if (zipimporter == NULL) {
194 PyErr_Clear(); /* No zipimporter object -- okay */
195 if (Py_VerboseFlag)
196 PySys_WriteStderr(
197 "# can't import zipimport.zipimporter\n");
199 else {
200 /* sys.path_hooks.append(zipimporter) */
201 err = PyList_Append(path_hooks, zipimporter);
202 Py_DECREF(zipimporter);
203 if (err)
204 goto error;
205 if (Py_VerboseFlag)
206 PySys_WriteStderr(
207 "# installed zipimport hook\n");
210 Py_DECREF(path_hooks);
213 void
214 _PyImport_Fini(void)
216 Py_XDECREF(extensions);
217 extensions = NULL;
218 PyMem_DEL(_PyImport_Filetab);
219 _PyImport_Filetab = NULL;
223 /* Locking primitives to prevent parallel imports of the same module
224 in different threads to return with a partially loaded module.
225 These calls are serialized by the global interpreter lock. */
227 #ifdef WITH_THREAD
229 #include "pythread.h"
231 static PyThread_type_lock import_lock = 0;
232 static long import_lock_thread = -1;
233 static int import_lock_level = 0;
235 static void
236 lock_import(void)
238 long me = PyThread_get_thread_ident();
239 if (me == -1)
240 return; /* Too bad */
241 if (import_lock == NULL)
242 import_lock = PyThread_allocate_lock();
243 if (import_lock_thread == me) {
244 import_lock_level++;
245 return;
247 if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
249 PyThreadState *tstate = PyEval_SaveThread();
250 PyThread_acquire_lock(import_lock, 1);
251 PyEval_RestoreThread(tstate);
253 import_lock_thread = me;
254 import_lock_level = 1;
257 static int
258 unlock_import(void)
260 long me = PyThread_get_thread_ident();
261 if (me == -1)
262 return 0; /* Too bad */
263 if (import_lock_thread != me)
264 return -1;
265 import_lock_level--;
266 if (import_lock_level == 0) {
267 import_lock_thread = -1;
268 PyThread_release_lock(import_lock);
270 return 1;
273 /* This function is called from PyOS_AfterFork to ensure that newly
274 created child processes do not share locks with the parent. */
276 void
277 _PyImport_ReInitLock(void)
279 #ifdef _AIX
280 if (import_lock != NULL)
281 import_lock = PyThread_allocate_lock();
282 #endif
285 #else
287 #define lock_import()
288 #define unlock_import() 0
290 #endif
292 static PyObject *
293 imp_lock_held(PyObject *self, PyObject *noargs)
295 #ifdef WITH_THREAD
296 return PyBool_FromLong(import_lock_thread != -1);
297 #else
298 return PyBool_FromLong(0);
299 #endif
302 static PyObject *
303 imp_acquire_lock(PyObject *self, PyObject *noargs)
305 #ifdef WITH_THREAD
306 lock_import();
307 #endif
308 Py_INCREF(Py_None);
309 return Py_None;
312 static PyObject *
313 imp_release_lock(PyObject *self, PyObject *noargs)
315 #ifdef WITH_THREAD
316 if (unlock_import() < 0) {
317 PyErr_SetString(PyExc_RuntimeError,
318 "not holding the import lock");
319 return NULL;
321 #endif
322 Py_INCREF(Py_None);
323 return Py_None;
326 /* Helper for sys */
328 PyObject *
329 PyImport_GetModuleDict(void)
331 PyInterpreterState *interp = PyThreadState_GET()->interp;
332 if (interp->modules == NULL)
333 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
334 return interp->modules;
338 /* List of names to clear in sys */
339 static char* sys_deletes[] = {
340 "path", "argv", "ps1", "ps2", "exitfunc",
341 "exc_type", "exc_value", "exc_traceback",
342 "last_type", "last_value", "last_traceback",
343 "path_hooks", "path_importer_cache", "meta_path",
344 NULL
347 static char* sys_files[] = {
348 "stdin", "__stdin__",
349 "stdout", "__stdout__",
350 "stderr", "__stderr__",
351 NULL
355 /* Un-initialize things, as good as we can */
357 void
358 PyImport_Cleanup(void)
360 Py_ssize_t pos, ndone;
361 char *name;
362 PyObject *key, *value, *dict;
363 PyInterpreterState *interp = PyThreadState_GET()->interp;
364 PyObject *modules = interp->modules;
366 if (modules == NULL)
367 return; /* Already done */
369 /* Delete some special variables first. These are common
370 places where user values hide and people complain when their
371 destructors fail. Since the modules containing them are
372 deleted *last* of all, they would come too late in the normal
373 destruction order. Sigh. */
375 value = PyDict_GetItemString(modules, "__builtin__");
376 if (value != NULL && PyModule_Check(value)) {
377 dict = PyModule_GetDict(value);
378 if (Py_VerboseFlag)
379 PySys_WriteStderr("# clear __builtin__._\n");
380 PyDict_SetItemString(dict, "_", Py_None);
382 value = PyDict_GetItemString(modules, "sys");
383 if (value != NULL && PyModule_Check(value)) {
384 char **p;
385 PyObject *v;
386 dict = PyModule_GetDict(value);
387 for (p = sys_deletes; *p != NULL; p++) {
388 if (Py_VerboseFlag)
389 PySys_WriteStderr("# clear sys.%s\n", *p);
390 PyDict_SetItemString(dict, *p, Py_None);
392 for (p = sys_files; *p != NULL; p+=2) {
393 if (Py_VerboseFlag)
394 PySys_WriteStderr("# restore sys.%s\n", *p);
395 v = PyDict_GetItemString(dict, *(p+1));
396 if (v == NULL)
397 v = Py_None;
398 PyDict_SetItemString(dict, *p, v);
402 /* First, delete __main__ */
403 value = PyDict_GetItemString(modules, "__main__");
404 if (value != NULL && PyModule_Check(value)) {
405 if (Py_VerboseFlag)
406 PySys_WriteStderr("# cleanup __main__\n");
407 _PyModule_Clear(value);
408 PyDict_SetItemString(modules, "__main__", Py_None);
411 /* The special treatment of __builtin__ here is because even
412 when it's not referenced as a module, its dictionary is
413 referenced by almost every module's __builtins__. Since
414 deleting a module clears its dictionary (even if there are
415 references left to it), we need to delete the __builtin__
416 module last. Likewise, we don't delete sys until the very
417 end because it is implicitly referenced (e.g. by print).
419 Also note that we 'delete' modules by replacing their entry
420 in the modules dict with None, rather than really deleting
421 them; this avoids a rehash of the modules dictionary and
422 also marks them as "non existent" so they won't be
423 re-imported. */
425 /* Next, repeatedly delete modules with a reference count of
426 one (skipping __builtin__ and sys) and delete them */
427 do {
428 ndone = 0;
429 pos = 0;
430 while (PyDict_Next(modules, &pos, &key, &value)) {
431 if (value->ob_refcnt != 1)
432 continue;
433 if (PyString_Check(key) && PyModule_Check(value)) {
434 name = PyString_AS_STRING(key);
435 if (strcmp(name, "__builtin__") == 0)
436 continue;
437 if (strcmp(name, "sys") == 0)
438 continue;
439 if (Py_VerboseFlag)
440 PySys_WriteStderr(
441 "# cleanup[1] %s\n", name);
442 _PyModule_Clear(value);
443 PyDict_SetItem(modules, key, Py_None);
444 ndone++;
447 } while (ndone > 0);
449 /* Next, delete all modules (still skipping __builtin__ and sys) */
450 pos = 0;
451 while (PyDict_Next(modules, &pos, &key, &value)) {
452 if (PyString_Check(key) && PyModule_Check(value)) {
453 name = PyString_AS_STRING(key);
454 if (strcmp(name, "__builtin__") == 0)
455 continue;
456 if (strcmp(name, "sys") == 0)
457 continue;
458 if (Py_VerboseFlag)
459 PySys_WriteStderr("# cleanup[2] %s\n", name);
460 _PyModule_Clear(value);
461 PyDict_SetItem(modules, key, Py_None);
465 /* Next, delete sys and __builtin__ (in that order) */
466 value = PyDict_GetItemString(modules, "sys");
467 if (value != NULL && PyModule_Check(value)) {
468 if (Py_VerboseFlag)
469 PySys_WriteStderr("# cleanup sys\n");
470 _PyModule_Clear(value);
471 PyDict_SetItemString(modules, "sys", Py_None);
473 value = PyDict_GetItemString(modules, "__builtin__");
474 if (value != NULL && PyModule_Check(value)) {
475 if (Py_VerboseFlag)
476 PySys_WriteStderr("# cleanup __builtin__\n");
477 _PyModule_Clear(value);
478 PyDict_SetItemString(modules, "__builtin__", Py_None);
481 /* Finally, clear and delete the modules directory */
482 PyDict_Clear(modules);
483 interp->modules = NULL;
484 Py_DECREF(modules);
488 /* Helper for pythonrun.c -- return magic number */
490 long
491 PyImport_GetMagicNumber(void)
493 return pyc_magic;
497 /* Magic for extension modules (built-in as well as dynamically
498 loaded). To prevent initializing an extension module more than
499 once, we keep a static dictionary 'extensions' keyed by module name
500 (for built-in modules) or by filename (for dynamically loaded
501 modules), containing these modules. A copy of the module's
502 dictionary is stored by calling _PyImport_FixupExtension()
503 immediately after the module initialization function succeeds. A
504 copy can be retrieved from there by calling
505 _PyImport_FindExtension(). */
507 PyObject *
508 _PyImport_FixupExtension(char *name, char *filename)
510 PyObject *modules, *mod, *dict, *copy;
511 if (extensions == NULL) {
512 extensions = PyDict_New();
513 if (extensions == NULL)
514 return NULL;
516 modules = PyImport_GetModuleDict();
517 mod = PyDict_GetItemString(modules, name);
518 if (mod == NULL || !PyModule_Check(mod)) {
519 PyErr_Format(PyExc_SystemError,
520 "_PyImport_FixupExtension: module %.200s not loaded", name);
521 return NULL;
523 dict = PyModule_GetDict(mod);
524 if (dict == NULL)
525 return NULL;
526 copy = PyDict_Copy(dict);
527 if (copy == NULL)
528 return NULL;
529 PyDict_SetItemString(extensions, filename, copy);
530 Py_DECREF(copy);
531 return copy;
534 PyObject *
535 _PyImport_FindExtension(char *name, char *filename)
537 PyObject *dict, *mod, *mdict;
538 if (extensions == NULL)
539 return NULL;
540 dict = PyDict_GetItemString(extensions, filename);
541 if (dict == NULL)
542 return NULL;
543 mod = PyImport_AddModule(name);
544 if (mod == NULL)
545 return NULL;
546 mdict = PyModule_GetDict(mod);
547 if (mdict == NULL)
548 return NULL;
549 if (PyDict_Update(mdict, dict))
550 return NULL;
551 if (Py_VerboseFlag)
552 PySys_WriteStderr("import %s # previously loaded (%s)\n",
553 name, filename);
554 return mod;
558 /* Get the module object corresponding to a module name.
559 First check the modules dictionary if there's one there,
560 if not, create a new one and insert it in the modules dictionary.
561 Because the former action is most common, THIS DOES NOT RETURN A
562 'NEW' REFERENCE! */
564 PyObject *
565 PyImport_AddModule(const char *name)
567 PyObject *modules = PyImport_GetModuleDict();
568 PyObject *m;
570 if ((m = PyDict_GetItemString(modules, name)) != NULL &&
571 PyModule_Check(m))
572 return m;
573 m = PyModule_New(name);
574 if (m == NULL)
575 return NULL;
576 if (PyDict_SetItemString(modules, name, m) != 0) {
577 Py_DECREF(m);
578 return NULL;
580 Py_DECREF(m); /* Yes, it still exists, in modules! */
582 return m;
585 /* Remove name from sys.modules, if it's there. */
586 static void
587 _RemoveModule(const char *name)
589 PyObject *modules = PyImport_GetModuleDict();
590 if (PyDict_GetItemString(modules, name) == NULL)
591 return;
592 if (PyDict_DelItemString(modules, name) < 0)
593 Py_FatalError("import: deleting existing key in"
594 "sys.modules failed");
597 /* Execute a code object in a module and return the module object
598 * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
599 * removed from sys.modules, to avoid leaving damaged module objects
600 * in sys.modules. The caller may wish to restore the original
601 * module object (if any) in this case; PyImport_ReloadModule is an
602 * example.
604 PyObject *
605 PyImport_ExecCodeModule(char *name, PyObject *co)
607 return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
610 PyObject *
611 PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
613 PyObject *modules = PyImport_GetModuleDict();
614 PyObject *m, *d, *v;
616 m = PyImport_AddModule(name);
617 if (m == NULL)
618 return NULL;
619 /* If the module is being reloaded, we get the old module back
620 and re-use its dict to exec the new code. */
621 d = PyModule_GetDict(m);
622 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
623 if (PyDict_SetItemString(d, "__builtins__",
624 PyEval_GetBuiltins()) != 0)
625 goto error;
627 /* Remember the filename as the __file__ attribute */
628 v = NULL;
629 if (pathname != NULL) {
630 v = PyString_FromString(pathname);
631 if (v == NULL)
632 PyErr_Clear();
634 if (v == NULL) {
635 v = ((PyCodeObject *)co)->co_filename;
636 Py_INCREF(v);
638 if (PyDict_SetItemString(d, "__file__", v) != 0)
639 PyErr_Clear(); /* Not important enough to report */
640 Py_DECREF(v);
642 v = PyEval_EvalCode((PyCodeObject *)co, d, d);
643 if (v == NULL)
644 goto error;
645 Py_DECREF(v);
647 if ((m = PyDict_GetItemString(modules, name)) == NULL) {
648 PyErr_Format(PyExc_ImportError,
649 "Loaded module %.200s not found in sys.modules",
650 name);
651 return NULL;
654 Py_INCREF(m);
656 return m;
658 error:
659 _RemoveModule(name);
660 return NULL;
664 /* Given a pathname for a Python source file, fill a buffer with the
665 pathname for the corresponding compiled file. Return the pathname
666 for the compiled file, or NULL if there's no space in the buffer.
667 Doesn't set an exception. */
669 static char *
670 make_compiled_pathname(char *pathname, char *buf, size_t buflen)
672 size_t len = strlen(pathname);
673 if (len+2 > buflen)
674 return NULL;
676 #ifdef MS_WINDOWS
677 /* Treat .pyw as if it were .py. The case of ".pyw" must match
678 that used in _PyImport_StandardFiletab. */
679 if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
680 --len; /* pretend 'w' isn't there */
681 #endif
682 memcpy(buf, pathname, len);
683 buf[len] = Py_OptimizeFlag ? 'o' : 'c';
684 buf[len+1] = '\0';
686 return buf;
690 /* Given a pathname for a Python source file, its time of last
691 modification, and a pathname for a compiled file, check whether the
692 compiled file represents the same version of the source. If so,
693 return a FILE pointer for the compiled file, positioned just after
694 the header; if not, return NULL.
695 Doesn't set an exception. */
697 static FILE *
698 check_compiled_module(char *pathname, time_t mtime, char *cpathname)
700 FILE *fp;
701 long magic;
702 long pyc_mtime;
704 fp = fopen(cpathname, "rb");
705 if (fp == NULL)
706 return NULL;
707 magic = PyMarshal_ReadLongFromFile(fp);
708 if (magic != pyc_magic) {
709 if (Py_VerboseFlag)
710 PySys_WriteStderr("# %s has bad magic\n", cpathname);
711 fclose(fp);
712 return NULL;
714 pyc_mtime = PyMarshal_ReadLongFromFile(fp);
715 if (pyc_mtime != mtime) {
716 if (Py_VerboseFlag)
717 PySys_WriteStderr("# %s has bad mtime\n", cpathname);
718 fclose(fp);
719 return NULL;
721 if (Py_VerboseFlag)
722 PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
723 return fp;
727 /* Read a code object from a file and check it for validity */
729 static PyCodeObject *
730 read_compiled_module(char *cpathname, FILE *fp)
732 PyObject *co;
734 co = PyMarshal_ReadLastObjectFromFile(fp);
735 if (co == NULL)
736 return NULL;
737 if (!PyCode_Check(co)) {
738 PyErr_Format(PyExc_ImportError,
739 "Non-code object in %.200s", cpathname);
740 Py_DECREF(co);
741 return NULL;
743 return (PyCodeObject *)co;
747 /* Load a module from a compiled file, execute it, and return its
748 module object WITH INCREMENTED REFERENCE COUNT */
750 static PyObject *
751 load_compiled_module(char *name, char *cpathname, FILE *fp)
753 long magic;
754 PyCodeObject *co;
755 PyObject *m;
757 magic = PyMarshal_ReadLongFromFile(fp);
758 if (magic != pyc_magic) {
759 PyErr_Format(PyExc_ImportError,
760 "Bad magic number in %.200s", cpathname);
761 return NULL;
763 (void) PyMarshal_ReadLongFromFile(fp);
764 co = read_compiled_module(cpathname, fp);
765 if (co == NULL)
766 return NULL;
767 if (Py_VerboseFlag)
768 PySys_WriteStderr("import %s # precompiled from %s\n",
769 name, cpathname);
770 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
771 Py_DECREF(co);
773 return m;
776 /* Parse a source file and return the corresponding code object */
778 static PyCodeObject *
779 parse_source_module(const char *pathname, FILE *fp)
781 PyCodeObject *co = NULL;
782 mod_ty mod;
783 PyArena *arena = PyArena_New();
785 mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, 0,
786 NULL, arena);
787 if (mod) {
788 co = PyAST_Compile(mod, pathname, NULL, arena);
790 PyArena_Free(arena);
791 return co;
795 /* Helper to open a bytecode file for writing in exclusive mode */
797 static FILE *
798 open_exclusive(char *filename)
800 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
801 /* Use O_EXCL to avoid a race condition when another process tries to
802 write the same file. When that happens, our open() call fails,
803 which is just fine (since it's only a cache).
804 XXX If the file exists and is writable but the directory is not
805 writable, the file will never be written. Oh well.
807 int fd;
808 (void) unlink(filename);
809 fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
810 #ifdef O_BINARY
811 |O_BINARY /* necessary for Windows */
812 #endif
813 #ifdef __VMS
814 , 0666, "ctxt=bin", "shr=nil"
815 #else
816 , 0666
817 #endif
819 if (fd < 0)
820 return NULL;
821 return fdopen(fd, "wb");
822 #else
823 /* Best we can do -- on Windows this can't happen anyway */
824 return fopen(filename, "wb");
825 #endif
829 /* Write a compiled module to a file, placing the time of last
830 modification of its source into the header.
831 Errors are ignored, if a write error occurs an attempt is made to
832 remove the file. */
834 static void
835 write_compiled_module(PyCodeObject *co, char *cpathname, time_t mtime)
837 FILE *fp;
839 fp = open_exclusive(cpathname);
840 if (fp == NULL) {
841 if (Py_VerboseFlag)
842 PySys_WriteStderr(
843 "# can't create %s\n", cpathname);
844 return;
846 PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
847 /* First write a 0 for mtime */
848 PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
849 PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
850 if (fflush(fp) != 0 || ferror(fp)) {
851 if (Py_VerboseFlag)
852 PySys_WriteStderr("# can't write %s\n", cpathname);
853 /* Don't keep partial file */
854 fclose(fp);
855 (void) unlink(cpathname);
856 return;
858 /* Now write the true mtime */
859 fseek(fp, 4L, 0);
860 assert(mtime < LONG_MAX);
861 PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
862 fflush(fp);
863 fclose(fp);
864 if (Py_VerboseFlag)
865 PySys_WriteStderr("# wrote %s\n", cpathname);
869 /* Load a source module from a given file and return its module
870 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
871 byte-compiled file, use that instead. */
873 static PyObject *
874 load_source_module(char *name, char *pathname, FILE *fp)
876 time_t mtime;
877 FILE *fpc;
878 char buf[MAXPATHLEN+1];
879 char *cpathname;
880 PyCodeObject *co;
881 PyObject *m;
883 mtime = PyOS_GetLastModificationTime(pathname, fp);
884 if (mtime == (time_t)(-1)) {
885 PyErr_Format(PyExc_RuntimeError,
886 "unable to get modification time from '%s'",
887 pathname);
888 return NULL;
890 #if SIZEOF_TIME_T > 4
891 /* Python's .pyc timestamp handling presumes that the timestamp fits
892 in 4 bytes. This will be fine until sometime in the year 2038,
893 when a 4-byte signed time_t will overflow.
895 if (mtime >> 32) {
896 PyErr_SetString(PyExc_OverflowError,
897 "modification time overflows a 4 byte field");
898 return NULL;
900 #endif
901 cpathname = make_compiled_pathname(pathname, buf,
902 (size_t)MAXPATHLEN + 1);
903 if (cpathname != NULL &&
904 (fpc = check_compiled_module(pathname, mtime, cpathname))) {
905 co = read_compiled_module(cpathname, fpc);
906 fclose(fpc);
907 if (co == NULL)
908 return NULL;
909 if (Py_VerboseFlag)
910 PySys_WriteStderr("import %s # precompiled from %s\n",
911 name, cpathname);
912 pathname = cpathname;
914 else {
915 co = parse_source_module(pathname, fp);
916 if (co == NULL)
917 return NULL;
918 if (Py_VerboseFlag)
919 PySys_WriteStderr("import %s # from %s\n",
920 name, pathname);
921 write_compiled_module(co, cpathname, mtime);
923 m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
924 Py_DECREF(co);
926 return m;
930 /* Forward */
931 static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
932 static struct filedescr *find_module(char *, char *, PyObject *,
933 char *, size_t, FILE **, PyObject **);
934 static struct _frozen *find_frozen(char *name);
936 /* Load a package and return its module object WITH INCREMENTED
937 REFERENCE COUNT */
939 static PyObject *
940 load_package(char *name, char *pathname)
942 PyObject *m, *d;
943 PyObject *file = NULL;
944 PyObject *path = NULL;
945 int err;
946 char buf[MAXPATHLEN+1];
947 FILE *fp = NULL;
948 struct filedescr *fdp;
950 m = PyImport_AddModule(name);
951 if (m == NULL)
952 return NULL;
953 if (Py_VerboseFlag)
954 PySys_WriteStderr("import %s # directory %s\n",
955 name, pathname);
956 d = PyModule_GetDict(m);
957 file = PyString_FromString(pathname);
958 if (file == NULL)
959 goto error;
960 path = Py_BuildValue("[O]", file);
961 if (path == NULL)
962 goto error;
963 err = PyDict_SetItemString(d, "__file__", file);
964 if (err == 0)
965 err = PyDict_SetItemString(d, "__path__", path);
966 if (err != 0)
967 goto error;
968 buf[0] = '\0';
969 fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
970 if (fdp == NULL) {
971 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
972 PyErr_Clear();
973 Py_INCREF(m);
975 else
976 m = NULL;
977 goto cleanup;
979 m = load_module(name, fp, buf, fdp->type, NULL);
980 if (fp != NULL)
981 fclose(fp);
982 goto cleanup;
984 error:
985 m = NULL;
986 cleanup:
987 Py_XDECREF(path);
988 Py_XDECREF(file);
989 return m;
993 /* Helper to test for built-in module */
995 static int
996 is_builtin(char *name)
998 int i;
999 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1000 if (strcmp(name, PyImport_Inittab[i].name) == 0) {
1001 if (PyImport_Inittab[i].initfunc == NULL)
1002 return -1;
1003 else
1004 return 1;
1007 return 0;
1011 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
1012 possibly by fetching it from the path_importer_cache dict. If it
1013 wasn't yet cached, traverse path_hooks until it a hook is found
1014 that can handle the path item. Return None if no hook could;
1015 this tells our caller it should fall back to the builtin
1016 import mechanism. Cache the result in path_importer_cache.
1017 Returns a borrowed reference. */
1019 static PyObject *
1020 get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
1021 PyObject *p)
1023 PyObject *importer;
1024 Py_ssize_t j, nhooks;
1026 /* These conditions are the caller's responsibility: */
1027 assert(PyList_Check(path_hooks));
1028 assert(PyDict_Check(path_importer_cache));
1030 nhooks = PyList_Size(path_hooks);
1031 if (nhooks < 0)
1032 return NULL; /* Shouldn't happen */
1034 importer = PyDict_GetItem(path_importer_cache, p);
1035 if (importer != NULL)
1036 return importer;
1038 /* set path_importer_cache[p] to None to avoid recursion */
1039 if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
1040 return NULL;
1042 for (j = 0; j < nhooks; j++) {
1043 PyObject *hook = PyList_GetItem(path_hooks, j);
1044 if (hook == NULL)
1045 return NULL;
1046 importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
1047 if (importer != NULL)
1048 break;
1050 if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
1051 return NULL;
1053 PyErr_Clear();
1055 if (importer == NULL)
1056 importer = Py_None;
1057 else if (importer != Py_None) {
1058 int err = PyDict_SetItem(path_importer_cache, p, importer);
1059 Py_DECREF(importer);
1060 if (err != 0)
1061 return NULL;
1063 return importer;
1066 /* Search the path (default sys.path) for a module. Return the
1067 corresponding filedescr struct, and (via return arguments) the
1068 pathname and an open file. Return NULL if the module is not found. */
1070 #ifdef MS_COREDLL
1071 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
1072 char *, Py_ssize_t);
1073 #endif
1075 static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
1076 static int find_init_module(char *); /* Forward */
1077 static struct filedescr importhookdescr = {"", "", IMP_HOOK};
1079 static struct filedescr *
1080 find_module(char *fullname, char *subname, PyObject *path, char *buf,
1081 size_t buflen, FILE **p_fp, PyObject **p_loader)
1083 Py_ssize_t i, npath;
1084 size_t len, namelen;
1085 struct filedescr *fdp = NULL;
1086 char *filemode;
1087 FILE *fp = NULL;
1088 PyObject *path_hooks, *path_importer_cache;
1089 #ifndef RISCOS
1090 struct stat statbuf;
1091 #endif
1092 static struct filedescr fd_frozen = {"", "", PY_FROZEN};
1093 static struct filedescr fd_builtin = {"", "", C_BUILTIN};
1094 static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
1095 char name[MAXPATHLEN+1];
1096 #if defined(PYOS_OS2)
1097 size_t saved_len;
1098 size_t saved_namelen;
1099 char *saved_buf = NULL;
1100 #endif
1101 if (p_loader != NULL)
1102 *p_loader = NULL;
1104 if (strlen(subname) > MAXPATHLEN) {
1105 PyErr_SetString(PyExc_OverflowError,
1106 "module name is too long");
1107 return NULL;
1109 strcpy(name, subname);
1111 /* sys.meta_path import hook */
1112 if (p_loader != NULL) {
1113 PyObject *meta_path;
1115 meta_path = PySys_GetObject("meta_path");
1116 if (meta_path == NULL || !PyList_Check(meta_path)) {
1117 PyErr_SetString(PyExc_ImportError,
1118 "sys.meta_path must be a list of "
1119 "import hooks");
1120 return NULL;
1122 Py_INCREF(meta_path); /* zap guard */
1123 npath = PyList_Size(meta_path);
1124 for (i = 0; i < npath; i++) {
1125 PyObject *loader;
1126 PyObject *hook = PyList_GetItem(meta_path, i);
1127 loader = PyObject_CallMethod(hook, "find_module",
1128 "sO", fullname,
1129 path != NULL ?
1130 path : Py_None);
1131 if (loader == NULL) {
1132 Py_DECREF(meta_path);
1133 return NULL; /* true error */
1135 if (loader != Py_None) {
1136 /* a loader was found */
1137 *p_loader = loader;
1138 Py_DECREF(meta_path);
1139 return &importhookdescr;
1141 Py_DECREF(loader);
1143 Py_DECREF(meta_path);
1146 if (path != NULL && PyString_Check(path)) {
1147 /* The only type of submodule allowed inside a "frozen"
1148 package are other frozen modules or packages. */
1149 if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
1150 PyErr_SetString(PyExc_ImportError,
1151 "full frozen module name too long");
1152 return NULL;
1154 strcpy(buf, PyString_AsString(path));
1155 strcat(buf, ".");
1156 strcat(buf, name);
1157 strcpy(name, buf);
1158 if (find_frozen(name) != NULL) {
1159 strcpy(buf, name);
1160 return &fd_frozen;
1162 PyErr_Format(PyExc_ImportError,
1163 "No frozen submodule named %.200s", name);
1164 return NULL;
1166 if (path == NULL) {
1167 if (is_builtin(name)) {
1168 strcpy(buf, name);
1169 return &fd_builtin;
1171 if ((find_frozen(name)) != NULL) {
1172 strcpy(buf, name);
1173 return &fd_frozen;
1176 #ifdef MS_COREDLL
1177 fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
1178 if (fp != NULL) {
1179 *p_fp = fp;
1180 return fdp;
1182 #endif
1183 path = PySys_GetObject("path");
1185 if (path == NULL || !PyList_Check(path)) {
1186 PyErr_SetString(PyExc_ImportError,
1187 "sys.path must be a list of directory names");
1188 return NULL;
1191 path_hooks = PySys_GetObject("path_hooks");
1192 if (path_hooks == NULL || !PyList_Check(path_hooks)) {
1193 PyErr_SetString(PyExc_ImportError,
1194 "sys.path_hooks must be a list of "
1195 "import hooks");
1196 return NULL;
1198 path_importer_cache = PySys_GetObject("path_importer_cache");
1199 if (path_importer_cache == NULL ||
1200 !PyDict_Check(path_importer_cache)) {
1201 PyErr_SetString(PyExc_ImportError,
1202 "sys.path_importer_cache must be a dict");
1203 return NULL;
1206 npath = PyList_Size(path);
1207 namelen = strlen(name);
1208 for (i = 0; i < npath; i++) {
1209 PyObject *copy = NULL;
1210 PyObject *v = PyList_GetItem(path, i);
1211 #ifdef Py_USING_UNICODE
1212 if (PyUnicode_Check(v)) {
1213 copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
1214 PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
1215 if (copy == NULL)
1216 return NULL;
1217 v = copy;
1219 else
1220 #endif
1221 if (!PyString_Check(v))
1222 continue;
1223 len = PyString_GET_SIZE(v);
1224 if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
1225 Py_XDECREF(copy);
1226 continue; /* Too long */
1228 strcpy(buf, PyString_AS_STRING(v));
1229 if (strlen(buf) != len) {
1230 Py_XDECREF(copy);
1231 continue; /* v contains '\0' */
1234 /* sys.path_hooks import hook */
1235 if (p_loader != NULL) {
1236 PyObject *importer;
1238 importer = get_path_importer(path_importer_cache,
1239 path_hooks, v);
1240 if (importer == NULL)
1241 return NULL;
1242 /* Note: importer is a borrowed reference */
1243 if (importer == Py_False) {
1244 /* Cached as not being a valid dir. */
1245 Py_XDECREF(copy);
1246 continue;
1248 else if (importer == Py_True) {
1249 /* Cached as being a valid dir, so just
1250 * continue below. */
1252 else if (importer == Py_None) {
1253 /* No importer was found, so it has to be a file.
1254 * Check if the directory is valid.
1255 * Note that the empty string is a valid path, but
1256 * not stat'able, hence the check for len. */
1257 #ifdef HAVE_STAT
1258 if (len && stat(buf, &statbuf) != 0) {
1259 /* Directory does not exist. */
1260 PyDict_SetItem(path_importer_cache,
1261 v, Py_False);
1262 Py_XDECREF(copy);
1263 continue;
1264 } else {
1265 PyDict_SetItem(path_importer_cache,
1266 v, Py_True);
1268 #endif
1270 else {
1271 /* A real import hook importer was found. */
1272 PyObject *loader;
1273 loader = PyObject_CallMethod(importer,
1274 "find_module",
1275 "s", fullname);
1276 if (loader == NULL)
1277 return NULL; /* error */
1278 if (loader != Py_None) {
1279 /* a loader was found */
1280 *p_loader = loader;
1281 return &importhookdescr;
1283 Py_DECREF(loader);
1284 Py_XDECREF(copy);
1285 continue;
1288 /* no hook was found, use builtin import */
1290 if (len > 0 && buf[len-1] != SEP
1291 #ifdef ALTSEP
1292 && buf[len-1] != ALTSEP
1293 #endif
1295 buf[len++] = SEP;
1296 strcpy(buf+len, name);
1297 len += namelen;
1299 /* Check for package import (buf holds a directory name,
1300 and there's an __init__ module in that directory */
1301 #ifdef HAVE_STAT
1302 if (stat(buf, &statbuf) == 0 && /* it exists */
1303 S_ISDIR(statbuf.st_mode) && /* it's a directory */
1304 case_ok(buf, len, namelen, name)) { /* case matches */
1305 if (find_init_module(buf)) { /* and has __init__.py */
1306 Py_XDECREF(copy);
1307 return &fd_package;
1309 else {
1310 char warnstr[MAXPATHLEN+80];
1311 sprintf(warnstr, "Not importing directory "
1312 "'%.*s': missing __init__.py",
1313 MAXPATHLEN, buf);
1314 if (PyErr_Warn(PyExc_ImportWarning,
1315 warnstr)) {
1316 Py_XDECREF(copy);
1317 return NULL;
1321 #else
1322 /* XXX How are you going to test for directories? */
1323 #ifdef RISCOS
1324 if (isdir(buf) &&
1325 case_ok(buf, len, namelen, name)) {
1326 if (find_init_module(buf)) {
1327 Py_XDECREF(copy);
1328 return &fd_package;
1330 else {
1331 char warnstr[MAXPATHLEN+80];
1332 sprintf(warnstr, "Not importing directory "
1333 "'%.*s': missing __init__.py",
1334 MAXPATHLEN, buf);
1335 if (PyErr_Warn(PyExc_ImportWarning,
1336 warnstr)) {
1337 Py_XDECREF(copy);
1338 return NULL;
1341 #endif
1342 #endif
1343 #if defined(PYOS_OS2)
1344 /* take a snapshot of the module spec for restoration
1345 * after the 8 character DLL hackery
1347 saved_buf = strdup(buf);
1348 saved_len = len;
1349 saved_namelen = namelen;
1350 #endif /* PYOS_OS2 */
1351 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
1352 #if defined(PYOS_OS2)
1353 /* OS/2 limits DLLs to 8 character names (w/o
1354 extension)
1355 * so if the name is longer than that and its a
1356 * dynamically loaded module we're going to try,
1357 * truncate the name before trying
1359 if (strlen(subname) > 8) {
1360 /* is this an attempt to load a C extension? */
1361 const struct filedescr *scan;
1362 scan = _PyImport_DynLoadFiletab;
1363 while (scan->suffix != NULL) {
1364 if (!strcmp(scan->suffix, fdp->suffix))
1365 break;
1366 else
1367 scan++;
1369 if (scan->suffix != NULL) {
1370 /* yes, so truncate the name */
1371 namelen = 8;
1372 len -= strlen(subname) - namelen;
1373 buf[len] = '\0';
1376 #endif /* PYOS_OS2 */
1377 strcpy(buf+len, fdp->suffix);
1378 if (Py_VerboseFlag > 1)
1379 PySys_WriteStderr("# trying %s\n", buf);
1380 filemode = fdp->mode;
1381 if (filemode[0] == 'U')
1382 filemode = "r" PY_STDIOTEXTMODE;
1383 fp = fopen(buf, filemode);
1384 if (fp != NULL) {
1385 if (case_ok(buf, len, namelen, name))
1386 break;
1387 else { /* continue search */
1388 fclose(fp);
1389 fp = NULL;
1392 #if defined(PYOS_OS2)
1393 /* restore the saved snapshot */
1394 strcpy(buf, saved_buf);
1395 len = saved_len;
1396 namelen = saved_namelen;
1397 #endif
1399 #if defined(PYOS_OS2)
1400 /* don't need/want the module name snapshot anymore */
1401 if (saved_buf)
1403 free(saved_buf);
1404 saved_buf = NULL;
1406 #endif
1407 Py_XDECREF(copy);
1408 if (fp != NULL)
1409 break;
1411 if (fp == NULL) {
1412 PyErr_Format(PyExc_ImportError,
1413 "No module named %.200s", name);
1414 return NULL;
1416 *p_fp = fp;
1417 return fdp;
1420 /* Helpers for main.c
1421 * Find the source file corresponding to a named module
1423 struct filedescr *
1424 _PyImport_FindModule(const char *name, PyObject *path, char *buf,
1425 size_t buflen, FILE **p_fp, PyObject **p_loader)
1427 return find_module((char *) name, (char *) name, path,
1428 buf, buflen, p_fp, p_loader);
1431 PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
1433 return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
1436 /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
1437 * The arguments here are tricky, best shown by example:
1438 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1439 * ^ ^ ^ ^
1440 * |--------------------- buf ---------------------|
1441 * |------------------- len ------------------|
1442 * |------ name -------|
1443 * |----- namelen -----|
1444 * buf is the full path, but len only counts up to (& exclusive of) the
1445 * extension. name is the module name, also exclusive of extension.
1447 * We've already done a successful stat() or fopen() on buf, so know that
1448 * there's some match, possibly case-insensitive.
1450 * case_ok() is to return 1 if there's a case-sensitive match for
1451 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1452 * exists.
1454 * case_ok() is used to implement case-sensitive import semantics even
1455 * on platforms with case-insensitive filesystems. It's trivial to implement
1456 * for case-sensitive filesystems. It's pretty much a cross-platform
1457 * nightmare for systems with case-insensitive filesystems.
1460 /* First we may need a pile of platform-specific header files; the sequence
1461 * of #if's here should match the sequence in the body of case_ok().
1463 #if defined(MS_WINDOWS)
1464 #include <windows.h>
1466 #elif defined(DJGPP)
1467 #include <dir.h>
1469 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1470 #include <sys/types.h>
1471 #include <dirent.h>
1473 #elif defined(PYOS_OS2)
1474 #define INCL_DOS
1475 #define INCL_DOSERRORS
1476 #define INCL_NOPMAPI
1477 #include <os2.h>
1479 #elif defined(RISCOS)
1480 #include "oslib/osfscontrol.h"
1481 #endif
1483 static int
1484 case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
1486 /* Pick a platform-specific implementation; the sequence of #if's here should
1487 * match the sequence just above.
1490 /* MS_WINDOWS */
1491 #if defined(MS_WINDOWS)
1492 WIN32_FIND_DATA data;
1493 HANDLE h;
1495 if (Py_GETENV("PYTHONCASEOK") != NULL)
1496 return 1;
1498 h = FindFirstFile(buf, &data);
1499 if (h == INVALID_HANDLE_VALUE) {
1500 PyErr_Format(PyExc_NameError,
1501 "Can't find file for module %.100s\n(filename %.300s)",
1502 name, buf);
1503 return 0;
1505 FindClose(h);
1506 return strncmp(data.cFileName, name, namelen) == 0;
1508 /* DJGPP */
1509 #elif defined(DJGPP)
1510 struct ffblk ffblk;
1511 int done;
1513 if (Py_GETENV("PYTHONCASEOK") != NULL)
1514 return 1;
1516 done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
1517 if (done) {
1518 PyErr_Format(PyExc_NameError,
1519 "Can't find file for module %.100s\n(filename %.300s)",
1520 name, buf);
1521 return 0;
1523 return strncmp(ffblk.ff_name, name, namelen) == 0;
1525 /* new-fangled macintosh (macosx) or Cygwin */
1526 #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
1527 DIR *dirp;
1528 struct dirent *dp;
1529 char dirname[MAXPATHLEN + 1];
1530 const int dirlen = len - namelen - 1; /* don't want trailing SEP */
1532 if (Py_GETENV("PYTHONCASEOK") != NULL)
1533 return 1;
1535 /* Copy the dir component into dirname; substitute "." if empty */
1536 if (dirlen <= 0) {
1537 dirname[0] = '.';
1538 dirname[1] = '\0';
1540 else {
1541 assert(dirlen <= MAXPATHLEN);
1542 memcpy(dirname, buf, dirlen);
1543 dirname[dirlen] = '\0';
1545 /* Open the directory and search the entries for an exact match. */
1546 dirp = opendir(dirname);
1547 if (dirp) {
1548 char *nameWithExt = buf + len - namelen;
1549 while ((dp = readdir(dirp)) != NULL) {
1550 const int thislen =
1551 #ifdef _DIRENT_HAVE_D_NAMELEN
1552 dp->d_namlen;
1553 #else
1554 strlen(dp->d_name);
1555 #endif
1556 if (thislen >= namelen &&
1557 strcmp(dp->d_name, nameWithExt) == 0) {
1558 (void)closedir(dirp);
1559 return 1; /* Found */
1562 (void)closedir(dirp);
1564 return 0 ; /* Not found */
1566 /* RISC OS */
1567 #elif defined(RISCOS)
1568 char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
1569 char buf2[MAXPATHLEN+2];
1570 char *nameWithExt = buf+len-namelen;
1571 int canonlen;
1572 os_error *e;
1574 if (Py_GETENV("PYTHONCASEOK") != NULL)
1575 return 1;
1577 /* workaround:
1578 append wildcard, otherwise case of filename wouldn't be touched */
1579 strcpy(buf2, buf);
1580 strcat(buf2, "*");
1582 e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
1583 canonlen = MAXPATHLEN+1-canonlen;
1584 if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
1585 return 0;
1586 if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
1587 return 1; /* match */
1589 return 0;
1591 /* OS/2 */
1592 #elif defined(PYOS_OS2)
1593 HDIR hdir = 1;
1594 ULONG srchcnt = 1;
1595 FILEFINDBUF3 ffbuf;
1596 APIRET rc;
1598 if (getenv("PYTHONCASEOK") != NULL)
1599 return 1;
1601 rc = DosFindFirst(buf,
1602 &hdir,
1603 FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
1604 &ffbuf, sizeof(ffbuf),
1605 &srchcnt,
1606 FIL_STANDARD);
1607 if (rc != NO_ERROR)
1608 return 0;
1609 return strncmp(ffbuf.achName, name, namelen) == 0;
1611 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1612 #else
1613 return 1;
1615 #endif
1619 #ifdef HAVE_STAT
1620 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1621 static int
1622 find_init_module(char *buf)
1624 const size_t save_len = strlen(buf);
1625 size_t i = save_len;
1626 char *pname; /* pointer to start of __init__ */
1627 struct stat statbuf;
1629 /* For calling case_ok(buf, len, namelen, name):
1630 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1631 * ^ ^ ^ ^
1632 * |--------------------- buf ---------------------|
1633 * |------------------- len ------------------|
1634 * |------ name -------|
1635 * |----- namelen -----|
1637 if (save_len + 13 >= MAXPATHLEN)
1638 return 0;
1639 buf[i++] = SEP;
1640 pname = buf + i;
1641 strcpy(pname, "__init__.py");
1642 if (stat(buf, &statbuf) == 0) {
1643 if (case_ok(buf,
1644 save_len + 9, /* len("/__init__") */
1645 8, /* len("__init__") */
1646 pname)) {
1647 buf[save_len] = '\0';
1648 return 1;
1651 i += strlen(pname);
1652 strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
1653 if (stat(buf, &statbuf) == 0) {
1654 if (case_ok(buf,
1655 save_len + 9, /* len("/__init__") */
1656 8, /* len("__init__") */
1657 pname)) {
1658 buf[save_len] = '\0';
1659 return 1;
1662 buf[save_len] = '\0';
1663 return 0;
1666 #else
1668 #ifdef RISCOS
1669 static int
1670 find_init_module(buf)
1671 char *buf;
1673 int save_len = strlen(buf);
1674 int i = save_len;
1676 if (save_len + 13 >= MAXPATHLEN)
1677 return 0;
1678 buf[i++] = SEP;
1679 strcpy(buf+i, "__init__/py");
1680 if (isfile(buf)) {
1681 buf[save_len] = '\0';
1682 return 1;
1685 if (Py_OptimizeFlag)
1686 strcpy(buf+i, "o");
1687 else
1688 strcpy(buf+i, "c");
1689 if (isfile(buf)) {
1690 buf[save_len] = '\0';
1691 return 1;
1693 buf[save_len] = '\0';
1694 return 0;
1696 #endif /*RISCOS*/
1698 #endif /* HAVE_STAT */
1701 static int init_builtin(char *); /* Forward */
1703 /* Load an external module using the default search path and return
1704 its module object WITH INCREMENTED REFERENCE COUNT */
1706 static PyObject *
1707 load_module(char *name, FILE *fp, char *buf, int type, PyObject *loader)
1709 PyObject *modules;
1710 PyObject *m;
1711 int err;
1713 /* First check that there's an open file (if we need one) */
1714 switch (type) {
1715 case PY_SOURCE:
1716 case PY_COMPILED:
1717 if (fp == NULL) {
1718 PyErr_Format(PyExc_ValueError,
1719 "file object required for import (type code %d)",
1720 type);
1721 return NULL;
1725 switch (type) {
1727 case PY_SOURCE:
1728 m = load_source_module(name, buf, fp);
1729 break;
1731 case PY_COMPILED:
1732 m = load_compiled_module(name, buf, fp);
1733 break;
1735 #ifdef HAVE_DYNAMIC_LOADING
1736 case C_EXTENSION:
1737 m = _PyImport_LoadDynamicModule(name, buf, fp);
1738 break;
1739 #endif
1741 case PKG_DIRECTORY:
1742 m = load_package(name, buf);
1743 break;
1745 case C_BUILTIN:
1746 case PY_FROZEN:
1747 if (buf != NULL && buf[0] != '\0')
1748 name = buf;
1749 if (type == C_BUILTIN)
1750 err = init_builtin(name);
1751 else
1752 err = PyImport_ImportFrozenModule(name);
1753 if (err < 0)
1754 return NULL;
1755 if (err == 0) {
1756 PyErr_Format(PyExc_ImportError,
1757 "Purported %s module %.200s not found",
1758 type == C_BUILTIN ?
1759 "builtin" : "frozen",
1760 name);
1761 return NULL;
1763 modules = PyImport_GetModuleDict();
1764 m = PyDict_GetItemString(modules, name);
1765 if (m == NULL) {
1766 PyErr_Format(
1767 PyExc_ImportError,
1768 "%s module %.200s not properly initialized",
1769 type == C_BUILTIN ?
1770 "builtin" : "frozen",
1771 name);
1772 return NULL;
1774 Py_INCREF(m);
1775 break;
1777 case IMP_HOOK: {
1778 if (loader == NULL) {
1779 PyErr_SetString(PyExc_ImportError,
1780 "import hook without loader");
1781 return NULL;
1783 m = PyObject_CallMethod(loader, "load_module", "s", name);
1784 break;
1787 default:
1788 PyErr_Format(PyExc_ImportError,
1789 "Don't know how to import %.200s (type code %d)",
1790 name, type);
1791 m = NULL;
1795 return m;
1799 /* Initialize a built-in module.
1800 Return 1 for succes, 0 if the module is not found, and -1 with
1801 an exception set if the initialization failed. */
1803 static int
1804 init_builtin(char *name)
1806 struct _inittab *p;
1808 if (_PyImport_FindExtension(name, name) != NULL)
1809 return 1;
1811 for (p = PyImport_Inittab; p->name != NULL; p++) {
1812 if (strcmp(name, p->name) == 0) {
1813 if (p->initfunc == NULL) {
1814 PyErr_Format(PyExc_ImportError,
1815 "Cannot re-init internal module %.200s",
1816 name);
1817 return -1;
1819 if (Py_VerboseFlag)
1820 PySys_WriteStderr("import %s # builtin\n", name);
1821 (*p->initfunc)();
1822 if (PyErr_Occurred())
1823 return -1;
1824 if (_PyImport_FixupExtension(name, name) == NULL)
1825 return -1;
1826 return 1;
1829 return 0;
1833 /* Frozen modules */
1835 static struct _frozen *
1836 find_frozen(char *name)
1838 struct _frozen *p;
1840 for (p = PyImport_FrozenModules; ; p++) {
1841 if (p->name == NULL)
1842 return NULL;
1843 if (strcmp(p->name, name) == 0)
1844 break;
1846 return p;
1849 static PyObject *
1850 get_frozen_object(char *name)
1852 struct _frozen *p = find_frozen(name);
1853 int size;
1855 if (p == NULL) {
1856 PyErr_Format(PyExc_ImportError,
1857 "No such frozen object named %.200s",
1858 name);
1859 return NULL;
1861 if (p->code == NULL) {
1862 PyErr_Format(PyExc_ImportError,
1863 "Excluded frozen object named %.200s",
1864 name);
1865 return NULL;
1867 size = p->size;
1868 if (size < 0)
1869 size = -size;
1870 return PyMarshal_ReadObjectFromString((char *)p->code, size);
1873 /* Initialize a frozen module.
1874 Return 1 for succes, 0 if the module is not found, and -1 with
1875 an exception set if the initialization failed.
1876 This function is also used from frozenmain.c */
1879 PyImport_ImportFrozenModule(char *name)
1881 struct _frozen *p = find_frozen(name);
1882 PyObject *co;
1883 PyObject *m;
1884 int ispackage;
1885 int size;
1887 if (p == NULL)
1888 return 0;
1889 if (p->code == NULL) {
1890 PyErr_Format(PyExc_ImportError,
1891 "Excluded frozen object named %.200s",
1892 name);
1893 return -1;
1895 size = p->size;
1896 ispackage = (size < 0);
1897 if (ispackage)
1898 size = -size;
1899 if (Py_VerboseFlag)
1900 PySys_WriteStderr("import %s # frozen%s\n",
1901 name, ispackage ? " package" : "");
1902 co = PyMarshal_ReadObjectFromString((char *)p->code, size);
1903 if (co == NULL)
1904 return -1;
1905 if (!PyCode_Check(co)) {
1906 Py_DECREF(co);
1907 PyErr_Format(PyExc_TypeError,
1908 "frozen object %.200s is not a code object",
1909 name);
1910 return -1;
1912 if (ispackage) {
1913 /* Set __path__ to the package name */
1914 PyObject *d, *s;
1915 int err;
1916 m = PyImport_AddModule(name);
1917 if (m == NULL)
1918 return -1;
1919 d = PyModule_GetDict(m);
1920 s = PyString_InternFromString(name);
1921 if (s == NULL)
1922 return -1;
1923 err = PyDict_SetItemString(d, "__path__", s);
1924 Py_DECREF(s);
1925 if (err != 0)
1926 return err;
1928 m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
1929 Py_DECREF(co);
1930 if (m == NULL)
1931 return -1;
1932 Py_DECREF(m);
1933 return 1;
1937 /* Import a module, either built-in, frozen, or external, and return
1938 its module object WITH INCREMENTED REFERENCE COUNT */
1940 PyObject *
1941 PyImport_ImportModule(const char *name)
1943 PyObject *pname;
1944 PyObject *result;
1946 pname = PyString_FromString(name);
1947 if (pname == NULL)
1948 return NULL;
1949 result = PyImport_Import(pname);
1950 Py_DECREF(pname);
1951 return result;
1954 /* Forward declarations for helper routines */
1955 static PyObject *get_parent(PyObject *globals, char *buf,
1956 Py_ssize_t *p_buflen, int level);
1957 static PyObject *load_next(PyObject *mod, PyObject *altmod,
1958 char **p_name, char *buf, Py_ssize_t *p_buflen);
1959 static int mark_miss(char *name);
1960 static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
1961 char *buf, Py_ssize_t buflen, int recursive);
1962 static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
1964 /* The Magnum Opus of dotted-name import :-) */
1966 static PyObject *
1967 import_module_level(char *name, PyObject *globals, PyObject *locals,
1968 PyObject *fromlist, int level)
1970 char buf[MAXPATHLEN+1];
1971 Py_ssize_t buflen = 0;
1972 PyObject *parent, *head, *next, *tail;
1974 parent = get_parent(globals, buf, &buflen, level);
1975 if (parent == NULL)
1976 return NULL;
1978 head = load_next(parent, Py_None, &name, buf, &buflen);
1979 if (head == NULL)
1980 return NULL;
1982 tail = head;
1983 Py_INCREF(tail);
1984 while (name) {
1985 next = load_next(tail, tail, &name, buf, &buflen);
1986 Py_DECREF(tail);
1987 if (next == NULL) {
1988 Py_DECREF(head);
1989 return NULL;
1991 tail = next;
1993 if (tail == Py_None) {
1994 /* If tail is Py_None, both get_parent and load_next found
1995 an empty module name: someone called __import__("") or
1996 doctored faulty bytecode */
1997 Py_DECREF(tail);
1998 Py_DECREF(head);
1999 PyErr_SetString(PyExc_ValueError,
2000 "Empty module name");
2001 return NULL;
2004 if (fromlist != NULL) {
2005 if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
2006 fromlist = NULL;
2009 if (fromlist == NULL) {
2010 Py_DECREF(tail);
2011 return head;
2014 Py_DECREF(head);
2015 if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
2016 Py_DECREF(tail);
2017 return NULL;
2020 return tail;
2023 /* For DLL compatibility */
2024 #undef PyImport_ImportModuleEx
2025 PyObject *
2026 PyImport_ImportModuleEx(char *name, PyObject *globals, PyObject *locals,
2027 PyObject *fromlist)
2029 PyObject *result;
2030 lock_import();
2031 result = import_module_level(name, globals, locals, fromlist, -1);
2032 if (unlock_import() < 0) {
2033 Py_XDECREF(result);
2034 PyErr_SetString(PyExc_RuntimeError,
2035 "not holding the import lock");
2036 return NULL;
2038 return result;
2040 #define PyImport_ImportModuleEx(n, g, l, f) \
2041 PyImport_ImportModuleLevel(n, g, l, f, -1);
2043 PyObject *
2044 PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
2045 PyObject *fromlist, int level)
2047 PyObject *result;
2048 lock_import();
2049 result = import_module_level(name, globals, locals, fromlist, level);
2050 if (unlock_import() < 0) {
2051 Py_XDECREF(result);
2052 PyErr_SetString(PyExc_RuntimeError,
2053 "not holding the import lock");
2054 return NULL;
2056 return result;
2059 /* Return the package that an import is being performed in. If globals comes
2060 from the module foo.bar.bat (not itself a package), this returns the
2061 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
2062 the package's entry in sys.modules is returned, as a borrowed reference.
2064 The *name* of the returned package is returned in buf, with the length of
2065 the name in *p_buflen.
2067 If globals doesn't come from a package or a module in a package, or a
2068 corresponding entry is not found in sys.modules, Py_None is returned.
2070 static PyObject *
2071 get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
2073 static PyObject *namestr = NULL;
2074 static PyObject *pathstr = NULL;
2075 PyObject *modname, *modpath, *modules, *parent;
2077 if (globals == NULL || !PyDict_Check(globals) || !level)
2078 return Py_None;
2080 if (namestr == NULL) {
2081 namestr = PyString_InternFromString("__name__");
2082 if (namestr == NULL)
2083 return NULL;
2085 if (pathstr == NULL) {
2086 pathstr = PyString_InternFromString("__path__");
2087 if (pathstr == NULL)
2088 return NULL;
2091 *buf = '\0';
2092 *p_buflen = 0;
2093 modname = PyDict_GetItem(globals, namestr);
2094 if (modname == NULL || !PyString_Check(modname))
2095 return Py_None;
2097 modpath = PyDict_GetItem(globals, pathstr);
2098 if (modpath != NULL) {
2099 Py_ssize_t len = PyString_GET_SIZE(modname);
2100 if (len > MAXPATHLEN) {
2101 PyErr_SetString(PyExc_ValueError,
2102 "Module name too long");
2103 return NULL;
2105 strcpy(buf, PyString_AS_STRING(modname));
2107 else {
2108 char *start = PyString_AS_STRING(modname);
2109 char *lastdot = strrchr(start, '.');
2110 size_t len;
2111 if (lastdot == NULL && level > 0) {
2112 PyErr_SetString(PyExc_ValueError,
2113 "Relative importpath too deep");
2114 return NULL;
2116 if (lastdot == NULL)
2117 return Py_None;
2118 len = lastdot - start;
2119 if (len >= MAXPATHLEN) {
2120 PyErr_SetString(PyExc_ValueError,
2121 "Module name too long");
2122 return NULL;
2124 strncpy(buf, start, len);
2125 buf[len] = '\0';
2128 while (--level > 0) {
2129 char *dot = strrchr(buf, '.');
2130 if (dot == NULL) {
2131 PyErr_SetString(PyExc_ValueError,
2132 "Relative importpath too deep");
2133 return NULL;
2135 *dot = '\0';
2137 *p_buflen = strlen(buf);
2139 modules = PyImport_GetModuleDict();
2140 parent = PyDict_GetItemString(modules, buf);
2141 if (parent == NULL)
2142 PyErr_Format(PyExc_SystemError,
2143 "Parent module '%.200s' not loaded", buf);
2144 return parent;
2145 /* We expect, but can't guarantee, if parent != None, that:
2146 - parent.__name__ == buf
2147 - parent.__dict__ is globals
2148 If this is violated... Who cares? */
2151 /* altmod is either None or same as mod */
2152 static PyObject *
2153 load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
2154 Py_ssize_t *p_buflen)
2156 char *name = *p_name;
2157 char *dot = strchr(name, '.');
2158 size_t len;
2159 char *p;
2160 PyObject *result;
2162 if (strlen(name) == 0) {
2163 /* completely empty module name should only happen in
2164 'from . import' (or '__import__("")')*/
2165 Py_INCREF(mod);
2166 *p_name = NULL;
2167 return mod;
2170 if (dot == NULL) {
2171 *p_name = NULL;
2172 len = strlen(name);
2174 else {
2175 *p_name = dot+1;
2176 len = dot-name;
2178 if (len == 0) {
2179 PyErr_SetString(PyExc_ValueError,
2180 "Empty module name");
2181 return NULL;
2184 p = buf + *p_buflen;
2185 if (p != buf)
2186 *p++ = '.';
2187 if (p+len-buf >= MAXPATHLEN) {
2188 PyErr_SetString(PyExc_ValueError,
2189 "Module name too long");
2190 return NULL;
2192 strncpy(p, name, len);
2193 p[len] = '\0';
2194 *p_buflen = p+len-buf;
2196 result = import_submodule(mod, p, buf);
2197 if (result == Py_None && altmod != mod) {
2198 Py_DECREF(result);
2199 /* Here, altmod must be None and mod must not be None */
2200 result = import_submodule(altmod, p, p);
2201 if (result != NULL && result != Py_None) {
2202 if (mark_miss(buf) != 0) {
2203 Py_DECREF(result);
2204 return NULL;
2206 strncpy(buf, name, len);
2207 buf[len] = '\0';
2208 *p_buflen = len;
2211 if (result == NULL)
2212 return NULL;
2214 if (result == Py_None) {
2215 Py_DECREF(result);
2216 PyErr_Format(PyExc_ImportError,
2217 "No module named %.200s", name);
2218 return NULL;
2221 return result;
2224 static int
2225 mark_miss(char *name)
2227 PyObject *modules = PyImport_GetModuleDict();
2228 return PyDict_SetItemString(modules, name, Py_None);
2231 static int
2232 ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
2233 int recursive)
2235 int i;
2237 if (!PyObject_HasAttrString(mod, "__path__"))
2238 return 1;
2240 for (i = 0; ; i++) {
2241 PyObject *item = PySequence_GetItem(fromlist, i);
2242 int hasit;
2243 if (item == NULL) {
2244 if (PyErr_ExceptionMatches(PyExc_IndexError)) {
2245 PyErr_Clear();
2246 return 1;
2248 return 0;
2250 if (!PyString_Check(item)) {
2251 PyErr_SetString(PyExc_TypeError,
2252 "Item in ``from list'' not a string");
2253 Py_DECREF(item);
2254 return 0;
2256 if (PyString_AS_STRING(item)[0] == '*') {
2257 PyObject *all;
2258 Py_DECREF(item);
2259 /* See if the package defines __all__ */
2260 if (recursive)
2261 continue; /* Avoid endless recursion */
2262 all = PyObject_GetAttrString(mod, "__all__");
2263 if (all == NULL)
2264 PyErr_Clear();
2265 else {
2266 int ret = ensure_fromlist(mod, all, buf, buflen, 1);
2267 Py_DECREF(all);
2268 if (!ret)
2269 return 0;
2271 continue;
2273 hasit = PyObject_HasAttr(mod, item);
2274 if (!hasit) {
2275 char *subname = PyString_AS_STRING(item);
2276 PyObject *submod;
2277 char *p;
2278 if (buflen + strlen(subname) >= MAXPATHLEN) {
2279 PyErr_SetString(PyExc_ValueError,
2280 "Module name too long");
2281 Py_DECREF(item);
2282 return 0;
2284 p = buf + buflen;
2285 *p++ = '.';
2286 strcpy(p, subname);
2287 submod = import_submodule(mod, subname, buf);
2288 Py_XDECREF(submod);
2289 if (submod == NULL) {
2290 Py_DECREF(item);
2291 return 0;
2294 Py_DECREF(item);
2297 /* NOTREACHED */
2300 static int
2301 add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
2302 PyObject *modules)
2304 if (mod == Py_None)
2305 return 1;
2306 /* Irrespective of the success of this load, make a
2307 reference to it in the parent package module. A copy gets
2308 saved in the modules dictionary under the full name, so get a
2309 reference from there, if need be. (The exception is when the
2310 load failed with a SyntaxError -- then there's no trace in
2311 sys.modules. In that case, of course, do nothing extra.) */
2312 if (submod == NULL) {
2313 submod = PyDict_GetItemString(modules, fullname);
2314 if (submod == NULL)
2315 return 1;
2317 if (PyModule_Check(mod)) {
2318 /* We can't use setattr here since it can give a
2319 * spurious warning if the submodule name shadows a
2320 * builtin name */
2321 PyObject *dict = PyModule_GetDict(mod);
2322 if (!dict)
2323 return 0;
2324 if (PyDict_SetItemString(dict, subname, submod) < 0)
2325 return 0;
2327 else {
2328 if (PyObject_SetAttrString(mod, subname, submod) < 0)
2329 return 0;
2331 return 1;
2334 static PyObject *
2335 import_submodule(PyObject *mod, char *subname, char *fullname)
2337 PyObject *modules = PyImport_GetModuleDict();
2338 PyObject *m = NULL;
2340 /* Require:
2341 if mod == None: subname == fullname
2342 else: mod.__name__ + "." + subname == fullname
2345 if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
2346 Py_INCREF(m);
2348 else {
2349 PyObject *path, *loader = NULL;
2350 char buf[MAXPATHLEN+1];
2351 struct filedescr *fdp;
2352 FILE *fp = NULL;
2354 if (mod == Py_None)
2355 path = NULL;
2356 else {
2357 path = PyObject_GetAttrString(mod, "__path__");
2358 if (path == NULL) {
2359 PyErr_Clear();
2360 Py_INCREF(Py_None);
2361 return Py_None;
2365 buf[0] = '\0';
2366 fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
2367 &fp, &loader);
2368 Py_XDECREF(path);
2369 if (fdp == NULL) {
2370 if (!PyErr_ExceptionMatches(PyExc_ImportError))
2371 return NULL;
2372 PyErr_Clear();
2373 Py_INCREF(Py_None);
2374 return Py_None;
2376 m = load_module(fullname, fp, buf, fdp->type, loader);
2377 Py_XDECREF(loader);
2378 if (fp)
2379 fclose(fp);
2380 if (!add_submodule(mod, m, fullname, subname, modules)) {
2381 Py_XDECREF(m);
2382 m = NULL;
2386 return m;
2390 /* Re-import a module of any kind and return its module object, WITH
2391 INCREMENTED REFERENCE COUNT */
2393 PyObject *
2394 PyImport_ReloadModule(PyObject *m)
2396 PyObject *modules = PyImport_GetModuleDict();
2397 PyObject *path = NULL, *loader = NULL;
2398 char *name, *subname;
2399 char buf[MAXPATHLEN+1];
2400 struct filedescr *fdp;
2401 FILE *fp = NULL;
2402 PyObject *newm;
2404 if (m == NULL || !PyModule_Check(m)) {
2405 PyErr_SetString(PyExc_TypeError,
2406 "reload() argument must be module");
2407 return NULL;
2409 name = PyModule_GetName(m);
2410 if (name == NULL)
2411 return NULL;
2412 if (m != PyDict_GetItemString(modules, name)) {
2413 PyErr_Format(PyExc_ImportError,
2414 "reload(): module %.200s not in sys.modules",
2415 name);
2416 return NULL;
2418 subname = strrchr(name, '.');
2419 if (subname == NULL)
2420 subname = name;
2421 else {
2422 PyObject *parentname, *parent;
2423 parentname = PyString_FromStringAndSize(name, (subname-name));
2424 if (parentname == NULL)
2425 return NULL;
2426 parent = PyDict_GetItem(modules, parentname);
2427 if (parent == NULL) {
2428 PyErr_Format(PyExc_ImportError,
2429 "reload(): parent %.200s not in sys.modules",
2430 PyString_AS_STRING(parentname));
2431 Py_DECREF(parentname);
2432 return NULL;
2434 Py_DECREF(parentname);
2435 subname++;
2436 path = PyObject_GetAttrString(parent, "__path__");
2437 if (path == NULL)
2438 PyErr_Clear();
2440 buf[0] = '\0';
2441 fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
2442 Py_XDECREF(path);
2444 if (fdp == NULL) {
2445 Py_XDECREF(loader);
2446 return NULL;
2449 newm = load_module(name, fp, buf, fdp->type, loader);
2450 Py_XDECREF(loader);
2452 if (fp)
2453 fclose(fp);
2454 if (newm == NULL) {
2455 /* load_module probably removed name from modules because of
2456 * the error. Put back the original module object. We're
2457 * going to return NULL in this case regardless of whether
2458 * replacing name succeeds, so the return value is ignored.
2460 PyDict_SetItemString(modules, name, m);
2462 return newm;
2466 /* Higher-level import emulator which emulates the "import" statement
2467 more accurately -- it invokes the __import__() function from the
2468 builtins of the current globals. This means that the import is
2469 done using whatever import hooks are installed in the current
2470 environment, e.g. by "rexec".
2471 A dummy list ["__doc__"] is passed as the 4th argument so that
2472 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2473 will return <module "gencache"> instead of <module "win32com">. */
2475 PyObject *
2476 PyImport_Import(PyObject *module_name)
2478 static PyObject *silly_list = NULL;
2479 static PyObject *builtins_str = NULL;
2480 static PyObject *import_str = NULL;
2481 PyObject *globals = NULL;
2482 PyObject *import = NULL;
2483 PyObject *builtins = NULL;
2484 PyObject *r = NULL;
2486 /* Initialize constant string objects */
2487 if (silly_list == NULL) {
2488 import_str = PyString_InternFromString("__import__");
2489 if (import_str == NULL)
2490 return NULL;
2491 builtins_str = PyString_InternFromString("__builtins__");
2492 if (builtins_str == NULL)
2493 return NULL;
2494 silly_list = Py_BuildValue("[s]", "__doc__");
2495 if (silly_list == NULL)
2496 return NULL;
2499 /* Get the builtins from current globals */
2500 globals = PyEval_GetGlobals();
2501 if (globals != NULL) {
2502 Py_INCREF(globals);
2503 builtins = PyObject_GetItem(globals, builtins_str);
2504 if (builtins == NULL)
2505 goto err;
2507 else {
2508 /* No globals -- use standard builtins, and fake globals */
2509 PyErr_Clear();
2511 builtins = PyImport_ImportModuleLevel("__builtin__",
2512 NULL, NULL, NULL, 0);
2513 if (builtins == NULL)
2514 return NULL;
2515 globals = Py_BuildValue("{OO}", builtins_str, builtins);
2516 if (globals == NULL)
2517 goto err;
2520 /* Get the __import__ function from the builtins */
2521 if (PyDict_Check(builtins)) {
2522 import = PyObject_GetItem(builtins, import_str);
2523 if (import == NULL)
2524 PyErr_SetObject(PyExc_KeyError, import_str);
2526 else
2527 import = PyObject_GetAttr(builtins, import_str);
2528 if (import == NULL)
2529 goto err;
2531 /* Call the _import__ function with the proper argument list */
2532 r = PyObject_CallFunctionObjArgs(import, module_name, globals,
2533 globals, silly_list, NULL);
2535 err:
2536 Py_XDECREF(globals);
2537 Py_XDECREF(builtins);
2538 Py_XDECREF(import);
2540 return r;
2544 /* Module 'imp' provides Python access to the primitives used for
2545 importing modules.
2548 static PyObject *
2549 imp_get_magic(PyObject *self, PyObject *noargs)
2551 char buf[4];
2553 buf[0] = (char) ((pyc_magic >> 0) & 0xff);
2554 buf[1] = (char) ((pyc_magic >> 8) & 0xff);
2555 buf[2] = (char) ((pyc_magic >> 16) & 0xff);
2556 buf[3] = (char) ((pyc_magic >> 24) & 0xff);
2558 return PyString_FromStringAndSize(buf, 4);
2561 static PyObject *
2562 imp_get_suffixes(PyObject *self, PyObject *noargs)
2564 PyObject *list;
2565 struct filedescr *fdp;
2567 list = PyList_New(0);
2568 if (list == NULL)
2569 return NULL;
2570 for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
2571 PyObject *item = Py_BuildValue("ssi",
2572 fdp->suffix, fdp->mode, fdp->type);
2573 if (item == NULL) {
2574 Py_DECREF(list);
2575 return NULL;
2577 if (PyList_Append(list, item) < 0) {
2578 Py_DECREF(list);
2579 Py_DECREF(item);
2580 return NULL;
2582 Py_DECREF(item);
2584 return list;
2587 static PyObject *
2588 call_find_module(char *name, PyObject *path)
2590 extern int fclose(FILE *);
2591 PyObject *fob, *ret;
2592 struct filedescr *fdp;
2593 char pathname[MAXPATHLEN+1];
2594 FILE *fp = NULL;
2596 pathname[0] = '\0';
2597 if (path == Py_None)
2598 path = NULL;
2599 fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
2600 if (fdp == NULL)
2601 return NULL;
2602 if (fp != NULL) {
2603 fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
2604 if (fob == NULL) {
2605 fclose(fp);
2606 return NULL;
2609 else {
2610 fob = Py_None;
2611 Py_INCREF(fob);
2613 ret = Py_BuildValue("Os(ssi)",
2614 fob, pathname, fdp->suffix, fdp->mode, fdp->type);
2615 Py_DECREF(fob);
2616 return ret;
2619 static PyObject *
2620 imp_find_module(PyObject *self, PyObject *args)
2622 char *name;
2623 PyObject *path = NULL;
2624 if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
2625 return NULL;
2626 return call_find_module(name, path);
2629 static PyObject *
2630 imp_init_builtin(PyObject *self, PyObject *args)
2632 char *name;
2633 int ret;
2634 PyObject *m;
2635 if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
2636 return NULL;
2637 ret = init_builtin(name);
2638 if (ret < 0)
2639 return NULL;
2640 if (ret == 0) {
2641 Py_INCREF(Py_None);
2642 return Py_None;
2644 m = PyImport_AddModule(name);
2645 Py_XINCREF(m);
2646 return m;
2649 static PyObject *
2650 imp_init_frozen(PyObject *self, PyObject *args)
2652 char *name;
2653 int ret;
2654 PyObject *m;
2655 if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
2656 return NULL;
2657 ret = PyImport_ImportFrozenModule(name);
2658 if (ret < 0)
2659 return NULL;
2660 if (ret == 0) {
2661 Py_INCREF(Py_None);
2662 return Py_None;
2664 m = PyImport_AddModule(name);
2665 Py_XINCREF(m);
2666 return m;
2669 static PyObject *
2670 imp_get_frozen_object(PyObject *self, PyObject *args)
2672 char *name;
2674 if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
2675 return NULL;
2676 return get_frozen_object(name);
2679 static PyObject *
2680 imp_is_builtin(PyObject *self, PyObject *args)
2682 char *name;
2683 if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
2684 return NULL;
2685 return PyInt_FromLong(is_builtin(name));
2688 static PyObject *
2689 imp_is_frozen(PyObject *self, PyObject *args)
2691 char *name;
2692 struct _frozen *p;
2693 if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
2694 return NULL;
2695 p = find_frozen(name);
2696 return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
2699 static FILE *
2700 get_file(char *pathname, PyObject *fob, char *mode)
2702 FILE *fp;
2703 if (fob == NULL) {
2704 if (mode[0] == 'U')
2705 mode = "r" PY_STDIOTEXTMODE;
2706 fp = fopen(pathname, mode);
2707 if (fp == NULL)
2708 PyErr_SetFromErrno(PyExc_IOError);
2710 else {
2711 fp = PyFile_AsFile(fob);
2712 if (fp == NULL)
2713 PyErr_SetString(PyExc_ValueError,
2714 "bad/closed file object");
2716 return fp;
2719 static PyObject *
2720 imp_load_compiled(PyObject *self, PyObject *args)
2722 char *name;
2723 char *pathname;
2724 PyObject *fob = NULL;
2725 PyObject *m;
2726 FILE *fp;
2727 if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
2728 &PyFile_Type, &fob))
2729 return NULL;
2730 fp = get_file(pathname, fob, "rb");
2731 if (fp == NULL)
2732 return NULL;
2733 m = load_compiled_module(name, pathname, fp);
2734 if (fob == NULL)
2735 fclose(fp);
2736 return m;
2739 #ifdef HAVE_DYNAMIC_LOADING
2741 static PyObject *
2742 imp_load_dynamic(PyObject *self, PyObject *args)
2744 char *name;
2745 char *pathname;
2746 PyObject *fob = NULL;
2747 PyObject *m;
2748 FILE *fp = NULL;
2749 if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
2750 &PyFile_Type, &fob))
2751 return NULL;
2752 if (fob) {
2753 fp = get_file(pathname, fob, "r");
2754 if (fp == NULL)
2755 return NULL;
2757 m = _PyImport_LoadDynamicModule(name, pathname, fp);
2758 return m;
2761 #endif /* HAVE_DYNAMIC_LOADING */
2763 static PyObject *
2764 imp_load_source(PyObject *self, PyObject *args)
2766 char *name;
2767 char *pathname;
2768 PyObject *fob = NULL;
2769 PyObject *m;
2770 FILE *fp;
2771 if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
2772 &PyFile_Type, &fob))
2773 return NULL;
2774 fp = get_file(pathname, fob, "r");
2775 if (fp == NULL)
2776 return NULL;
2777 m = load_source_module(name, pathname, fp);
2778 if (fob == NULL)
2779 fclose(fp);
2780 return m;
2783 static PyObject *
2784 imp_load_module(PyObject *self, PyObject *args)
2786 char *name;
2787 PyObject *fob;
2788 char *pathname;
2789 char *suffix; /* Unused */
2790 char *mode;
2791 int type;
2792 FILE *fp;
2794 if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
2795 &name, &fob, &pathname,
2796 &suffix, &mode, &type))
2797 return NULL;
2798 if (*mode) {
2799 /* Mode must start with 'r' or 'U' and must not contain '+'.
2800 Implicit in this test is the assumption that the mode
2801 may contain other modifiers like 'b' or 't'. */
2803 if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
2804 PyErr_Format(PyExc_ValueError,
2805 "invalid file open mode %.200s", mode);
2806 return NULL;
2809 if (fob == Py_None)
2810 fp = NULL;
2811 else {
2812 if (!PyFile_Check(fob)) {
2813 PyErr_SetString(PyExc_ValueError,
2814 "load_module arg#2 should be a file or None");
2815 return NULL;
2817 fp = get_file(pathname, fob, mode);
2818 if (fp == NULL)
2819 return NULL;
2821 return load_module(name, fp, pathname, type, NULL);
2824 static PyObject *
2825 imp_load_package(PyObject *self, PyObject *args)
2827 char *name;
2828 char *pathname;
2829 if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
2830 return NULL;
2831 return load_package(name, pathname);
2834 static PyObject *
2835 imp_new_module(PyObject *self, PyObject *args)
2837 char *name;
2838 if (!PyArg_ParseTuple(args, "s:new_module", &name))
2839 return NULL;
2840 return PyModule_New(name);
2843 /* Doc strings */
2845 PyDoc_STRVAR(doc_imp,
2846 "This module provides the components needed to build your own\n\
2847 __import__ function. Undocumented functions are obsolete.");
2849 PyDoc_STRVAR(doc_find_module,
2850 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2851 Search for a module. If path is omitted or None, search for a\n\
2852 built-in, frozen or special module and continue search in sys.path.\n\
2853 The module name cannot contain '.'; to search for a submodule of a\n\
2854 package, pass the submodule name and the package's __path__.");
2856 PyDoc_STRVAR(doc_load_module,
2857 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2858 Load a module, given information returned by find_module().\n\
2859 The module name must include the full package name, if any.");
2861 PyDoc_STRVAR(doc_get_magic,
2862 "get_magic() -> string\n\
2863 Return the magic number for .pyc or .pyo files.");
2865 PyDoc_STRVAR(doc_get_suffixes,
2866 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2867 Return a list of (suffix, mode, type) tuples describing the files\n\
2868 that find_module() looks for.");
2870 PyDoc_STRVAR(doc_new_module,
2871 "new_module(name) -> module\n\
2872 Create a new module. Do not enter it in sys.modules.\n\
2873 The module name must include the full package name, if any.");
2875 PyDoc_STRVAR(doc_lock_held,
2876 "lock_held() -> boolean\n\
2877 Return True if the import lock is currently held, else False.\n\
2878 On platforms without threads, return False.");
2880 PyDoc_STRVAR(doc_acquire_lock,
2881 "acquire_lock() -> None\n\
2882 Acquires the interpreter's import lock for the current thread.\n\
2883 This lock should be used by import hooks to ensure thread-safety\n\
2884 when importing modules.\n\
2885 On platforms without threads, this function does nothing.");
2887 PyDoc_STRVAR(doc_release_lock,
2888 "release_lock() -> None\n\
2889 Release the interpreter's import lock.\n\
2890 On platforms without threads, this function does nothing.");
2892 static PyMethodDef imp_methods[] = {
2893 {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
2894 {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
2895 {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
2896 {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
2897 {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
2898 {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
2899 {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
2900 {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
2901 /* The rest are obsolete */
2902 {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
2903 {"init_builtin", imp_init_builtin, METH_VARARGS},
2904 {"init_frozen", imp_init_frozen, METH_VARARGS},
2905 {"is_builtin", imp_is_builtin, METH_VARARGS},
2906 {"is_frozen", imp_is_frozen, METH_VARARGS},
2907 {"load_compiled", imp_load_compiled, METH_VARARGS},
2908 #ifdef HAVE_DYNAMIC_LOADING
2909 {"load_dynamic", imp_load_dynamic, METH_VARARGS},
2910 #endif
2911 {"load_package", imp_load_package, METH_VARARGS},
2912 {"load_source", imp_load_source, METH_VARARGS},
2913 {NULL, NULL} /* sentinel */
2916 static int
2917 setint(PyObject *d, char *name, int value)
2919 PyObject *v;
2920 int err;
2922 v = PyInt_FromLong((long)value);
2923 err = PyDict_SetItemString(d, name, v);
2924 Py_XDECREF(v);
2925 return err;
2928 PyMODINIT_FUNC
2929 initimp(void)
2931 PyObject *m, *d;
2933 m = Py_InitModule4("imp", imp_methods, doc_imp,
2934 NULL, PYTHON_API_VERSION);
2935 if (m == NULL)
2936 goto failure;
2937 d = PyModule_GetDict(m);
2939 if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
2940 if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
2941 if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
2942 if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
2943 if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
2944 if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
2945 if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
2946 if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
2947 if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
2948 if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
2950 failure:
2955 /* API for embedding applications that want to add their own entries
2956 to the table of built-in modules. This should normally be called
2957 *before* Py_Initialize(). When the table resize fails, -1 is
2958 returned and the existing table is unchanged.
2960 After a similar function by Just van Rossum. */
2963 PyImport_ExtendInittab(struct _inittab *newtab)
2965 static struct _inittab *our_copy = NULL;
2966 struct _inittab *p;
2967 int i, n;
2969 /* Count the number of entries in both tables */
2970 for (n = 0; newtab[n].name != NULL; n++)
2972 if (n == 0)
2973 return 0; /* Nothing to do */
2974 for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2977 /* Allocate new memory for the combined table */
2978 p = our_copy;
2979 PyMem_RESIZE(p, struct _inittab, i+n+1);
2980 if (p == NULL)
2981 return -1;
2983 /* Copy the tables into the new memory */
2984 if (our_copy != PyImport_Inittab)
2985 memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2986 PyImport_Inittab = our_copy = p;
2987 memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
2989 return 0;
2992 /* Shorthand to add a single entry given a name and a function */
2995 PyImport_AppendInittab(char *name, void (*initfunc)(void))
2997 struct _inittab newtab[2];
2999 memset(newtab, '\0', sizeof newtab);
3001 newtab[0].name = name;
3002 newtab[0].initfunc = initfunc;
3004 return PyImport_ExtendInittab(newtab);
3007 #ifdef __cplusplus
3009 #endif