2 /* Module definition and import implementation */
22 extern time_t PyOS_GetLastModificationTime(char *, FILE *);
25 /* Magic word to reject .pyc files generated by other Python versions */
26 /* Change for each incompatible change */
27 /* The value of CR and LF is incorporated so if you ever read or write
28 a .pyc file in text mode the magic number will be wrong; also, the
29 Apple MPW compiler swaps their values, botching string constants.
30 XXX That probably isn't important anymore.
32 /* XXX Perhaps the magic number should be frozen and a version field
33 added to the .pyc file header? */
34 /* New way to come up with the low 16 bits of the magic number:
35 (YEAR-1995) * 10000 + MONTH * 100 + DAY
36 where MONTH and DAY are 1-based.
37 XXX Whatever the "old way" may have been isn't documented.
38 XXX This scheme breaks in 2002, as (2002-1995)*10000 = 70000 doesn't
40 XXX Later, sometimes 1 gets added to MAGIC in order to record that
41 the Unicode -U option is in use. IMO (Tim's), that's a Bad Idea
42 (quite apart from that the -U option doesn't work so isn't used
45 XXX MAL, 2002-02-07: I had to modify the MAGIC due to a fix of the
46 UTF-8 encoder (it previously produced invalid UTF-8 for unpaired
47 high surrogates), so I simply bumped the month value to 20 (invalid
48 month) and set the day to 1. This should be recognizable by any
49 algorithm relying on the above scheme. Perhaps we should simply
50 start counting in increments of 10 from now on ?!
52 MWH, 2002-08-03: Removed SET_LINENO. Couldn't be bothered figuring
53 out the MAGIC schemes, so just incremented it by 10.
55 GvR, 2002-08-31: Because MWH changed the bytecode again, moved the
56 magic number *back* to 62011. This should get the snake-farm to
57 throw away its old .pyc files, amongst others.
71 Python 2.3a0: 62011 (!)
73 #define MAGIC (62011 | ((long)'\r'<<16) | ((long)'\n'<<24))
75 /* Magic word as global; note that _PyImport_Init() can change the
76 value of this global to accommodate for alterations of how the
77 compiler works which are enabled by command line switches. */
78 static long pyc_magic
= MAGIC
;
80 /* See _PyImport_FixupExtension() below */
81 static PyObject
*extensions
= NULL
;
83 /* This table is defined in config.c: */
84 extern struct _inittab _PyImport_Inittab
[];
86 struct _inittab
*PyImport_Inittab
= _PyImport_Inittab
;
88 /* these tables define the module suffixes that Python recognizes */
89 struct filedescr
* _PyImport_Filetab
= NULL
;
92 static const struct filedescr _PyImport_StandardFiletab
[] = {
93 {"/py", "U", PY_SOURCE
},
94 {"/pyc", "rb", PY_COMPILED
},
98 static const struct filedescr _PyImport_StandardFiletab
[] = {
99 {".py", "U", PY_SOURCE
},
101 {".pyw", "U", PY_SOURCE
},
103 {".pyc", "rb", PY_COMPILED
},
108 /* Initialize things */
113 const struct filedescr
*scan
;
114 struct filedescr
*filetab
;
118 /* prepare _PyImport_Filetab: copy entries from
119 _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
121 for (scan
= _PyImport_DynLoadFiletab
; scan
->suffix
!= NULL
; ++scan
)
123 for (scan
= _PyImport_StandardFiletab
; scan
->suffix
!= NULL
; ++scan
)
125 filetab
= PyMem_NEW(struct filedescr
, countD
+ countS
+ 1);
126 memcpy(filetab
, _PyImport_DynLoadFiletab
,
127 countD
* sizeof(struct filedescr
));
128 memcpy(filetab
+ countD
, _PyImport_StandardFiletab
,
129 countS
* sizeof(struct filedescr
));
130 filetab
[countD
+ countS
].suffix
= NULL
;
132 _PyImport_Filetab
= filetab
;
134 if (Py_OptimizeFlag
) {
135 /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
136 for (; filetab
->suffix
!= NULL
; filetab
++) {
138 if (strcmp(filetab
->suffix
, ".pyc") == 0)
139 filetab
->suffix
= ".pyo";
141 if (strcmp(filetab
->suffix
, "/pyc") == 0)
142 filetab
->suffix
= "/pyo";
147 if (Py_UnicodeFlag
) {
148 /* Fix the pyc_magic so that byte compiled code created
149 using the all-Unicode method doesn't interfere with
150 code created in normal operation mode. */
151 pyc_magic
= MAGIC
+ 1;
156 _PyImportHooks_Init(void)
158 PyObject
*v
, *path_hooks
= NULL
, *zimpimport
;
161 /* adding sys.path_hooks and sys.path_importer_cache, setting up
165 PySys_WriteStderr("# installing zipimport hook\n");
170 err
= PySys_SetObject("meta_path", v
);
177 err
= PySys_SetObject("path_importer_cache", v
);
181 path_hooks
= PyList_New(0);
182 if (path_hooks
== NULL
)
184 err
= PySys_SetObject("path_hooks", path_hooks
);
188 Py_FatalError("initializing sys.meta_path, sys.path_hooks or "
189 "path_importer_cache failed");
191 zimpimport
= PyImport_ImportModule("zipimport");
192 if (zimpimport
== NULL
) {
193 PyErr_Clear(); /* No zip import module -- okay */
195 PySys_WriteStderr("# can't import zipimport\n");
198 PyObject
*zipimporter
= PyObject_GetAttrString(zimpimport
,
200 Py_DECREF(zimpimport
);
201 if (zipimporter
== NULL
) {
202 PyErr_Clear(); /* No zipimporter object -- okay */
205 "# can't import zipimport.zimimporter\n");
208 /* sys.path_hooks.append(zipimporter) */
209 err
= PyList_Append(path_hooks
, zipimporter
);
210 Py_DECREF(zipimporter
);
215 "# installed zipimport hook\n");
218 Py_DECREF(path_hooks
);
224 Py_XDECREF(extensions
);
226 PyMem_DEL(_PyImport_Filetab
);
227 _PyImport_Filetab
= NULL
;
231 /* Locking primitives to prevent parallel imports of the same module
232 in different threads to return with a partially loaded module.
233 These calls are serialized by the global interpreter lock. */
237 #include "pythread.h"
239 static PyThread_type_lock import_lock
= 0;
240 static long import_lock_thread
= -1;
241 static int import_lock_level
= 0;
246 long me
= PyThread_get_thread_ident();
248 return; /* Too bad */
249 if (import_lock
== NULL
)
250 import_lock
= PyThread_allocate_lock();
251 if (import_lock_thread
== me
) {
255 if (import_lock_thread
!= -1 || !PyThread_acquire_lock(import_lock
, 0))
257 PyThreadState
*tstate
= PyEval_SaveThread();
258 PyThread_acquire_lock(import_lock
, 1);
259 PyEval_RestoreThread(tstate
);
261 import_lock_thread
= me
;
262 import_lock_level
= 1;
268 long me
= PyThread_get_thread_ident();
270 return 0; /* Too bad */
271 if (import_lock_thread
!= me
)
274 if (import_lock_level
== 0) {
275 import_lock_thread
= -1;
276 PyThread_release_lock(import_lock
);
283 #define lock_import()
284 #define unlock_import() 0
289 imp_lock_held(PyObject
*self
, PyObject
*noargs
)
292 return PyBool_FromLong(import_lock_thread
!= -1);
294 return PyBool_FromLong(0);
299 imp_acquire_lock(PyObject
*self
, PyObject
*noargs
)
309 imp_release_lock(PyObject
*self
, PyObject
*noargs
)
312 if (unlock_import() < 0) {
313 PyErr_SetString(PyExc_RuntimeError
,
314 "not holding the import lock");
325 PyImport_GetModuleDict(void)
327 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
328 if (interp
->modules
== NULL
)
329 Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
330 return interp
->modules
;
334 /* List of names to clear in sys */
335 static char* sys_deletes
[] = {
336 "path", "argv", "ps1", "ps2", "exitfunc",
337 "exc_type", "exc_value", "exc_traceback",
338 "last_type", "last_value", "last_traceback",
339 "path_hooks", "path_importer_cache", "meta_path",
343 static char* sys_files
[] = {
344 "stdin", "__stdin__",
345 "stdout", "__stdout__",
346 "stderr", "__stderr__",
351 /* Un-initialize things, as good as we can */
354 PyImport_Cleanup(void)
358 PyObject
*key
, *value
, *dict
;
359 PyInterpreterState
*interp
= PyThreadState_Get()->interp
;
360 PyObject
*modules
= interp
->modules
;
363 return; /* Already done */
365 /* Delete some special variables first. These are common
366 places where user values hide and people complain when their
367 destructors fail. Since the modules containing them are
368 deleted *last* of all, they would come too late in the normal
369 destruction order. Sigh. */
371 value
= PyDict_GetItemString(modules
, "__builtin__");
372 if (value
!= NULL
&& PyModule_Check(value
)) {
373 dict
= PyModule_GetDict(value
);
375 PySys_WriteStderr("# clear __builtin__._\n");
376 PyDict_SetItemString(dict
, "_", Py_None
);
378 value
= PyDict_GetItemString(modules
, "sys");
379 if (value
!= NULL
&& PyModule_Check(value
)) {
382 dict
= PyModule_GetDict(value
);
383 for (p
= sys_deletes
; *p
!= NULL
; p
++) {
385 PySys_WriteStderr("# clear sys.%s\n", *p
);
386 PyDict_SetItemString(dict
, *p
, Py_None
);
388 for (p
= sys_files
; *p
!= NULL
; p
+=2) {
390 PySys_WriteStderr("# restore sys.%s\n", *p
);
391 v
= PyDict_GetItemString(dict
, *(p
+1));
394 PyDict_SetItemString(dict
, *p
, v
);
398 /* First, delete __main__ */
399 value
= PyDict_GetItemString(modules
, "__main__");
400 if (value
!= NULL
&& PyModule_Check(value
)) {
402 PySys_WriteStderr("# cleanup __main__\n");
403 _PyModule_Clear(value
);
404 PyDict_SetItemString(modules
, "__main__", Py_None
);
407 /* The special treatment of __builtin__ here is because even
408 when it's not referenced as a module, its dictionary is
409 referenced by almost every module's __builtins__. Since
410 deleting a module clears its dictionary (even if there are
411 references left to it), we need to delete the __builtin__
412 module last. Likewise, we don't delete sys until the very
413 end because it is implicitly referenced (e.g. by print).
415 Also note that we 'delete' modules by replacing their entry
416 in the modules dict with None, rather than really deleting
417 them; this avoids a rehash of the modules dictionary and
418 also marks them as "non existent" so they won't be
421 /* Next, repeatedly delete modules with a reference count of
422 one (skipping __builtin__ and sys) and delete them */
426 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
427 if (value
->ob_refcnt
!= 1)
429 if (PyString_Check(key
) && PyModule_Check(value
)) {
430 name
= PyString_AS_STRING(key
);
431 if (strcmp(name
, "__builtin__") == 0)
433 if (strcmp(name
, "sys") == 0)
437 "# cleanup[1] %s\n", name
);
438 _PyModule_Clear(value
);
439 PyDict_SetItem(modules
, key
, Py_None
);
445 /* Next, delete all modules (still skipping __builtin__ and sys) */
447 while (PyDict_Next(modules
, &pos
, &key
, &value
)) {
448 if (PyString_Check(key
) && PyModule_Check(value
)) {
449 name
= PyString_AS_STRING(key
);
450 if (strcmp(name
, "__builtin__") == 0)
452 if (strcmp(name
, "sys") == 0)
455 PySys_WriteStderr("# cleanup[2] %s\n", name
);
456 _PyModule_Clear(value
);
457 PyDict_SetItem(modules
, key
, Py_None
);
461 /* Next, delete sys and __builtin__ (in that order) */
462 value
= PyDict_GetItemString(modules
, "sys");
463 if (value
!= NULL
&& PyModule_Check(value
)) {
465 PySys_WriteStderr("# cleanup sys\n");
466 _PyModule_Clear(value
);
467 PyDict_SetItemString(modules
, "sys", Py_None
);
469 value
= PyDict_GetItemString(modules
, "__builtin__");
470 if (value
!= NULL
&& PyModule_Check(value
)) {
472 PySys_WriteStderr("# cleanup __builtin__\n");
473 _PyModule_Clear(value
);
474 PyDict_SetItemString(modules
, "__builtin__", Py_None
);
477 /* Finally, clear and delete the modules directory */
478 PyDict_Clear(modules
);
479 interp
->modules
= NULL
;
484 /* Helper for pythonrun.c -- return magic number */
487 PyImport_GetMagicNumber(void)
493 /* Magic for extension modules (built-in as well as dynamically
494 loaded). To prevent initializing an extension module more than
495 once, we keep a static dictionary 'extensions' keyed by module name
496 (for built-in modules) or by filename (for dynamically loaded
497 modules), containing these modules. A copy of the module's
498 dictionary is stored by calling _PyImport_FixupExtension()
499 immediately after the module initialization function succeeds. A
500 copy can be retrieved from there by calling
501 _PyImport_FindExtension(). */
504 _PyImport_FixupExtension(char *name
, char *filename
)
506 PyObject
*modules
, *mod
, *dict
, *copy
;
507 if (extensions
== NULL
) {
508 extensions
= PyDict_New();
509 if (extensions
== NULL
)
512 modules
= PyImport_GetModuleDict();
513 mod
= PyDict_GetItemString(modules
, name
);
514 if (mod
== NULL
|| !PyModule_Check(mod
)) {
515 PyErr_Format(PyExc_SystemError
,
516 "_PyImport_FixupExtension: module %.200s not loaded", name
);
519 dict
= PyModule_GetDict(mod
);
522 copy
= PyDict_Copy(dict
);
525 PyDict_SetItemString(extensions
, filename
, copy
);
531 _PyImport_FindExtension(char *name
, char *filename
)
533 PyObject
*dict
, *mod
, *mdict
;
534 if (extensions
== NULL
)
536 dict
= PyDict_GetItemString(extensions
, filename
);
539 mod
= PyImport_AddModule(name
);
542 mdict
= PyModule_GetDict(mod
);
545 if (PyDict_Update(mdict
, dict
))
548 PySys_WriteStderr("import %s # previously loaded (%s)\n",
554 /* Get the module object corresponding to a module name.
555 First check the modules dictionary if there's one there,
556 if not, create a new one and insert in in the modules dictionary.
557 Because the former action is most common, THIS DOES NOT RETURN A
561 PyImport_AddModule(char *name
)
563 PyObject
*modules
= PyImport_GetModuleDict();
566 if ((m
= PyDict_GetItemString(modules
, name
)) != NULL
&&
569 m
= PyModule_New(name
);
572 if (PyDict_SetItemString(modules
, name
, m
) != 0) {
576 Py_DECREF(m
); /* Yes, it still exists, in modules! */
582 /* Execute a code object in a module and return the module object
583 WITH INCREMENTED REFERENCE COUNT */
586 PyImport_ExecCodeModule(char *name
, PyObject
*co
)
588 return PyImport_ExecCodeModuleEx(name
, co
, (char *)NULL
);
592 PyImport_ExecCodeModuleEx(char *name
, PyObject
*co
, char *pathname
)
594 PyObject
*modules
= PyImport_GetModuleDict();
597 m
= PyImport_AddModule(name
);
600 d
= PyModule_GetDict(m
);
601 if (PyDict_GetItemString(d
, "__builtins__") == NULL
) {
602 if (PyDict_SetItemString(d
, "__builtins__",
603 PyEval_GetBuiltins()) != 0)
606 /* Remember the filename as the __file__ attribute */
608 if (pathname
!= NULL
) {
609 v
= PyString_FromString(pathname
);
614 v
= ((PyCodeObject
*)co
)->co_filename
;
617 if (PyDict_SetItemString(d
, "__file__", v
) != 0)
618 PyErr_Clear(); /* Not important enough to report */
621 v
= PyEval_EvalCode((PyCodeObject
*)co
, d
, d
);
626 if ((m
= PyDict_GetItemString(modules
, name
)) == NULL
) {
627 PyErr_Format(PyExc_ImportError
,
628 "Loaded module %.200s not found in sys.modules",
639 /* Given a pathname for a Python source file, fill a buffer with the
640 pathname for the corresponding compiled file. Return the pathname
641 for the compiled file, or NULL if there's no space in the buffer.
642 Doesn't set an exception. */
645 make_compiled_pathname(char *pathname
, char *buf
, size_t buflen
)
647 size_t len
= strlen(pathname
);
652 /* Treat .pyw as if it were .py. The case of ".pyw" must match
653 that used in _PyImport_StandardFiletab. */
654 if (len
>= 4 && strcmp(&pathname
[len
-4], ".pyw") == 0)
655 --len
; /* pretend 'w' isn't there */
657 memcpy(buf
, pathname
, len
);
658 buf
[len
] = Py_OptimizeFlag
? 'o' : 'c';
665 /* Given a pathname for a Python source file, its time of last
666 modification, and a pathname for a compiled file, check whether the
667 compiled file represents the same version of the source. If so,
668 return a FILE pointer for the compiled file, positioned just after
669 the header; if not, return NULL.
670 Doesn't set an exception. */
673 check_compiled_module(char *pathname
, long mtime
, char *cpathname
)
679 fp
= fopen(cpathname
, "rb");
682 magic
= PyMarshal_ReadLongFromFile(fp
);
683 if (magic
!= pyc_magic
) {
685 PySys_WriteStderr("# %s has bad magic\n", cpathname
);
689 pyc_mtime
= PyMarshal_ReadLongFromFile(fp
);
690 if (pyc_mtime
!= mtime
) {
692 PySys_WriteStderr("# %s has bad mtime\n", cpathname
);
697 PySys_WriteStderr("# %s matches %s\n", cpathname
, pathname
);
702 /* Read a code object from a file and check it for validity */
704 static PyCodeObject
*
705 read_compiled_module(char *cpathname
, FILE *fp
)
709 co
= PyMarshal_ReadLastObjectFromFile(fp
);
710 /* Ugly: rd_object() may return NULL with or without error */
711 if (co
== NULL
|| !PyCode_Check(co
)) {
712 if (!PyErr_Occurred())
713 PyErr_Format(PyExc_ImportError
,
714 "Non-code object in %.200s", cpathname
);
718 return (PyCodeObject
*)co
;
722 /* Load a module from a compiled file, execute it, and return its
723 module object WITH INCREMENTED REFERENCE COUNT */
726 load_compiled_module(char *name
, char *cpathname
, FILE *fp
)
732 magic
= PyMarshal_ReadLongFromFile(fp
);
733 if (magic
!= pyc_magic
) {
734 PyErr_Format(PyExc_ImportError
,
735 "Bad magic number in %.200s", cpathname
);
738 (void) PyMarshal_ReadLongFromFile(fp
);
739 co
= read_compiled_module(cpathname
, fp
);
743 PySys_WriteStderr("import %s # precompiled from %s\n",
745 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, cpathname
);
751 /* Parse a source file and return the corresponding code object */
753 static PyCodeObject
*
754 parse_source_module(char *pathname
, FILE *fp
)
759 n
= PyParser_SimpleParseFile(fp
, pathname
, Py_file_input
);
762 co
= PyNode_Compile(n
, pathname
);
769 /* Helper to open a bytecode file for writing in exclusive mode */
772 open_exclusive(char *filename
)
774 #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
775 /* Use O_EXCL to avoid a race condition when another process tries to
776 write the same file. When that happens, our open() call fails,
777 which is just fine (since it's only a cache).
778 XXX If the file exists and is writable but the directory is not
779 writable, the file will never be written. Oh well.
782 (void) unlink(filename
);
783 fd
= open(filename
, O_EXCL
|O_CREAT
|O_WRONLY
|O_TRUNC
785 |O_BINARY
/* necessary for Windows */
788 , 0666, "ctxt=bin", "shr=nil");
794 return fdopen(fd
, "wb");
796 /* Best we can do -- on Windows this can't happen anyway */
797 return fopen(filename
, "wb");
802 /* Write a compiled module to a file, placing the time of last
803 modification of its source into the header.
804 Errors are ignored, if a write error occurs an attempt is made to
808 write_compiled_module(PyCodeObject
*co
, char *cpathname
, long mtime
)
812 fp
= open_exclusive(cpathname
);
816 "# can't create %s\n", cpathname
);
819 PyMarshal_WriteLongToFile(pyc_magic
, fp
);
820 /* First write a 0 for mtime */
821 PyMarshal_WriteLongToFile(0L, fp
);
822 PyMarshal_WriteObjectToFile((PyObject
*)co
, fp
);
825 PySys_WriteStderr("# can't write %s\n", cpathname
);
826 /* Don't keep partial file */
828 (void) unlink(cpathname
);
831 /* Now write the true mtime */
833 PyMarshal_WriteLongToFile(mtime
, fp
);
837 PySys_WriteStderr("# wrote %s\n", cpathname
);
839 PyMac_setfiletype(cpathname
, 'Pyth', 'PYC ');
844 /* Load a source module from a given file and return its module
845 object WITH INCREMENTED REFERENCE COUNT. If there's a matching
846 byte-compiled file, use that instead. */
849 load_source_module(char *name
, char *pathname
, FILE *fp
)
853 char buf
[MAXPATHLEN
+1];
858 mtime
= PyOS_GetLastModificationTime(pathname
, fp
);
859 if (mtime
== (time_t)(-1))
861 #if SIZEOF_TIME_T > 4
862 /* Python's .pyc timestamp handling presumes that the timestamp fits
863 in 4 bytes. This will be fine until sometime in the year 2038,
864 when a 4-byte signed time_t will overflow.
867 PyErr_SetString(PyExc_OverflowError
,
868 "modification time overflows a 4 byte field");
872 cpathname
= make_compiled_pathname(pathname
, buf
,
873 (size_t)MAXPATHLEN
+ 1);
874 if (cpathname
!= NULL
&&
875 (fpc
= check_compiled_module(pathname
, mtime
, cpathname
))) {
876 co
= read_compiled_module(cpathname
, fpc
);
881 PySys_WriteStderr("import %s # precompiled from %s\n",
883 pathname
= cpathname
;
886 co
= parse_source_module(pathname
, fp
);
890 PySys_WriteStderr("import %s # from %s\n",
892 write_compiled_module(co
, cpathname
, mtime
);
894 m
= PyImport_ExecCodeModuleEx(name
, (PyObject
*)co
, pathname
);
902 static PyObject
*load_module(char *, FILE *, char *, int, PyObject
*);
903 static struct filedescr
*find_module(char *, char *, PyObject
*,
904 char *, size_t, FILE **, PyObject
**);
905 static struct _frozen
*find_frozen(char *name
);
907 /* Load a package and return its module object WITH INCREMENTED
911 load_package(char *name
, char *pathname
)
913 PyObject
*m
, *d
, *file
, *path
;
915 char buf
[MAXPATHLEN
+1];
917 struct filedescr
*fdp
;
919 m
= PyImport_AddModule(name
);
923 PySys_WriteStderr("import %s # directory %s\n",
925 d
= PyModule_GetDict(m
);
926 file
= PyString_FromString(pathname
);
929 path
= Py_BuildValue("[O]", file
);
934 err
= PyDict_SetItemString(d
, "__file__", file
);
936 err
= PyDict_SetItemString(d
, "__path__", path
);
942 fdp
= find_module(name
, "__init__", path
, buf
, sizeof(buf
), &fp
, NULL
);
944 if (PyErr_ExceptionMatches(PyExc_ImportError
)) {
951 m
= load_module(name
, fp
, buf
, fdp
->type
, NULL
);
961 /* Helper to test for built-in module */
964 is_builtin(char *name
)
967 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++) {
968 if (strcmp(name
, PyImport_Inittab
[i
].name
) == 0) {
969 if (PyImport_Inittab
[i
].initfunc
== NULL
)
979 /* Return an importer object for a sys.path/pkg.__path__ item 'p',
980 possibly by fetching it from the path_importer_cache dict. If it
981 wasn't yet cached, traverse path_hooks until it a hook is found
982 that can handle the path item. Return None if no hook could;
983 this tells our caller it should fall back to the builtin
984 import mechanism. Cache the result in path_importer_cache.
985 Returns a borrowed reference. */
988 get_path_importer(PyObject
*path_importer_cache
, PyObject
*path_hooks
,
994 /* These conditions are the caller's responsibility: */
995 assert(PyList_Check(path_hooks
));
996 assert(PyDict_Check(path_importer_cache
));
998 nhooks
= PyList_Size(path_hooks
);
1000 return NULL
; /* Shouldn't happen */
1002 importer
= PyDict_GetItem(path_importer_cache
, p
);
1003 if (importer
!= NULL
)
1006 /* set path_importer_cache[p] to None to avoid recursion */
1007 if (PyDict_SetItem(path_importer_cache
, p
, Py_None
) != 0)
1010 for (j
= 0; j
< nhooks
; j
++) {
1011 PyObject
*hook
= PyList_GetItem(path_hooks
, j
);
1014 importer
= PyObject_CallFunction(hook
, "O", p
);
1015 if (importer
!= NULL
)
1018 if (!PyErr_ExceptionMatches(PyExc_ImportError
)) {
1023 if (importer
== NULL
)
1025 else if (importer
!= Py_None
) {
1026 int err
= PyDict_SetItem(path_importer_cache
, p
, importer
);
1027 Py_DECREF(importer
);
1034 /* Search the path (default sys.path) for a module. Return the
1035 corresponding filedescr struct, and (via return arguments) the
1036 pathname and an open file. Return NULL if the module is not found. */
1039 extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr
**,
1043 static int case_ok(char *, int, int, char *);
1044 static int find_init_module(char *); /* Forward */
1045 static struct filedescr importhookdescr
= {"", "", IMP_HOOK
};
1047 static struct filedescr
*
1048 find_module(char *fullname
, char *subname
, PyObject
*path
, char *buf
,
1049 size_t buflen
, FILE **p_fp
, PyObject
**p_loader
)
1052 size_t len
, namelen
;
1053 struct filedescr
*fdp
= NULL
;
1056 PyObject
*path_hooks
, *path_importer_cache
;
1058 struct stat statbuf
;
1060 static struct filedescr fd_frozen
= {"", "", PY_FROZEN
};
1061 static struct filedescr fd_builtin
= {"", "", C_BUILTIN
};
1062 static struct filedescr fd_package
= {"", "", PKG_DIRECTORY
};
1063 char name
[MAXPATHLEN
+1];
1064 #if defined(PYOS_OS2)
1066 size_t saved_namelen
;
1067 char *saved_buf
= NULL
;
1069 if (p_loader
!= NULL
)
1072 if (strlen(subname
) > MAXPATHLEN
) {
1073 PyErr_SetString(PyExc_OverflowError
,
1074 "module name is too long");
1077 strcpy(name
, subname
);
1079 /* sys.meta_path import hook */
1080 if (p_loader
!= NULL
) {
1081 PyObject
*meta_path
;
1083 meta_path
= PySys_GetObject("meta_path");
1084 if (meta_path
== NULL
|| !PyList_Check(meta_path
)) {
1085 PyErr_SetString(PyExc_ImportError
,
1086 "sys.meta_path must be a list of "
1090 Py_INCREF(meta_path
); /* zap guard */
1091 npath
= PyList_Size(meta_path
);
1092 for (i
= 0; i
< npath
; i
++) {
1094 PyObject
*hook
= PyList_GetItem(meta_path
, i
);
1095 loader
= PyObject_CallMethod(hook
, "find_module",
1099 if (loader
== NULL
) {
1100 Py_DECREF(meta_path
);
1101 return NULL
; /* true error */
1103 if (loader
!= Py_None
) {
1104 /* a loader was found */
1106 Py_DECREF(meta_path
);
1107 return &importhookdescr
;
1111 Py_DECREF(meta_path
);
1114 if (path
!= NULL
&& PyString_Check(path
)) {
1115 /* The only type of submodule allowed inside a "frozen"
1116 package are other frozen modules or packages. */
1117 if (PyString_Size(path
) + 1 + strlen(name
) >= (size_t)buflen
) {
1118 PyErr_SetString(PyExc_ImportError
,
1119 "full frozen module name too long");
1122 strcpy(buf
, PyString_AsString(path
));
1127 /* Freezing on the mac works different, and the modules are
1128 ** actually on sys.path. So we don't take the quick exit but
1129 ** continue with the normal flow.
1133 if (find_frozen(name
) != NULL
) {
1137 PyErr_Format(PyExc_ImportError
,
1138 "No frozen submodule named %.200s", name
);
1143 if (is_builtin(name
)) {
1147 if ((find_frozen(name
)) != NULL
) {
1153 fp
= PyWin_FindRegisteredModule(name
, &fdp
, buf
, buflen
);
1159 path
= PySys_GetObject("path");
1161 if (path
== NULL
|| !PyList_Check(path
)) {
1162 PyErr_SetString(PyExc_ImportError
,
1163 "sys.path must be a list of directory names");
1167 path_hooks
= PySys_GetObject("path_hooks");
1168 if (path_hooks
== NULL
|| !PyList_Check(path_hooks
)) {
1169 PyErr_SetString(PyExc_ImportError
,
1170 "sys.path_hooks must be a list of "
1174 path_importer_cache
= PySys_GetObject("path_importer_cache");
1175 if (path_importer_cache
== NULL
||
1176 !PyDict_Check(path_importer_cache
)) {
1177 PyErr_SetString(PyExc_ImportError
,
1178 "sys.path_importer_cache must be a dict");
1182 npath
= PyList_Size(path
);
1183 namelen
= strlen(name
);
1184 for (i
= 0; i
< npath
; i
++) {
1185 PyObject
*copy
= NULL
;
1186 PyObject
*v
= PyList_GetItem(path
, i
);
1187 #ifdef Py_USING_UNICODE
1188 if (PyUnicode_Check(v
)) {
1189 copy
= PyUnicode_Encode(PyUnicode_AS_UNICODE(v
),
1190 PyUnicode_GET_SIZE(v
), Py_FileSystemDefaultEncoding
, NULL
);
1197 if (!PyString_Check(v
))
1199 len
= PyString_Size(v
);
1200 if (len
+ 2 + namelen
+ MAXSUFFIXSIZE
>= buflen
) {
1202 continue; /* Too long */
1204 strcpy(buf
, PyString_AsString(v
));
1205 if (strlen(buf
) != len
) {
1207 continue; /* v contains '\0' */
1210 /* sys.path_hooks import hook */
1211 if (p_loader
!= NULL
) {
1214 importer
= get_path_importer(path_importer_cache
,
1216 if (importer
== NULL
)
1218 /* Note: importer is a borrowed reference */
1219 if (importer
!= Py_None
) {
1221 loader
= PyObject_CallMethod(importer
,
1225 return NULL
; /* error */
1226 if (loader
!= Py_None
) {
1227 /* a loader was found */
1229 return &importhookdescr
;
1233 /* no hook was successful, use builtin import */
1238 ** Speedup: each sys.path item is interned, and
1239 ** FindResourceModule remembers which items refer to
1240 ** folders (so we don't have to bother trying to look
1241 ** into them for resources). We only do this for string
1244 if (PyString_Check(PyList_GET_ITEM(path
, i
))) {
1245 PyString_InternInPlace(&PyList_GET_ITEM(path
, i
));
1246 v
= PyList_GET_ITEM(path
, i
);
1247 if (PyMac_FindResourceModule((PyStringObject
*)v
, name
, buf
)) {
1248 static struct filedescr resfiledescr
=
1249 {"", "", PY_RESOURCE
};
1252 return &resfiledescr
;
1254 if (PyMac_FindCodeResourceModule((PyStringObject
*)v
, name
, buf
)) {
1255 static struct filedescr resfiledescr
=
1256 {"", "", PY_CODERESOURCE
};
1259 return &resfiledescr
;
1263 if (len
> 0 && buf
[len
-1] != SEP
1265 && buf
[len
-1] != ALTSEP
1269 strcpy(buf
+len
, name
);
1272 /* Check for package import (buf holds a directory name,
1273 and there's an __init__ module in that directory */
1275 if (stat(buf
, &statbuf
) == 0 && /* it exists */
1276 S_ISDIR(statbuf
.st_mode
) && /* it's a directory */
1277 find_init_module(buf
) && /* it has __init__.py */
1278 case_ok(buf
, len
, namelen
, name
)) { /* and case matches */
1283 /* XXX How are you going to test for directories? */
1286 find_init_module(buf
) &&
1287 case_ok(buf
, len
, namelen
, name
)) {
1294 fdp
= PyMac_FindModuleExtension(buf
, &len
, name
);
1297 #if defined(PYOS_OS2)
1298 /* take a snapshot of the module spec for restoration
1299 * after the 8 character DLL hackery
1301 saved_buf
= strdup(buf
);
1303 saved_namelen
= namelen
;
1304 #endif /* PYOS_OS2 */
1305 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
1306 #if defined(PYOS_OS2)
1307 /* OS/2 limits DLLs to 8 character names (w/o
1309 * so if the name is longer than that and its a
1310 * dynamically loaded module we're going to try,
1311 * truncate the name before trying
1313 if (strlen(subname
) > 8) {
1314 /* is this an attempt to load a C extension? */
1315 const struct filedescr
*scan
;
1316 scan
= _PyImport_DynLoadFiletab
;
1317 while (scan
->suffix
!= NULL
) {
1318 if (!strcmp(scan
->suffix
, fdp
->suffix
))
1323 if (scan
->suffix
!= NULL
) {
1324 /* yes, so truncate the name */
1326 len
-= strlen(subname
) - namelen
;
1330 #endif /* PYOS_OS2 */
1331 strcpy(buf
+len
, fdp
->suffix
);
1332 if (Py_VerboseFlag
> 1)
1333 PySys_WriteStderr("# trying %s\n", buf
);
1334 #endif /* !macintosh */
1335 filemode
= fdp
->mode
;
1336 if (filemode
[0] == 'U')
1337 filemode
= "r" PY_STDIOTEXTMODE
;
1338 fp
= fopen(buf
, filemode
);
1340 if (case_ok(buf
, len
, namelen
, name
))
1342 else { /* continue search */
1347 #if defined(PYOS_OS2)
1348 /* restore the saved snapshot */
1349 strcpy(buf
, saved_buf
);
1351 namelen
= saved_namelen
;
1354 #if defined(PYOS_OS2)
1355 /* don't need/want the module name snapshot anymore */
1367 PyErr_Format(PyExc_ImportError
,
1368 "No module named %.200s", name
);
1375 /* case_ok(char* buf, int len, int namelen, char* name)
1376 * The arguments here are tricky, best shown by example:
1377 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1379 * |--------------------- buf ---------------------|
1380 * |------------------- len ------------------|
1381 * |------ name -------|
1382 * |----- namelen -----|
1383 * buf is the full path, but len only counts up to (& exclusive of) the
1384 * extension. name is the module name, also exclusive of extension.
1386 * We've already done a successful stat() or fopen() on buf, so know that
1387 * there's some match, possibly case-insensitive.
1389 * case_ok() is to return 1 if there's a case-sensitive match for
1390 * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
1393 * case_ok() is used to implement case-sensitive import semantics even
1394 * on platforms with case-insensitive filesystems. It's trivial to implement
1395 * for case-sensitive filesystems. It's pretty much a cross-platform
1396 * nightmare for systems with case-insensitive filesystems.
1399 /* First we may need a pile of platform-specific header files; the sequence
1400 * of #if's here should match the sequence in the body of case_ok().
1402 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
1403 #include <windows.h>
1405 #include <sys/cygwin.h>
1408 #elif defined(DJGPP)
1411 #elif defined(macintosh)
1412 #include <TextUtils.h>
1414 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1415 #include <sys/types.h>
1418 #elif defined(PYOS_OS2)
1420 #define INCL_DOSERRORS
1421 #define INCL_NOPMAPI
1424 #elif defined(RISCOS)
1425 #include "oslib/osfscontrol.h"
1429 case_ok(char *buf
, int len
, int namelen
, char *name
)
1431 /* Pick a platform-specific implementation; the sequence of #if's here should
1432 * match the sequence just above.
1435 /* MS_WINDOWS || __CYGWIN__ */
1436 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
1437 WIN32_FIND_DATA data
;
1440 char tempbuf
[MAX_PATH
];
1443 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1447 cygwin32_conv_to_win32_path(buf
, tempbuf
);
1448 h
= FindFirstFile(tempbuf
, &data
);
1450 h
= FindFirstFile(buf
, &data
);
1452 if (h
== INVALID_HANDLE_VALUE
) {
1453 PyErr_Format(PyExc_NameError
,
1454 "Can't find file for module %.100s\n(filename %.300s)",
1459 return strncmp(data
.cFileName
, name
, namelen
) == 0;
1462 #elif defined(DJGPP)
1466 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1469 done
= findfirst(buf
, &ffblk
, FA_ARCH
|FA_RDONLY
|FA_HIDDEN
|FA_DIREC
);
1471 PyErr_Format(PyExc_NameError
,
1472 "Can't find file for module %.100s\n(filename %.300s)",
1476 return strncmp(ffblk
.ff_name
, name
, namelen
) == 0;
1479 #elif defined(macintosh)
1483 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1486 err
= FSMakeFSSpec(0, 0, Pstring(buf
), &fss
);
1488 PyErr_Format(PyExc_NameError
,
1489 "Can't find file for module %.100s\n(filename %.300s)",
1493 return fss
.name
[0] >= namelen
&&
1494 strncmp(name
, (char *)fss
.name
+1, namelen
) == 0;
1496 /* new-fangled macintosh (macosx) */
1497 #elif defined(__MACH__) && defined(__APPLE__) && defined(HAVE_DIRENT_H)
1500 char dirname
[MAXPATHLEN
+ 1];
1501 const int dirlen
= len
- namelen
- 1; /* don't want trailing SEP */
1503 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1506 /* Copy the dir component into dirname; substitute "." if empty */
1512 assert(dirlen
<= MAXPATHLEN
);
1513 memcpy(dirname
, buf
, dirlen
);
1514 dirname
[dirlen
] = '\0';
1516 /* Open the directory and search the entries for an exact match. */
1517 dirp
= opendir(dirname
);
1519 char *nameWithExt
= buf
+ len
- namelen
;
1520 while ((dp
= readdir(dirp
)) != NULL
) {
1522 #ifdef _DIRENT_HAVE_D_NAMELEN
1527 if (thislen
>= namelen
&&
1528 strcmp(dp
->d_name
, nameWithExt
) == 0) {
1529 (void)closedir(dirp
);
1530 return 1; /* Found */
1533 (void)closedir(dirp
);
1535 return 0 ; /* Not found */
1538 #elif defined(RISCOS)
1539 char canon
[MAXPATHLEN
+1]; /* buffer for the canonical form of the path */
1540 char buf2
[MAXPATHLEN
+2];
1541 char *nameWithExt
= buf
+len
-namelen
;
1545 if (Py_GETENV("PYTHONCASEOK") != NULL
)
1549 append wildcard, otherwise case of filename wouldn't be touched */
1553 e
= xosfscontrol_canonicalise_path(buf2
,canon
,0,0,MAXPATHLEN
+1,&canonlen
);
1554 canonlen
= MAXPATHLEN
+1-canonlen
;
1555 if (e
|| canonlen
<=0 || canonlen
>(MAXPATHLEN
+1) )
1557 if (strcmp(nameWithExt
, canon
+canonlen
-strlen(nameWithExt
))==0)
1558 return 1; /* match */
1563 #elif defined(PYOS_OS2)
1569 if (getenv("PYTHONCASEOK") != NULL
)
1572 rc
= DosFindFirst(buf
,
1574 FILE_READONLY
| FILE_HIDDEN
| FILE_SYSTEM
| FILE_DIRECTORY
,
1575 &ffbuf
, sizeof(ffbuf
),
1580 return strncmp(ffbuf
.achName
, name
, namelen
) == 0;
1582 /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
1591 /* Helper to look for __init__.py or __init__.py[co] in potential package */
1593 find_init_module(char *buf
)
1595 const size_t save_len
= strlen(buf
);
1596 size_t i
= save_len
;
1597 char *pname
; /* pointer to start of __init__ */
1598 struct stat statbuf
;
1600 /* For calling case_ok(buf, len, namelen, name):
1601 * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
1603 * |--------------------- buf ---------------------|
1604 * |------------------- len ------------------|
1605 * |------ name -------|
1606 * |----- namelen -----|
1608 if (save_len
+ 13 >= MAXPATHLEN
)
1612 strcpy(pname
, "__init__.py");
1613 if (stat(buf
, &statbuf
) == 0) {
1615 save_len
+ 9, /* len("/__init__") */
1616 8, /* len("__init__") */
1618 buf
[save_len
] = '\0';
1623 strcpy(buf
+i
, Py_OptimizeFlag
? "o" : "c");
1624 if (stat(buf
, &statbuf
) == 0) {
1626 save_len
+ 9, /* len("/__init__") */
1627 8, /* len("__init__") */
1629 buf
[save_len
] = '\0';
1633 buf
[save_len
] = '\0';
1641 find_init_module(buf
)
1644 int save_len
= strlen(buf
);
1647 if (save_len
+ 13 >= MAXPATHLEN
)
1650 strcpy(buf
+i
, "__init__/py");
1652 buf
[save_len
] = '\0';
1656 if (Py_OptimizeFlag
)
1661 buf
[save_len
] = '\0';
1664 buf
[save_len
] = '\0';
1669 #endif /* HAVE_STAT */
1672 static int init_builtin(char *); /* Forward */
1674 /* Load an external module using the default search path and return
1675 its module object WITH INCREMENTED REFERENCE COUNT */
1678 load_module(char *name
, FILE *fp
, char *buf
, int type
, PyObject
*loader
)
1684 /* First check that there's an open file (if we need one) */
1689 PyErr_Format(PyExc_ValueError
,
1690 "file object required for import (type code %d)",
1699 m
= load_source_module(name
, buf
, fp
);
1703 m
= load_compiled_module(name
, buf
, fp
);
1706 #ifdef HAVE_DYNAMIC_LOADING
1708 m
= _PyImport_LoadDynamicModule(name
, buf
, fp
);
1714 m
= PyMac_LoadResourceModule(name
, buf
);
1716 case PY_CODERESOURCE
:
1717 m
= PyMac_LoadCodeResourceModule(name
, buf
);
1722 m
= load_package(name
, buf
);
1727 if (buf
!= NULL
&& buf
[0] != '\0')
1729 if (type
== C_BUILTIN
)
1730 err
= init_builtin(name
);
1732 err
= PyImport_ImportFrozenModule(name
);
1736 PyErr_Format(PyExc_ImportError
,
1737 "Purported %s module %.200s not found",
1739 "builtin" : "frozen",
1743 modules
= PyImport_GetModuleDict();
1744 m
= PyDict_GetItemString(modules
, name
);
1748 "%s module %.200s not properly initialized",
1750 "builtin" : "frozen",
1758 if (loader
== NULL
) {
1759 PyErr_SetString(PyExc_ImportError
,
1760 "import hook without loader");
1763 m
= PyObject_CallMethod(loader
, "load_module", "s", name
);
1768 PyErr_Format(PyExc_ImportError
,
1769 "Don't know how to import %.200s (type code %d)",
1779 /* Initialize a built-in module.
1780 Return 1 for succes, 0 if the module is not found, and -1 with
1781 an exception set if the initialization failed. */
1784 init_builtin(char *name
)
1788 if (_PyImport_FindExtension(name
, name
) != NULL
)
1791 for (p
= PyImport_Inittab
; p
->name
!= NULL
; p
++) {
1792 if (strcmp(name
, p
->name
) == 0) {
1793 if (p
->initfunc
== NULL
) {
1794 PyErr_Format(PyExc_ImportError
,
1795 "Cannot re-init internal module %.200s",
1800 PySys_WriteStderr("import %s # builtin\n", name
);
1802 if (PyErr_Occurred())
1804 if (_PyImport_FixupExtension(name
, name
) == NULL
)
1813 /* Frozen modules */
1815 static struct _frozen
*
1816 find_frozen(char *name
)
1820 for (p
= PyImport_FrozenModules
; ; p
++) {
1821 if (p
->name
== NULL
)
1823 if (strcmp(p
->name
, name
) == 0)
1830 get_frozen_object(char *name
)
1832 struct _frozen
*p
= find_frozen(name
);
1836 PyErr_Format(PyExc_ImportError
,
1837 "No such frozen object named %.200s",
1841 if (p
->code
== NULL
) {
1842 PyErr_Format(PyExc_ImportError
,
1843 "Excluded frozen object named %.200s",
1850 return PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1853 /* Initialize a frozen module.
1854 Return 1 for succes, 0 if the module is not found, and -1 with
1855 an exception set if the initialization failed.
1856 This function is also used from frozenmain.c */
1859 PyImport_ImportFrozenModule(char *name
)
1861 struct _frozen
*p
= find_frozen(name
);
1869 if (p
->code
== NULL
) {
1870 PyErr_Format(PyExc_ImportError
,
1871 "Excluded frozen object named %.200s",
1876 ispackage
= (size
< 0);
1880 PySys_WriteStderr("import %s # frozen%s\n",
1881 name
, ispackage
? " package" : "");
1882 co
= PyMarshal_ReadObjectFromString((char *)p
->code
, size
);
1885 if (!PyCode_Check(co
)) {
1887 PyErr_Format(PyExc_TypeError
,
1888 "frozen object %.200s is not a code object",
1893 /* Set __path__ to the package name */
1896 m
= PyImport_AddModule(name
);
1899 d
= PyModule_GetDict(m
);
1900 s
= PyString_InternFromString(name
);
1903 err
= PyDict_SetItemString(d
, "__path__", s
);
1908 m
= PyImport_ExecCodeModuleEx(name
, co
, "<frozen>");
1917 /* Import a module, either built-in, frozen, or external, and return
1918 its module object WITH INCREMENTED REFERENCE COUNT */
1921 PyImport_ImportModule(char *name
)
1926 pname
= PyString_FromString(name
);
1929 result
= PyImport_Import(pname
);
1934 /* Forward declarations for helper routines */
1935 static PyObject
*get_parent(PyObject
*globals
, char *buf
, int *p_buflen
);
1936 static PyObject
*load_next(PyObject
*mod
, PyObject
*altmod
,
1937 char **p_name
, char *buf
, int *p_buflen
);
1938 static int mark_miss(char *name
);
1939 static int ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
,
1940 char *buf
, int buflen
, int recursive
);
1941 static PyObject
* import_submodule(PyObject
*mod
, char *name
, char *fullname
);
1943 /* The Magnum Opus of dotted-name import :-) */
1946 import_module_ex(char *name
, PyObject
*globals
, PyObject
*locals
,
1949 char buf
[MAXPATHLEN
+1];
1951 PyObject
*parent
, *head
, *next
, *tail
;
1953 parent
= get_parent(globals
, buf
, &buflen
);
1957 head
= load_next(parent
, Py_None
, &name
, buf
, &buflen
);
1964 next
= load_next(tail
, tail
, &name
, buf
, &buflen
);
1973 if (fromlist
!= NULL
) {
1974 if (fromlist
== Py_None
|| !PyObject_IsTrue(fromlist
))
1978 if (fromlist
== NULL
) {
1984 if (!ensure_fromlist(tail
, fromlist
, buf
, buflen
, 0)) {
1993 PyImport_ImportModuleEx(char *name
, PyObject
*globals
, PyObject
*locals
,
1998 result
= import_module_ex(name
, globals
, locals
, fromlist
);
1999 if (unlock_import() < 0) {
2001 PyErr_SetString(PyExc_RuntimeError
,
2002 "not holding the import lock");
2009 get_parent(PyObject
*globals
, char *buf
, int *p_buflen
)
2011 static PyObject
*namestr
= NULL
;
2012 static PyObject
*pathstr
= NULL
;
2013 PyObject
*modname
, *modpath
, *modules
, *parent
;
2015 if (globals
== NULL
|| !PyDict_Check(globals
))
2018 if (namestr
== NULL
) {
2019 namestr
= PyString_InternFromString("__name__");
2020 if (namestr
== NULL
)
2023 if (pathstr
== NULL
) {
2024 pathstr
= PyString_InternFromString("__path__");
2025 if (pathstr
== NULL
)
2031 modname
= PyDict_GetItem(globals
, namestr
);
2032 if (modname
== NULL
|| !PyString_Check(modname
))
2035 modpath
= PyDict_GetItem(globals
, pathstr
);
2036 if (modpath
!= NULL
) {
2037 int len
= PyString_GET_SIZE(modname
);
2038 if (len
> MAXPATHLEN
) {
2039 PyErr_SetString(PyExc_ValueError
,
2040 "Module name too long");
2043 strcpy(buf
, PyString_AS_STRING(modname
));
2047 char *start
= PyString_AS_STRING(modname
);
2048 char *lastdot
= strrchr(start
, '.');
2050 if (lastdot
== NULL
)
2052 len
= lastdot
- start
;
2053 if (len
>= MAXPATHLEN
) {
2054 PyErr_SetString(PyExc_ValueError
,
2055 "Module name too long");
2058 strncpy(buf
, start
, len
);
2063 modules
= PyImport_GetModuleDict();
2064 parent
= PyDict_GetItemString(modules
, buf
);
2068 /* We expect, but can't guarantee, if parent != None, that:
2069 - parent.__name__ == buf
2070 - parent.__dict__ is globals
2071 If this is violated... Who cares? */
2074 /* altmod is either None or same as mod */
2076 load_next(PyObject
*mod
, PyObject
*altmod
, char **p_name
, char *buf
,
2079 char *name
= *p_name
;
2080 char *dot
= strchr(name
, '.');
2094 PyErr_SetString(PyExc_ValueError
,
2095 "Empty module name");
2099 p
= buf
+ *p_buflen
;
2102 if (p
+len
-buf
>= MAXPATHLEN
) {
2103 PyErr_SetString(PyExc_ValueError
,
2104 "Module name too long");
2107 strncpy(p
, name
, len
);
2109 *p_buflen
= p
+len
-buf
;
2111 result
= import_submodule(mod
, p
, buf
);
2112 if (result
== Py_None
&& altmod
!= mod
) {
2114 /* Here, altmod must be None and mod must not be None */
2115 result
= import_submodule(altmod
, p
, p
);
2116 if (result
!= NULL
&& result
!= Py_None
) {
2117 if (mark_miss(buf
) != 0) {
2121 strncpy(buf
, name
, len
);
2129 if (result
== Py_None
) {
2131 PyErr_Format(PyExc_ImportError
,
2132 "No module named %.200s", name
);
2140 mark_miss(char *name
)
2142 PyObject
*modules
= PyImport_GetModuleDict();
2143 return PyDict_SetItemString(modules
, name
, Py_None
);
2147 ensure_fromlist(PyObject
*mod
, PyObject
*fromlist
, char *buf
, int buflen
,
2152 if (!PyObject_HasAttrString(mod
, "__path__"))
2155 for (i
= 0; ; i
++) {
2156 PyObject
*item
= PySequence_GetItem(fromlist
, i
);
2159 if (PyErr_ExceptionMatches(PyExc_IndexError
)) {
2165 if (!PyString_Check(item
)) {
2166 PyErr_SetString(PyExc_TypeError
,
2167 "Item in ``from list'' not a string");
2171 if (PyString_AS_STRING(item
)[0] == '*') {
2174 /* See if the package defines __all__ */
2176 continue; /* Avoid endless recursion */
2177 all
= PyObject_GetAttrString(mod
, "__all__");
2181 if (!ensure_fromlist(mod
, all
, buf
, buflen
, 1))
2187 hasit
= PyObject_HasAttr(mod
, item
);
2189 char *subname
= PyString_AS_STRING(item
);
2192 if (buflen
+ strlen(subname
) >= MAXPATHLEN
) {
2193 PyErr_SetString(PyExc_ValueError
,
2194 "Module name too long");
2201 submod
= import_submodule(mod
, subname
, buf
);
2203 if (submod
== NULL
) {
2215 import_submodule(PyObject
*mod
, char *subname
, char *fullname
)
2217 PyObject
*modules
= PyImport_GetModuleDict();
2218 PyObject
*m
, *res
= NULL
;
2221 if mod == None: subname == fullname
2222 else: mod.__name__ + "." + subname == fullname
2225 if ((m
= PyDict_GetItemString(modules
, fullname
)) != NULL
) {
2229 PyObject
*path
, *loader
= NULL
;
2230 char buf
[MAXPATHLEN
+1];
2231 struct filedescr
*fdp
;
2237 path
= PyObject_GetAttrString(mod
, "__path__");
2246 fdp
= find_module(fullname
, subname
, path
, buf
, MAXPATHLEN
+1,
2250 if (!PyErr_ExceptionMatches(PyExc_ImportError
))
2256 m
= load_module(fullname
, fp
, buf
, fdp
->type
, loader
);
2260 if (mod
!= Py_None
) {
2261 /* Irrespective of the success of this load, make a
2262 reference to it in the parent package module.
2263 A copy gets saved in the modules dictionary
2264 under the full name, so get a reference from
2265 there, if need be. (The exception is when
2266 the load failed with a SyntaxError -- then
2267 there's no trace in sys.modules. In that case,
2268 of course, do nothing extra.) */
2271 res
= PyDict_GetItemString(modules
, fullname
);
2273 PyObject_SetAttrString(mod
, subname
, res
) < 0) {
2284 /* Re-import a module of any kind and return its module object, WITH
2285 INCREMENTED REFERENCE COUNT */
2288 PyImport_ReloadModule(PyObject
*m
)
2290 PyObject
*modules
= PyImport_GetModuleDict();
2291 PyObject
*path
= NULL
;
2292 char *name
, *subname
;
2293 char buf
[MAXPATHLEN
+1];
2294 struct filedescr
*fdp
;
2297 if (m
== NULL
|| !PyModule_Check(m
)) {
2298 PyErr_SetString(PyExc_TypeError
,
2299 "reload() argument must be module");
2302 name
= PyModule_GetName(m
);
2305 if (m
!= PyDict_GetItemString(modules
, name
)) {
2306 PyErr_Format(PyExc_ImportError
,
2307 "reload(): module %.200s not in sys.modules",
2311 subname
= strrchr(name
, '.');
2312 if (subname
== NULL
)
2315 PyObject
*parentname
, *parent
;
2316 parentname
= PyString_FromStringAndSize(name
, (subname
-name
));
2317 if (parentname
== NULL
)
2319 parent
= PyDict_GetItem(modules
, parentname
);
2320 Py_DECREF(parentname
);
2321 if (parent
== NULL
) {
2322 PyErr_Format(PyExc_ImportError
,
2323 "reload(): parent %.200s not in sys.modules",
2328 path
= PyObject_GetAttrString(parent
, "__path__");
2333 fdp
= find_module(name
, subname
, path
, buf
, MAXPATHLEN
+1, &fp
, NULL
);
2337 m
= load_module(name
, fp
, buf
, fdp
->type
, NULL
);
2344 /* Higher-level import emulator which emulates the "import" statement
2345 more accurately -- it invokes the __import__() function from the
2346 builtins of the current globals. This means that the import is
2347 done using whatever import hooks are installed in the current
2348 environment, e.g. by "rexec".
2349 A dummy list ["__doc__"] is passed as the 4th argument so that
2350 e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
2351 will return <module "gencache"> instead of <module "win32com">. */
2354 PyImport_Import(PyObject
*module_name
)
2356 static PyObject
*silly_list
= NULL
;
2357 static PyObject
*builtins_str
= NULL
;
2358 static PyObject
*import_str
= NULL
;
2359 PyObject
*globals
= NULL
;
2360 PyObject
*import
= NULL
;
2361 PyObject
*builtins
= NULL
;
2364 /* Initialize constant string objects */
2365 if (silly_list
== NULL
) {
2366 import_str
= PyString_InternFromString("__import__");
2367 if (import_str
== NULL
)
2369 builtins_str
= PyString_InternFromString("__builtins__");
2370 if (builtins_str
== NULL
)
2372 silly_list
= Py_BuildValue("[s]", "__doc__");
2373 if (silly_list
== NULL
)
2377 /* Get the builtins from current globals */
2378 globals
= PyEval_GetGlobals();
2379 if (globals
!= NULL
) {
2381 builtins
= PyObject_GetItem(globals
, builtins_str
);
2382 if (builtins
== NULL
)
2386 /* No globals -- use standard builtins, and fake globals */
2389 builtins
= PyImport_ImportModuleEx("__builtin__",
2391 if (builtins
== NULL
)
2393 globals
= Py_BuildValue("{OO}", builtins_str
, builtins
);
2394 if (globals
== NULL
)
2398 /* Get the __import__ function from the builtins */
2399 if (PyDict_Check(builtins
)) {
2400 import
= PyObject_GetItem(builtins
, import_str
);
2402 PyErr_SetObject(PyExc_KeyError
, import_str
);
2405 import
= PyObject_GetAttr(builtins
, import_str
);
2409 /* Call the _import__ function with the proper argument list */
2410 r
= PyObject_CallFunction(import
, "OOOO",
2411 module_name
, globals
, globals
, silly_list
);
2414 Py_XDECREF(globals
);
2415 Py_XDECREF(builtins
);
2422 /* Module 'imp' provides Python access to the primitives used for
2427 imp_get_magic(PyObject
*self
, PyObject
*noargs
)
2431 buf
[0] = (char) ((pyc_magic
>> 0) & 0xff);
2432 buf
[1] = (char) ((pyc_magic
>> 8) & 0xff);
2433 buf
[2] = (char) ((pyc_magic
>> 16) & 0xff);
2434 buf
[3] = (char) ((pyc_magic
>> 24) & 0xff);
2436 return PyString_FromStringAndSize(buf
, 4);
2440 imp_get_suffixes(PyObject
*self
, PyObject
*noargs
)
2443 struct filedescr
*fdp
;
2445 list
= PyList_New(0);
2448 for (fdp
= _PyImport_Filetab
; fdp
->suffix
!= NULL
; fdp
++) {
2449 PyObject
*item
= Py_BuildValue("ssi",
2450 fdp
->suffix
, fdp
->mode
, fdp
->type
);
2455 if (PyList_Append(list
, item
) < 0) {
2466 call_find_module(char *name
, PyObject
*path
)
2468 extern int fclose(FILE *);
2469 PyObject
*fob
, *ret
;
2470 struct filedescr
*fdp
;
2471 char pathname
[MAXPATHLEN
+1];
2475 if (path
== Py_None
)
2477 fdp
= find_module(NULL
, name
, path
, pathname
, MAXPATHLEN
+1, &fp
, NULL
);
2481 fob
= PyFile_FromFile(fp
, pathname
, fdp
->mode
, fclose
);
2491 ret
= Py_BuildValue("Os(ssi)",
2492 fob
, pathname
, fdp
->suffix
, fdp
->mode
, fdp
->type
);
2498 imp_find_module(PyObject
*self
, PyObject
*args
)
2501 PyObject
*path
= NULL
;
2502 if (!PyArg_ParseTuple(args
, "s|O:find_module", &name
, &path
))
2504 return call_find_module(name
, path
);
2508 imp_init_builtin(PyObject
*self
, PyObject
*args
)
2513 if (!PyArg_ParseTuple(args
, "s:init_builtin", &name
))
2515 ret
= init_builtin(name
);
2522 m
= PyImport_AddModule(name
);
2528 imp_init_frozen(PyObject
*self
, PyObject
*args
)
2533 if (!PyArg_ParseTuple(args
, "s:init_frozen", &name
))
2535 ret
= PyImport_ImportFrozenModule(name
);
2542 m
= PyImport_AddModule(name
);
2548 imp_get_frozen_object(PyObject
*self
, PyObject
*args
)
2552 if (!PyArg_ParseTuple(args
, "s:get_frozen_object", &name
))
2554 return get_frozen_object(name
);
2558 imp_is_builtin(PyObject
*self
, PyObject
*args
)
2561 if (!PyArg_ParseTuple(args
, "s:is_builtin", &name
))
2563 return PyInt_FromLong(is_builtin(name
));
2567 imp_is_frozen(PyObject
*self
, PyObject
*args
)
2571 if (!PyArg_ParseTuple(args
, "s:is_frozen", &name
))
2573 p
= find_frozen(name
);
2574 return PyBool_FromLong((long) (p
== NULL
? 0 : p
->size
));
2578 get_file(char *pathname
, PyObject
*fob
, char *mode
)
2583 mode
= "r" PY_STDIOTEXTMODE
;
2584 fp
= fopen(pathname
, mode
);
2586 PyErr_SetFromErrno(PyExc_IOError
);
2589 fp
= PyFile_AsFile(fob
);
2591 PyErr_SetString(PyExc_ValueError
,
2592 "bad/closed file object");
2598 imp_load_compiled(PyObject
*self
, PyObject
*args
)
2602 PyObject
*fob
= NULL
;
2605 if (!PyArg_ParseTuple(args
, "ss|O!:load_compiled", &name
, &pathname
,
2606 &PyFile_Type
, &fob
))
2608 fp
= get_file(pathname
, fob
, "rb");
2611 m
= load_compiled_module(name
, pathname
, fp
);
2617 #ifdef HAVE_DYNAMIC_LOADING
2620 imp_load_dynamic(PyObject
*self
, PyObject
*args
)
2624 PyObject
*fob
= NULL
;
2627 if (!PyArg_ParseTuple(args
, "ss|O!:load_dynamic", &name
, &pathname
,
2628 &PyFile_Type
, &fob
))
2631 fp
= get_file(pathname
, fob
, "r");
2635 m
= _PyImport_LoadDynamicModule(name
, pathname
, fp
);
2639 #endif /* HAVE_DYNAMIC_LOADING */
2642 imp_load_source(PyObject
*self
, PyObject
*args
)
2646 PyObject
*fob
= NULL
;
2649 if (!PyArg_ParseTuple(args
, "ss|O!:load_source", &name
, &pathname
,
2650 &PyFile_Type
, &fob
))
2652 fp
= get_file(pathname
, fob
, "r");
2655 m
= load_source_module(name
, pathname
, fp
);
2663 imp_load_resource(PyObject
*self
, PyObject
*args
)
2669 if (!PyArg_ParseTuple(args
, "ss:load_resource", &name
, &pathname
))
2671 m
= PyMac_LoadResourceModule(name
, pathname
);
2674 #endif /* macintosh */
2677 imp_load_module(PyObject
*self
, PyObject
*args
)
2682 char *suffix
; /* Unused */
2687 if (!PyArg_ParseTuple(args
, "sOs(ssi):load_module",
2688 &name
, &fob
, &pathname
,
2689 &suffix
, &mode
, &type
))
2692 /* Mode must start with 'r' or 'U' and must not contain '+'.
2693 Implicit in this test is the assumption that the mode
2694 may contain other modifiers like 'b' or 't'. */
2696 if (!(*mode
== 'r' || *mode
== 'U') || strchr(mode
, '+')) {
2697 PyErr_Format(PyExc_ValueError
,
2698 "invalid file open mode %.200s", mode
);
2705 if (!PyFile_Check(fob
)) {
2706 PyErr_SetString(PyExc_ValueError
,
2707 "load_module arg#2 should be a file or None");
2710 fp
= get_file(pathname
, fob
, mode
);
2714 return load_module(name
, fp
, pathname
, type
, NULL
);
2718 imp_load_package(PyObject
*self
, PyObject
*args
)
2722 if (!PyArg_ParseTuple(args
, "ss:load_package", &name
, &pathname
))
2724 return load_package(name
, pathname
);
2728 imp_new_module(PyObject
*self
, PyObject
*args
)
2731 if (!PyArg_ParseTuple(args
, "s:new_module", &name
))
2733 return PyModule_New(name
);
2738 PyDoc_STRVAR(doc_imp
,
2739 "This module provides the components needed to build your own\n\
2740 __import__ function. Undocumented functions are obsolete.");
2742 PyDoc_STRVAR(doc_find_module
,
2743 "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
2744 Search for a module. If path is omitted or None, search for a\n\
2745 built-in, frozen or special module and continue search in sys.path.\n\
2746 The module name cannot contain '.'; to search for a submodule of a\n\
2747 package, pass the submodule name and the package's __path__.");
2749 PyDoc_STRVAR(doc_load_module
,
2750 "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
2751 Load a module, given information returned by find_module().\n\
2752 The module name must include the full package name, if any.");
2754 PyDoc_STRVAR(doc_get_magic
,
2755 "get_magic() -> string\n\
2756 Return the magic number for .pyc or .pyo files.");
2758 PyDoc_STRVAR(doc_get_suffixes
,
2759 "get_suffixes() -> [(suffix, mode, type), ...]\n\
2760 Return a list of (suffix, mode, type) tuples describing the files\n\
2761 that find_module() looks for.");
2763 PyDoc_STRVAR(doc_new_module
,
2764 "new_module(name) -> module\n\
2765 Create a new module. Do not enter it in sys.modules.\n\
2766 The module name must include the full package name, if any.");
2768 PyDoc_STRVAR(doc_lock_held
,
2769 "lock_held() -> 0 or 1\n\
2770 Return 1 if the import lock is currently held.\n\
2771 On platforms without threads, return 0.");
2773 PyDoc_STRVAR(doc_acquire_lock
,
2774 "acquire_lock() -> None\n\
2775 Acquires the interpreter's import lock for the current thread.\n\
2776 This lock should be used by import hooks to ensure thread-safety\n\
2777 when importing modules.\n\
2778 On platforms without threads, this function does nothing.");
2780 PyDoc_STRVAR(doc_release_lock
,
2781 "release_lock() -> None\n\
2782 Release the interpreter's import lock.\n\
2783 On platforms without threads, this function does nothing.");
2785 static PyMethodDef imp_methods
[] = {
2786 {"find_module", imp_find_module
, METH_VARARGS
, doc_find_module
},
2787 {"get_magic", imp_get_magic
, METH_NOARGS
, doc_get_magic
},
2788 {"get_suffixes", imp_get_suffixes
, METH_NOARGS
, doc_get_suffixes
},
2789 {"load_module", imp_load_module
, METH_VARARGS
, doc_load_module
},
2790 {"new_module", imp_new_module
, METH_VARARGS
, doc_new_module
},
2791 {"lock_held", imp_lock_held
, METH_NOARGS
, doc_lock_held
},
2792 {"acquire_lock", imp_acquire_lock
, METH_NOARGS
, doc_acquire_lock
},
2793 {"release_lock", imp_release_lock
, METH_NOARGS
, doc_release_lock
},
2794 /* The rest are obsolete */
2795 {"get_frozen_object", imp_get_frozen_object
, METH_VARARGS
},
2796 {"init_builtin", imp_init_builtin
, METH_VARARGS
},
2797 {"init_frozen", imp_init_frozen
, METH_VARARGS
},
2798 {"is_builtin", imp_is_builtin
, METH_VARARGS
},
2799 {"is_frozen", imp_is_frozen
, METH_VARARGS
},
2800 {"load_compiled", imp_load_compiled
, METH_VARARGS
},
2801 #ifdef HAVE_DYNAMIC_LOADING
2802 {"load_dynamic", imp_load_dynamic
, METH_VARARGS
},
2804 {"load_package", imp_load_package
, METH_VARARGS
},
2806 {"load_resource", imp_load_resource
, METH_VARARGS
},
2808 {"load_source", imp_load_source
, METH_VARARGS
},
2809 {NULL
, NULL
} /* sentinel */
2813 setint(PyObject
*d
, char *name
, int value
)
2818 v
= PyInt_FromLong((long)value
);
2819 err
= PyDict_SetItemString(d
, name
, v
);
2829 m
= Py_InitModule4("imp", imp_methods
, doc_imp
,
2830 NULL
, PYTHON_API_VERSION
);
2831 d
= PyModule_GetDict(m
);
2833 if (setint(d
, "SEARCH_ERROR", SEARCH_ERROR
) < 0) goto failure
;
2834 if (setint(d
, "PY_SOURCE", PY_SOURCE
) < 0) goto failure
;
2835 if (setint(d
, "PY_COMPILED", PY_COMPILED
) < 0) goto failure
;
2836 if (setint(d
, "C_EXTENSION", C_EXTENSION
) < 0) goto failure
;
2837 if (setint(d
, "PY_RESOURCE", PY_RESOURCE
) < 0) goto failure
;
2838 if (setint(d
, "PKG_DIRECTORY", PKG_DIRECTORY
) < 0) goto failure
;
2839 if (setint(d
, "C_BUILTIN", C_BUILTIN
) < 0) goto failure
;
2840 if (setint(d
, "PY_FROZEN", PY_FROZEN
) < 0) goto failure
;
2841 if (setint(d
, "PY_CODERESOURCE", PY_CODERESOURCE
) < 0) goto failure
;
2842 if (setint(d
, "IMP_HOOK", IMP_HOOK
) < 0) goto failure
;
2849 /* API for embedding applications that want to add their own entries
2850 to the table of built-in modules. This should normally be called
2851 *before* Py_Initialize(). When the table resize fails, -1 is
2852 returned and the existing table is unchanged.
2854 After a similar function by Just van Rossum. */
2857 PyImport_ExtendInittab(struct _inittab
*newtab
)
2859 static struct _inittab
*our_copy
= NULL
;
2863 /* Count the number of entries in both tables */
2864 for (n
= 0; newtab
[n
].name
!= NULL
; n
++)
2867 return 0; /* Nothing to do */
2868 for (i
= 0; PyImport_Inittab
[i
].name
!= NULL
; i
++)
2871 /* Allocate new memory for the combined table */
2873 PyMem_RESIZE(p
, struct _inittab
, i
+n
+1);
2877 /* Copy the tables into the new memory */
2878 if (our_copy
!= PyImport_Inittab
)
2879 memcpy(p
, PyImport_Inittab
, (i
+1) * sizeof(struct _inittab
));
2880 PyImport_Inittab
= our_copy
= p
;
2881 memcpy(p
+i
, newtab
, (n
+1) * sizeof(struct _inittab
));
2886 /* Shorthand to add a single entry given a name and a function */
2889 PyImport_AppendInittab(char *name
, void (*initfunc
)(void))
2891 struct _inittab newtab
[2];
2893 memset(newtab
, '\0', sizeof newtab
);
2895 newtab
[0].name
= name
;
2896 newtab
[0].initfunc
= initfunc
;
2898 return PyImport_ExtendInittab(newtab
);