+++ /dev/null
-\r
-/* Module definition and import implementation */\r
-\r
-#include "Python.h"\r
-\r
-#include "Python-ast.h"\r
-#undef Yield /* undefine macro conflicting with winbase.h */\r
-#include "pyarena.h"\r
-#include "pythonrun.h"\r
-#include "errcode.h"\r
-#include "marshal.h"\r
-#include "code.h"\r
-#include "compile.h"\r
-#include "eval.h"\r
-#include "osdefs.h"\r
-#include "importdl.h"\r
-\r
-#ifdef HAVE_FCNTL_H\r
-#include <fcntl.h>\r
-#endif\r
-#ifdef __cplusplus\r
-extern "C" {\r
-#endif\r
-\r
-#ifdef MS_WINDOWS\r
-/* for stat.st_mode */\r
-typedef unsigned short mode_t;\r
-#endif\r
-\r
-\r
-/* Magic word to reject .pyc files generated by other Python versions.\r
- It should change for each incompatible change to the bytecode.\r
-\r
- The value of CR and LF is incorporated so if you ever read or write\r
- a .pyc file in text mode the magic number will be wrong; also, the\r
- Apple MPW compiler swaps their values, botching string constants.\r
-\r
- The magic numbers must be spaced apart atleast 2 values, as the\r
- -U interpeter flag will cause MAGIC+1 being used. They have been\r
- odd numbers for some time now.\r
-\r
- There were a variety of old schemes for setting the magic number.\r
- The current working scheme is to increment the previous value by\r
- 10.\r
-\r
- Known values:\r
- Python 1.5: 20121\r
- Python 1.5.1: 20121\r
- Python 1.5.2: 20121\r
- Python 1.6: 50428\r
- Python 2.0: 50823\r
- Python 2.0.1: 50823\r
- Python 2.1: 60202\r
- Python 2.1.1: 60202\r
- Python 2.1.2: 60202\r
- Python 2.2: 60717\r
- Python 2.3a0: 62011\r
- Python 2.3a0: 62021\r
- Python 2.3a0: 62011 (!)\r
- Python 2.4a0: 62041\r
- Python 2.4a3: 62051\r
- Python 2.4b1: 62061\r
- Python 2.5a0: 62071\r
- Python 2.5a0: 62081 (ast-branch)\r
- Python 2.5a0: 62091 (with)\r
- Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)\r
- Python 2.5b3: 62101 (fix wrong code: for x, in ...)\r
- Python 2.5b3: 62111 (fix wrong code: x += yield)\r
- Python 2.5c1: 62121 (fix wrong lnotab with for loops and\r
- storing constants that should have been removed)\r
- Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)\r
- Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)\r
- Python 2.6a1: 62161 (WITH_CLEANUP optimization)\r
- Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)\r
- Python 2.7a0: 62181 (optimize conditional branches:\r
- introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)\r
- Python 2.7a0 62191 (introduce SETUP_WITH)\r
- Python 2.7a0 62201 (introduce BUILD_SET)\r
- Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD)\r
-.\r
-*/\r
-#define MAGIC (62211 | ((long)'\r'<<16) | ((long)'\n'<<24))\r
-\r
-/* Magic word as global; note that _PyImport_Init() can change the\r
- value of this global to accommodate for alterations of how the\r
- compiler works which are enabled by command line switches. */\r
-static long pyc_magic = MAGIC;\r
-\r
-/* See _PyImport_FixupExtension() below */\r
-static PyObject *extensions = NULL;\r
-\r
-/* This table is defined in config.c: */\r
-extern struct _inittab _PyImport_Inittab[];\r
-\r
-struct _inittab *PyImport_Inittab = _PyImport_Inittab;\r
-\r
-/* these tables define the module suffixes that Python recognizes */\r
-struct filedescr * _PyImport_Filetab = NULL;\r
-\r
-#ifdef RISCOS\r
-static const struct filedescr _PyImport_StandardFiletab[] = {\r
- {"/py", "U", PY_SOURCE},\r
- {"/pyc", "rb", PY_COMPILED},\r
- {0, 0}\r
-};\r
-#else\r
-static const struct filedescr _PyImport_StandardFiletab[] = {\r
- {".py", "U", PY_SOURCE},\r
-#ifdef MS_WINDOWS\r
- {".pyw", "U", PY_SOURCE},\r
-#endif\r
- {".pyc", "rb", PY_COMPILED},\r
- {0, 0}\r
-};\r
-#endif\r
-\r
-#ifdef MS_WINDOWS\r
-static int isdir(char *path) {\r
- DWORD rv;\r
- /* see issue1293 and issue3677:\r
- * stat() on Windows doesn't recognise paths like\r
- * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.\r
- * Also reference issue6727:\r
- * stat() on Windows is broken and doesn't resolve symlinks properly.\r
- */\r
- rv = GetFileAttributesA(path);\r
- return rv != INVALID_FILE_ATTRIBUTES && rv & FILE_ATTRIBUTE_DIRECTORY;\r
-}\r
-#else\r
-#ifdef HAVE_STAT\r
-static int isdir(char *path) {\r
- struct stat statbuf;\r
- return stat(path, &statbuf) == 0 && S_ISDIR(statbuf.st_mode);\r
-}\r
-#else\r
-#ifdef RISCOS\r
-/* with RISCOS, isdir is in unixstuff */\r
-#else\r
-int isdir(char *path) {\r
- return 0;\r
-}\r
-#endif /* RISCOS */\r
-#endif /* HAVE_STAT */\r
-#endif /* MS_WINDOWS */\r
-\r
-/* Initialize things */\r
-\r
-void\r
-_PyImport_Init(void)\r
-{\r
- const struct filedescr *scan;\r
- struct filedescr *filetab;\r
- int countD = 0;\r
- int countS = 0;\r
-\r
- /* prepare _PyImport_Filetab: copy entries from\r
- _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.\r
- */\r
-#ifdef HAVE_DYNAMIC_LOADING\r
- for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)\r
- ++countD;\r
-#endif\r
- for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)\r
- ++countS;\r
- filetab = PyMem_NEW(struct filedescr, countD + countS + 1);\r
- if (filetab == NULL)\r
- Py_FatalError("Can't initialize import file table.");\r
-#ifdef HAVE_DYNAMIC_LOADING\r
- memcpy(filetab, _PyImport_DynLoadFiletab,\r
- countD * sizeof(struct filedescr));\r
-#endif\r
- memcpy(filetab + countD, _PyImport_StandardFiletab,\r
- countS * sizeof(struct filedescr));\r
- filetab[countD + countS].suffix = NULL;\r
-\r
- _PyImport_Filetab = filetab;\r
-\r
- if (Py_OptimizeFlag) {\r
- /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */\r
- for (; filetab->suffix != NULL; filetab++) {\r
-#ifndef RISCOS\r
- if (strcmp(filetab->suffix, ".pyc") == 0)\r
- filetab->suffix = ".pyo";\r
-#else\r
- if (strcmp(filetab->suffix, "/pyc") == 0)\r
- filetab->suffix = "/pyo";\r
-#endif\r
- }\r
- }\r
-\r
- if (Py_UnicodeFlag) {\r
- /* Fix the pyc_magic so that byte compiled code created\r
- using the all-Unicode method doesn't interfere with\r
- code created in normal operation mode. */\r
- pyc_magic = MAGIC + 1;\r
- }\r
-}\r
-\r
-void\r
-_PyImportHooks_Init(void)\r
-{\r
- PyObject *v, *path_hooks = NULL, *zimpimport;\r
- int err = 0;\r
-\r
- /* adding sys.path_hooks and sys.path_importer_cache, setting up\r
- zipimport */\r
- if (PyType_Ready(&PyNullImporter_Type) < 0)\r
- goto error;\r
-\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# installing zipimport hook\n");\r
-\r
- v = PyList_New(0);\r
- if (v == NULL)\r
- goto error;\r
- err = PySys_SetObject("meta_path", v);\r
- Py_DECREF(v);\r
- if (err)\r
- goto error;\r
- v = PyDict_New();\r
- if (v == NULL)\r
- goto error;\r
- err = PySys_SetObject("path_importer_cache", v);\r
- Py_DECREF(v);\r
- if (err)\r
- goto error;\r
- path_hooks = PyList_New(0);\r
- if (path_hooks == NULL)\r
- goto error;\r
- err = PySys_SetObject("path_hooks", path_hooks);\r
- if (err) {\r
- error:\r
- PyErr_Print();\r
- Py_FatalError("initializing sys.meta_path, sys.path_hooks, "\r
- "path_importer_cache, or NullImporter failed"\r
- );\r
- }\r
-\r
- zimpimport = PyImport_ImportModule("zipimport");\r
- if (zimpimport == NULL) {\r
- PyErr_Clear(); /* No zip import module -- okay */\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# can't import zipimport\n");\r
- }\r
- else {\r
- PyObject *zipimporter = PyObject_GetAttrString(zimpimport,\r
- "zipimporter");\r
- Py_DECREF(zimpimport);\r
- if (zipimporter == NULL) {\r
- PyErr_Clear(); /* No zipimporter object -- okay */\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr(\r
- "# can't import zipimport.zipimporter\n");\r
- }\r
- else {\r
- /* sys.path_hooks.append(zipimporter) */\r
- err = PyList_Append(path_hooks, zipimporter);\r
- Py_DECREF(zipimporter);\r
- if (err)\r
- goto error;\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr(\r
- "# installed zipimport hook\n");\r
- }\r
- }\r
- Py_DECREF(path_hooks);\r
-}\r
-\r
-void\r
-_PyImport_Fini(void)\r
-{\r
- Py_XDECREF(extensions);\r
- extensions = NULL;\r
- PyMem_DEL(_PyImport_Filetab);\r
- _PyImport_Filetab = NULL;\r
-}\r
-\r
-\r
-/* Locking primitives to prevent parallel imports of the same module\r
- in different threads to return with a partially loaded module.\r
- These calls are serialized by the global interpreter lock. */\r
-\r
-#ifdef WITH_THREAD\r
-\r
-#include "pythread.h"\r
-\r
-static PyThread_type_lock import_lock = 0;\r
-static long import_lock_thread = -1;\r
-static int import_lock_level = 0;\r
-\r
-void\r
-_PyImport_AcquireLock(void)\r
-{\r
- long me = PyThread_get_thread_ident();\r
- if (me == -1)\r
- return; /* Too bad */\r
- if (import_lock == NULL) {\r
- import_lock = PyThread_allocate_lock();\r
- if (import_lock == NULL)\r
- return; /* Nothing much we can do. */\r
- }\r
- if (import_lock_thread == me) {\r
- import_lock_level++;\r
- return;\r
- }\r
- if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))\r
- {\r
- PyThreadState *tstate = PyEval_SaveThread();\r
- PyThread_acquire_lock(import_lock, 1);\r
- PyEval_RestoreThread(tstate);\r
- }\r
- import_lock_thread = me;\r
- import_lock_level = 1;\r
-}\r
-\r
-int\r
-_PyImport_ReleaseLock(void)\r
-{\r
- long me = PyThread_get_thread_ident();\r
- if (me == -1 || import_lock == NULL)\r
- return 0; /* Too bad */\r
- if (import_lock_thread != me)\r
- return -1;\r
- import_lock_level--;\r
- if (import_lock_level == 0) {\r
- import_lock_thread = -1;\r
- PyThread_release_lock(import_lock);\r
- }\r
- return 1;\r
-}\r
-\r
-/* This function is called from PyOS_AfterFork to ensure that newly\r
- created child processes do not share locks with the parent.\r
- We now acquire the import lock around fork() calls but on some platforms\r
- (Solaris 9 and earlier? see isue7242) that still left us with problems. */\r
-\r
-void\r
-_PyImport_ReInitLock(void)\r
-{\r
- if (import_lock != NULL) {\r
- import_lock = PyThread_allocate_lock();\r
- if (import_lock == NULL) {\r
- Py_FatalError("PyImport_ReInitLock failed to create a new lock");\r
- }\r
- }\r
- import_lock_thread = -1;\r
- import_lock_level = 0;\r
-}\r
-\r
-#endif\r
-\r
-static PyObject *\r
-imp_lock_held(PyObject *self, PyObject *noargs)\r
-{\r
-#ifdef WITH_THREAD\r
- return PyBool_FromLong(import_lock_thread != -1);\r
-#else\r
- return PyBool_FromLong(0);\r
-#endif\r
-}\r
-\r
-static PyObject *\r
-imp_acquire_lock(PyObject *self, PyObject *noargs)\r
-{\r
-#ifdef WITH_THREAD\r
- _PyImport_AcquireLock();\r
-#endif\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
-}\r
-\r
-static PyObject *\r
-imp_release_lock(PyObject *self, PyObject *noargs)\r
-{\r
-#ifdef WITH_THREAD\r
- if (_PyImport_ReleaseLock() < 0) {\r
- PyErr_SetString(PyExc_RuntimeError,\r
- "not holding the import lock");\r
- return NULL;\r
- }\r
-#endif\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
-}\r
-\r
-static void\r
-imp_modules_reloading_clear(void)\r
-{\r
- PyInterpreterState *interp = PyThreadState_Get()->interp;\r
- if (interp->modules_reloading != NULL)\r
- PyDict_Clear(interp->modules_reloading);\r
-}\r
-\r
-/* Helper for sys */\r
-\r
-PyObject *\r
-PyImport_GetModuleDict(void)\r
-{\r
- PyInterpreterState *interp = PyThreadState_GET()->interp;\r
- if (interp->modules == NULL)\r
- Py_FatalError("PyImport_GetModuleDict: no module dictionary!");\r
- return interp->modules;\r
-}\r
-\r
-\r
-/* List of names to clear in sys */\r
-static char* sys_deletes[] = {\r
- "path", "argv", "ps1", "ps2", "exitfunc",\r
- "exc_type", "exc_value", "exc_traceback",\r
- "last_type", "last_value", "last_traceback",\r
- "path_hooks", "path_importer_cache", "meta_path",\r
- /* misc stuff */\r
- "flags", "float_info",\r
- NULL\r
-};\r
-\r
-static char* sys_files[] = {\r
- "stdin", "__stdin__",\r
- "stdout", "__stdout__",\r
- "stderr", "__stderr__",\r
- NULL\r
-};\r
-\r
-\r
-/* Un-initialize things, as good as we can */\r
-\r
-void\r
-PyImport_Cleanup(void)\r
-{\r
- Py_ssize_t pos, ndone;\r
- char *name;\r
- PyObject *key, *value, *dict;\r
- PyInterpreterState *interp = PyThreadState_GET()->interp;\r
- PyObject *modules = interp->modules;\r
-\r
- if (modules == NULL)\r
- return; /* Already done */\r
-\r
- /* Delete some special variables first. These are common\r
- places where user values hide and people complain when their\r
- destructors fail. Since the modules containing them are\r
- deleted *last* of all, they would come too late in the normal\r
- destruction order. Sigh. */\r
-\r
- value = PyDict_GetItemString(modules, "__builtin__");\r
- if (value != NULL && PyModule_Check(value)) {\r
- dict = PyModule_GetDict(value);\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# clear __builtin__._\n");\r
- PyDict_SetItemString(dict, "_", Py_None);\r
- }\r
- value = PyDict_GetItemString(modules, "sys");\r
- if (value != NULL && PyModule_Check(value)) {\r
- char **p;\r
- PyObject *v;\r
- dict = PyModule_GetDict(value);\r
- for (p = sys_deletes; *p != NULL; p++) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# clear sys.%s\n", *p);\r
- PyDict_SetItemString(dict, *p, Py_None);\r
- }\r
- for (p = sys_files; *p != NULL; p+=2) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# restore sys.%s\n", *p);\r
- v = PyDict_GetItemString(dict, *(p+1));\r
- if (v == NULL)\r
- v = Py_None;\r
- PyDict_SetItemString(dict, *p, v);\r
- }\r
- }\r
-\r
- /* First, delete __main__ */\r
- value = PyDict_GetItemString(modules, "__main__");\r
- if (value != NULL && PyModule_Check(value)) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# cleanup __main__\n");\r
- _PyModule_Clear(value);\r
- PyDict_SetItemString(modules, "__main__", Py_None);\r
- }\r
-\r
- /* The special treatment of __builtin__ here is because even\r
- when it's not referenced as a module, its dictionary is\r
- referenced by almost every module's __builtins__. Since\r
- deleting a module clears its dictionary (even if there are\r
- references left to it), we need to delete the __builtin__\r
- module last. Likewise, we don't delete sys until the very\r
- end because it is implicitly referenced (e.g. by print).\r
-\r
- Also note that we 'delete' modules by replacing their entry\r
- in the modules dict with None, rather than really deleting\r
- them; this avoids a rehash of the modules dictionary and\r
- also marks them as "non existent" so they won't be\r
- re-imported. */\r
-\r
- /* Next, repeatedly delete modules with a reference count of\r
- one (skipping __builtin__ and sys) and delete them */\r
- do {\r
- ndone = 0;\r
- pos = 0;\r
- while (PyDict_Next(modules, &pos, &key, &value)) {\r
- if (value->ob_refcnt != 1)\r
- continue;\r
- if (PyString_Check(key) && PyModule_Check(value)) {\r
- name = PyString_AS_STRING(key);\r
- if (strcmp(name, "__builtin__") == 0)\r
- continue;\r
- if (strcmp(name, "sys") == 0)\r
- continue;\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr(\r
- "# cleanup[1] %s\n", name);\r
- _PyModule_Clear(value);\r
- PyDict_SetItem(modules, key, Py_None);\r
- ndone++;\r
- }\r
- }\r
- } while (ndone > 0);\r
-\r
- /* Next, delete all modules (still skipping __builtin__ and sys) */\r
- pos = 0;\r
- while (PyDict_Next(modules, &pos, &key, &value)) {\r
- if (PyString_Check(key) && PyModule_Check(value)) {\r
- name = PyString_AS_STRING(key);\r
- if (strcmp(name, "__builtin__") == 0)\r
- continue;\r
- if (strcmp(name, "sys") == 0)\r
- continue;\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# cleanup[2] %s\n", name);\r
- _PyModule_Clear(value);\r
- PyDict_SetItem(modules, key, Py_None);\r
- }\r
- }\r
-\r
- /* Next, delete sys and __builtin__ (in that order) */\r
- value = PyDict_GetItemString(modules, "sys");\r
- if (value != NULL && PyModule_Check(value)) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# cleanup sys\n");\r
- _PyModule_Clear(value);\r
- PyDict_SetItemString(modules, "sys", Py_None);\r
- }\r
- value = PyDict_GetItemString(modules, "__builtin__");\r
- if (value != NULL && PyModule_Check(value)) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# cleanup __builtin__\n");\r
- _PyModule_Clear(value);\r
- PyDict_SetItemString(modules, "__builtin__", Py_None);\r
- }\r
-\r
- /* Finally, clear and delete the modules directory */\r
- PyDict_Clear(modules);\r
- interp->modules = NULL;\r
- Py_DECREF(modules);\r
- Py_CLEAR(interp->modules_reloading);\r
-}\r
-\r
-\r
-/* Helper for pythonrun.c -- return magic number */\r
-\r
-long\r
-PyImport_GetMagicNumber(void)\r
-{\r
- return pyc_magic;\r
-}\r
-\r
-\r
-/* Magic for extension modules (built-in as well as dynamically\r
- loaded). To prevent initializing an extension module more than\r
- once, we keep a static dictionary 'extensions' keyed by module name\r
- (for built-in modules) or by filename (for dynamically loaded\r
- modules), containing these modules. A copy of the module's\r
- dictionary is stored by calling _PyImport_FixupExtension()\r
- immediately after the module initialization function succeeds. A\r
- copy can be retrieved from there by calling\r
- _PyImport_FindExtension(). */\r
-\r
-PyObject *\r
-_PyImport_FixupExtension(char *name, char *filename)\r
-{\r
- PyObject *modules, *mod, *dict, *copy;\r
- if (extensions == NULL) {\r
- extensions = PyDict_New();\r
- if (extensions == NULL)\r
- return NULL;\r
- }\r
- modules = PyImport_GetModuleDict();\r
- mod = PyDict_GetItemString(modules, name);\r
- if (mod == NULL || !PyModule_Check(mod)) {\r
- PyErr_Format(PyExc_SystemError,\r
- "_PyImport_FixupExtension: module %.200s not loaded", name);\r
- return NULL;\r
- }\r
- dict = PyModule_GetDict(mod);\r
- if (dict == NULL)\r
- return NULL;\r
- copy = PyDict_Copy(dict);\r
- if (copy == NULL)\r
- return NULL;\r
- PyDict_SetItemString(extensions, filename, copy);\r
- Py_DECREF(copy);\r
- return copy;\r
-}\r
-\r
-PyObject *\r
-_PyImport_FindExtension(char *name, char *filename)\r
-{\r
- PyObject *dict, *mod, *mdict;\r
- if (extensions == NULL)\r
- return NULL;\r
- dict = PyDict_GetItemString(extensions, filename);\r
- if (dict == NULL)\r
- return NULL;\r
- mod = PyImport_AddModule(name);\r
- if (mod == NULL)\r
- return NULL;\r
- mdict = PyModule_GetDict(mod);\r
- if (mdict == NULL)\r
- return NULL;\r
- if (PyDict_Update(mdict, dict))\r
- return NULL;\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("import %s # previously loaded (%s)\n",\r
- name, filename);\r
- return mod;\r
-}\r
-\r
-\r
-/* Get the module object corresponding to a module name.\r
- First check the modules dictionary if there's one there,\r
- if not, create a new one and insert it in the modules dictionary.\r
- Because the former action is most common, THIS DOES NOT RETURN A\r
- 'NEW' REFERENCE! */\r
-\r
-PyObject *\r
-PyImport_AddModule(const char *name)\r
-{\r
- PyObject *modules = PyImport_GetModuleDict();\r
- PyObject *m;\r
-\r
- if ((m = PyDict_GetItemString(modules, name)) != NULL &&\r
- PyModule_Check(m))\r
- return m;\r
- m = PyModule_New(name);\r
- if (m == NULL)\r
- return NULL;\r
- if (PyDict_SetItemString(modules, name, m) != 0) {\r
- Py_DECREF(m);\r
- return NULL;\r
- }\r
- Py_DECREF(m); /* Yes, it still exists, in modules! */\r
-\r
- return m;\r
-}\r
-\r
-/* Remove name from sys.modules, if it's there. */\r
-static void\r
-remove_module(const char *name)\r
-{\r
- PyObject *modules = PyImport_GetModuleDict();\r
- if (PyDict_GetItemString(modules, name) == NULL)\r
- return;\r
- if (PyDict_DelItemString(modules, name) < 0)\r
- Py_FatalError("import: deleting existing key in"\r
- "sys.modules failed");\r
-}\r
-\r
-/* Execute a code object in a module and return the module object\r
- * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is\r
- * removed from sys.modules, to avoid leaving damaged module objects\r
- * in sys.modules. The caller may wish to restore the original\r
- * module object (if any) in this case; PyImport_ReloadModule is an\r
- * example.\r
- */\r
-PyObject *\r
-PyImport_ExecCodeModule(char *name, PyObject *co)\r
-{\r
- return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);\r
-}\r
-\r
-PyObject *\r
-PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)\r
-{\r
- PyObject *modules = PyImport_GetModuleDict();\r
- PyObject *m, *d, *v;\r
-\r
- m = PyImport_AddModule(name);\r
- if (m == NULL)\r
- return NULL;\r
- /* If the module is being reloaded, we get the old module back\r
- and re-use its dict to exec the new code. */\r
- d = PyModule_GetDict(m);\r
- if (PyDict_GetItemString(d, "__builtins__") == NULL) {\r
- if (PyDict_SetItemString(d, "__builtins__",\r
- PyEval_GetBuiltins()) != 0)\r
- goto error;\r
- }\r
- /* Remember the filename as the __file__ attribute */\r
- v = NULL;\r
- if (pathname != NULL) {\r
- v = PyString_FromString(pathname);\r
- if (v == NULL)\r
- PyErr_Clear();\r
- }\r
- if (v == NULL) {\r
- v = ((PyCodeObject *)co)->co_filename;\r
- Py_INCREF(v);\r
- }\r
- if (PyDict_SetItemString(d, "__file__", v) != 0)\r
- PyErr_Clear(); /* Not important enough to report */\r
- Py_DECREF(v);\r
-\r
- v = PyEval_EvalCode((PyCodeObject *)co, d, d);\r
- if (v == NULL)\r
- goto error;\r
- Py_DECREF(v);\r
-\r
- if ((m = PyDict_GetItemString(modules, name)) == NULL) {\r
- PyErr_Format(PyExc_ImportError,\r
- "Loaded module %.200s not found in sys.modules",\r
- name);\r
- return NULL;\r
- }\r
-\r
- Py_INCREF(m);\r
-\r
- return m;\r
-\r
- error:\r
- remove_module(name);\r
- return NULL;\r
-}\r
-\r
-\r
-/* Given a pathname for a Python source file, fill a buffer with the\r
- pathname for the corresponding compiled file. Return the pathname\r
- for the compiled file, or NULL if there's no space in the buffer.\r
- Doesn't set an exception. */\r
-\r
-static char *\r
-make_compiled_pathname(char *pathname, char *buf, size_t buflen)\r
-{\r
- size_t len = strlen(pathname);\r
- if (len+2 > buflen)\r
- return NULL;\r
-\r
-#ifdef MS_WINDOWS\r
- /* Treat .pyw as if it were .py. The case of ".pyw" must match\r
- that used in _PyImport_StandardFiletab. */\r
- if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)\r
- --len; /* pretend 'w' isn't there */\r
-#endif\r
- memcpy(buf, pathname, len);\r
- buf[len] = Py_OptimizeFlag ? 'o' : 'c';\r
- buf[len+1] = '\0';\r
-\r
- return buf;\r
-}\r
-\r
-\r
-/* Given a pathname for a Python source file, its time of last\r
- modification, and a pathname for a compiled file, check whether the\r
- compiled file represents the same version of the source. If so,\r
- return a FILE pointer for the compiled file, positioned just after\r
- the header; if not, return NULL.\r
- Doesn't set an exception. */\r
-\r
-static FILE *\r
-check_compiled_module(char *pathname, time_t mtime, char *cpathname)\r
-{\r
- FILE *fp;\r
- long magic;\r
- long pyc_mtime;\r
-\r
- fp = fopen(cpathname, "rb");\r
- if (fp == NULL)\r
- return NULL;\r
- magic = PyMarshal_ReadLongFromFile(fp);\r
- if (magic != pyc_magic) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# %s has bad magic\n", cpathname);\r
- fclose(fp);\r
- return NULL;\r
- }\r
- pyc_mtime = PyMarshal_ReadLongFromFile(fp);\r
- if (pyc_mtime != mtime) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# %s has bad mtime\n", cpathname);\r
- fclose(fp);\r
- return NULL;\r
- }\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);\r
- return fp;\r
-}\r
-\r
-\r
-/* Read a code object from a file and check it for validity */\r
-\r
-static PyCodeObject *\r
-read_compiled_module(char *cpathname, FILE *fp)\r
-{\r
- PyObject *co;\r
-\r
- co = PyMarshal_ReadLastObjectFromFile(fp);\r
- if (co == NULL)\r
- return NULL;\r
- if (!PyCode_Check(co)) {\r
- PyErr_Format(PyExc_ImportError,\r
- "Non-code object in %.200s", cpathname);\r
- Py_DECREF(co);\r
- return NULL;\r
- }\r
- return (PyCodeObject *)co;\r
-}\r
-\r
-\r
-/* Load a module from a compiled file, execute it, and return its\r
- module object WITH INCREMENTED REFERENCE COUNT */\r
-\r
-static PyObject *\r
-load_compiled_module(char *name, char *cpathname, FILE *fp)\r
-{\r
- long magic;\r
- PyCodeObject *co;\r
- PyObject *m;\r
-\r
- magic = PyMarshal_ReadLongFromFile(fp);\r
- if (magic != pyc_magic) {\r
- PyErr_Format(PyExc_ImportError,\r
- "Bad magic number in %.200s", cpathname);\r
- return NULL;\r
- }\r
- (void) PyMarshal_ReadLongFromFile(fp);\r
- co = read_compiled_module(cpathname, fp);\r
- if (co == NULL)\r
- return NULL;\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("import %s # precompiled from %s\n",\r
- name, cpathname);\r
- m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);\r
- Py_DECREF(co);\r
-\r
- return m;\r
-}\r
-\r
-/* Parse a source file and return the corresponding code object */\r
-\r
-static PyCodeObject *\r
-parse_source_module(const char *pathname, FILE *fp)\r
-{\r
- PyCodeObject *co = NULL;\r
- mod_ty mod;\r
- PyCompilerFlags flags;\r
- PyArena *arena = PyArena_New();\r
- if (arena == NULL)\r
- return NULL;\r
-\r
- flags.cf_flags = 0;\r
-\r
- mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags,\r
- NULL, arena);\r
- if (mod) {\r
- co = PyAST_Compile(mod, pathname, NULL, arena);\r
- }\r
- PyArena_Free(arena);\r
- return co;\r
-}\r
-\r
-\r
-/* Helper to open a bytecode file for writing in exclusive mode */\r
-\r
-static FILE *\r
-open_exclusive(char *filename, mode_t mode)\r
-{\r
-#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)\r
- /* Use O_EXCL to avoid a race condition when another process tries to\r
- write the same file. When that happens, our open() call fails,\r
- which is just fine (since it's only a cache).\r
- XXX If the file exists and is writable but the directory is not\r
- writable, the file will never be written. Oh well.\r
- */\r
- int fd;\r
- (void) unlink(filename);\r
- fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC\r
-#ifdef O_BINARY\r
- |O_BINARY /* necessary for Windows */\r
-#endif\r
-#ifdef __VMS\r
- , mode, "ctxt=bin", "shr=nil"\r
-#else\r
- , mode\r
-#endif\r
- );\r
- if (fd < 0)\r
- return NULL;\r
- return fdopen(fd, "wb");\r
-#else\r
- /* Best we can do -- on Windows this can't happen anyway */\r
- return fopen(filename, "wb");\r
-#endif\r
-}\r
-\r
-\r
-/* Write a compiled module to a file, placing the time of last\r
- modification of its source into the header.\r
- Errors are ignored, if a write error occurs an attempt is made to\r
- remove the file. */\r
-\r
-static void\r
-write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat, time_t mtime)\r
-{\r
- FILE *fp;\r
-#ifdef MS_WINDOWS /* since Windows uses different permissions */\r
- mode_t mode = srcstat->st_mode & ~S_IEXEC;\r
- /* Issue #6074: We ensure user write access, so we can delete it later\r
- * when the source file changes. (On POSIX, this only requires write\r
- * access to the directory, on Windows, we need write access to the file\r
- * as well)\r
- */\r
- mode |= _S_IWRITE;\r
-#else\r
- mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;\r
-#endif\r
-\r
- fp = open_exclusive(cpathname, mode);\r
- if (fp == NULL) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr(\r
- "# can't create %s\n", cpathname);\r
- return;\r
- }\r
- PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);\r
- /* First write a 0 for mtime */\r
- PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);\r
- PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);\r
- if (fflush(fp) != 0 || ferror(fp)) {\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# can't write %s\n", cpathname);\r
- /* Don't keep partial file */\r
- fclose(fp);\r
- (void) unlink(cpathname);\r
- return;\r
- }\r
- /* Now write the true mtime (as a 32-bit field) */\r
- fseek(fp, 4L, 0);\r
- assert(mtime <= 0xFFFFFFFF);\r
- PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);\r
- fflush(fp);\r
- fclose(fp);\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("# wrote %s\n", cpathname);\r
-}\r
-\r
-static void\r
-update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)\r
-{\r
- PyObject *constants, *tmp;\r
- Py_ssize_t i, n;\r
-\r
- if (!_PyString_Eq(co->co_filename, oldname))\r
- return;\r
-\r
- tmp = co->co_filename;\r
- co->co_filename = newname;\r
- Py_INCREF(co->co_filename);\r
- Py_DECREF(tmp);\r
-\r
- constants = co->co_consts;\r
- n = PyTuple_GET_SIZE(constants);\r
- for (i = 0; i < n; i++) {\r
- tmp = PyTuple_GET_ITEM(constants, i);\r
- if (PyCode_Check(tmp))\r
- update_code_filenames((PyCodeObject *)tmp,\r
- oldname, newname);\r
- }\r
-}\r
-\r
-static int\r
-update_compiled_module(PyCodeObject *co, char *pathname)\r
-{\r
- PyObject *oldname, *newname;\r
-\r
- if (strcmp(PyString_AsString(co->co_filename), pathname) == 0)\r
- return 0;\r
-\r
- newname = PyString_FromString(pathname);\r
- if (newname == NULL)\r
- return -1;\r
-\r
- oldname = co->co_filename;\r
- Py_INCREF(oldname);\r
- update_code_filenames(co, oldname, newname);\r
- Py_DECREF(oldname);\r
- Py_DECREF(newname);\r
- return 1;\r
-}\r
-\r
-#ifdef MS_WINDOWS\r
-\r
-/* Seconds between 1.1.1601 and 1.1.1970 */\r
-static __int64 secs_between_epochs = 11644473600;\r
-\r
-/* Get mtime from file pointer. */\r
-\r
-static time_t\r
-win32_mtime(FILE *fp, char *pathname)\r
-{\r
- __int64 filetime;\r
- HANDLE fh;\r
- BY_HANDLE_FILE_INFORMATION file_information;\r
-\r
- fh = (HANDLE)_get_osfhandle(fileno(fp));\r
- if (fh == INVALID_HANDLE_VALUE ||\r
- !GetFileInformationByHandle(fh, &file_information)) {\r
- PyErr_Format(PyExc_RuntimeError,\r
- "unable to get file status from '%s'",\r
- pathname);\r
- return -1;\r
- }\r
- /* filetime represents the number of 100ns intervals since\r
- 1.1.1601 (UTC). Convert to seconds since 1.1.1970 (UTC). */\r
- filetime = (__int64)file_information.ftLastWriteTime.dwHighDateTime << 32 |\r
- file_information.ftLastWriteTime.dwLowDateTime;\r
- return filetime / 10000000 - secs_between_epochs;\r
-}\r
-\r
-#endif /* #ifdef MS_WINDOWS */\r
-\r
-\r
-/* Load a source module from a given file and return its module\r
- object WITH INCREMENTED REFERENCE COUNT. If there's a matching\r
- byte-compiled file, use that instead. */\r
-\r
-static PyObject *\r
-load_source_module(char *name, char *pathname, FILE *fp)\r
-{\r
- struct stat st;\r
- FILE *fpc;\r
- char *buf;\r
- char *cpathname;\r
- PyCodeObject *co = NULL;\r
- PyObject *m;\r
- time_t mtime;\r
-\r
- if (fstat(fileno(fp), &st) != 0) {\r
- PyErr_Format(PyExc_RuntimeError,\r
- "unable to get file status from '%s'",\r
- pathname);\r
- return NULL;\r
- }\r
-\r
-#ifdef MS_WINDOWS\r
- mtime = win32_mtime(fp, pathname);\r
- if (mtime == (time_t)-1 && PyErr_Occurred())\r
- return NULL;\r
-#else\r
- mtime = st.st_mtime;\r
-#endif\r
- if (sizeof mtime > 4) {\r
- /* Python's .pyc timestamp handling presumes that the timestamp fits\r
- in 4 bytes. Since the code only does an equality comparison,\r
- ordering is not important and we can safely ignore the higher bits\r
- (collisions are extremely unlikely).\r
- */\r
- mtime &= 0xFFFFFFFF;\r
- }\r
- buf = PyMem_MALLOC(MAXPATHLEN+1);\r
- if (buf == NULL) {\r
- return PyErr_NoMemory();\r
- }\r
- cpathname = make_compiled_pathname(pathname, buf,\r
- (size_t)MAXPATHLEN + 1);\r
- if (cpathname != NULL &&\r
- (fpc = check_compiled_module(pathname, mtime, cpathname))) {\r
- co = read_compiled_module(cpathname, fpc);\r
- fclose(fpc);\r
- if (co == NULL)\r
- goto error_exit;\r
- if (update_compiled_module(co, pathname) < 0)\r
- goto error_exit;\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("import %s # precompiled from %s\n",\r
- name, cpathname);\r
- pathname = cpathname;\r
- }\r
- else {\r
- co = parse_source_module(pathname, fp);\r
- if (co == NULL)\r
- goto error_exit;\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("import %s # from %s\n",\r
- name, pathname);\r
- if (cpathname) {\r
- PyObject *ro = PySys_GetObject("dont_write_bytecode");\r
- int b = (ro == NULL) ? 0 : PyObject_IsTrue(ro);\r
- if (b < 0)\r
- goto error_exit;\r
- if (!b)\r
- write_compiled_module(co, cpathname, &st, mtime);\r
- }\r
- }\r
- m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);\r
- Py_DECREF(co);\r
-\r
- PyMem_FREE(buf);\r
- return m;\r
-\r
-error_exit:\r
- Py_XDECREF(co);\r
- PyMem_FREE(buf);\r
- return NULL;\r
-}\r
-\r
-\r
-/* Forward */\r
-static PyObject *load_module(char *, FILE *, char *, int, PyObject *);\r
-static struct filedescr *find_module(char *, char *, PyObject *,\r
- char *, size_t, FILE **, PyObject **);\r
-static struct _frozen *find_frozen(char *name);\r
-\r
-/* Load a package and return its module object WITH INCREMENTED\r
- REFERENCE COUNT */\r
-\r
-static PyObject *\r
-load_package(char *name, char *pathname)\r
-{\r
- PyObject *m, *d;\r
- PyObject *file = NULL;\r
- PyObject *path = NULL;\r
- int err;\r
- char *buf = NULL;\r
- FILE *fp = NULL;\r
- struct filedescr *fdp;\r
-\r
- m = PyImport_AddModule(name);\r
- if (m == NULL)\r
- return NULL;\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("import %s # directory %s\n",\r
- name, pathname);\r
- d = PyModule_GetDict(m);\r
- file = PyString_FromString(pathname);\r
- if (file == NULL)\r
- goto error;\r
- path = Py_BuildValue("[O]", file);\r
- if (path == NULL)\r
- goto error;\r
- err = PyDict_SetItemString(d, "__file__", file);\r
- if (err == 0)\r
- err = PyDict_SetItemString(d, "__path__", path);\r
- if (err != 0)\r
- goto error;\r
- buf = PyMem_MALLOC(MAXPATHLEN+1);\r
- if (buf == NULL) {\r
- PyErr_NoMemory();\r
- goto error;\r
- }\r
- buf[0] = '\0';\r
- fdp = find_module(name, "__init__", path, buf, MAXPATHLEN+1, &fp, NULL);\r
- if (fdp == NULL) {\r
- if (PyErr_ExceptionMatches(PyExc_ImportError)) {\r
- PyErr_Clear();\r
- Py_INCREF(m);\r
- }\r
- else\r
- m = NULL;\r
- goto cleanup;\r
- }\r
- m = load_module(name, fp, buf, fdp->type, NULL);\r
- if (fp != NULL)\r
- fclose(fp);\r
- goto cleanup;\r
-\r
- error:\r
- m = NULL;\r
- cleanup:\r
- if (buf)\r
- PyMem_FREE(buf);\r
- Py_XDECREF(path);\r
- Py_XDECREF(file);\r
- return m;\r
-}\r
-\r
-\r
-/* Helper to test for built-in module */\r
-\r
-static int\r
-is_builtin(char *name)\r
-{\r
- int i;\r
- for (i = 0; PyImport_Inittab[i].name != NULL; i++) {\r
- if (strcmp(name, PyImport_Inittab[i].name) == 0) {\r
- if (PyImport_Inittab[i].initfunc == NULL)\r
- return -1;\r
- else\r
- return 1;\r
- }\r
- }\r
- return 0;\r
-}\r
-\r
-\r
-/* Return an importer object for a sys.path/pkg.__path__ item 'p',\r
- possibly by fetching it from the path_importer_cache dict. If it\r
- wasn't yet cached, traverse path_hooks until a hook is found\r
- that can handle the path item. Return None if no hook could;\r
- this tells our caller it should fall back to the builtin\r
- import mechanism. Cache the result in path_importer_cache.\r
- Returns a borrowed reference. */\r
-\r
-static PyObject *\r
-get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,\r
- PyObject *p)\r
-{\r
- PyObject *importer;\r
- Py_ssize_t j, nhooks;\r
-\r
- /* These conditions are the caller's responsibility: */\r
- assert(PyList_Check(path_hooks));\r
- assert(PyDict_Check(path_importer_cache));\r
-\r
- nhooks = PyList_Size(path_hooks);\r
- if (nhooks < 0)\r
- return NULL; /* Shouldn't happen */\r
-\r
- importer = PyDict_GetItem(path_importer_cache, p);\r
- if (importer != NULL)\r
- return importer;\r
-\r
- /* set path_importer_cache[p] to None to avoid recursion */\r
- if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)\r
- return NULL;\r
-\r
- for (j = 0; j < nhooks; j++) {\r
- PyObject *hook = PyList_GetItem(path_hooks, j);\r
- if (hook == NULL)\r
- return NULL;\r
- importer = PyObject_CallFunctionObjArgs(hook, p, NULL);\r
- if (importer != NULL)\r
- break;\r
-\r
- if (!PyErr_ExceptionMatches(PyExc_ImportError)) {\r
- return NULL;\r
- }\r
- PyErr_Clear();\r
- }\r
- if (importer == NULL) {\r
- importer = PyObject_CallFunctionObjArgs(\r
- (PyObject *)&PyNullImporter_Type, p, NULL\r
- );\r
- if (importer == NULL) {\r
- if (PyErr_ExceptionMatches(PyExc_ImportError)) {\r
- PyErr_Clear();\r
- return Py_None;\r
- }\r
- }\r
- }\r
- if (importer != NULL) {\r
- int err = PyDict_SetItem(path_importer_cache, p, importer);\r
- Py_DECREF(importer);\r
- if (err != 0)\r
- return NULL;\r
- }\r
- return importer;\r
-}\r
-\r
-PyAPI_FUNC(PyObject *)\r
-PyImport_GetImporter(PyObject *path) {\r
- PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;\r
-\r
- if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {\r
- if ((path_hooks = PySys_GetObject("path_hooks"))) {\r
- importer = get_path_importer(path_importer_cache,\r
- path_hooks, path);\r
- }\r
- }\r
- Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */\r
- return importer;\r
-}\r
-\r
-/* Search the path (default sys.path) for a module. Return the\r
- corresponding filedescr struct, and (via return arguments) the\r
- pathname and an open file. Return NULL if the module is not found. */\r
-\r
-#ifdef MS_COREDLL\r
-extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,\r
- char *, Py_ssize_t);\r
-#endif\r
-\r
-static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);\r
-static int find_init_module(char *); /* Forward */\r
-static struct filedescr importhookdescr = {"", "", IMP_HOOK};\r
-\r
-static struct filedescr *\r
-find_module(char *fullname, char *subname, PyObject *path, char *buf,\r
- size_t buflen, FILE **p_fp, PyObject **p_loader)\r
-{\r
- Py_ssize_t i, npath;\r
- size_t len, namelen;\r
- struct filedescr *fdp = NULL;\r
- char *filemode;\r
- FILE *fp = NULL;\r
- PyObject *path_hooks, *path_importer_cache;\r
- static struct filedescr fd_frozen = {"", "", PY_FROZEN};\r
- static struct filedescr fd_builtin = {"", "", C_BUILTIN};\r
- static struct filedescr fd_package = {"", "", PKG_DIRECTORY};\r
- char *name;\r
-#if defined(PYOS_OS2)\r
- size_t saved_len;\r
- size_t saved_namelen;\r
- char *saved_buf = NULL;\r
-#endif\r
- if (p_loader != NULL)\r
- *p_loader = NULL;\r
-\r
- if (strlen(subname) > MAXPATHLEN) {\r
- PyErr_SetString(PyExc_OverflowError,\r
- "module name is too long");\r
- return NULL;\r
- }\r
- name = PyMem_MALLOC(MAXPATHLEN+1);\r
- if (name == NULL) {\r
- PyErr_NoMemory();\r
- return NULL;\r
- }\r
- strcpy(name, subname);\r
-\r
- /* sys.meta_path import hook */\r
- if (p_loader != NULL) {\r
- PyObject *meta_path;\r
-\r
- meta_path = PySys_GetObject("meta_path");\r
- if (meta_path == NULL || !PyList_Check(meta_path)) {\r
- PyErr_SetString(PyExc_RuntimeError,\r
- "sys.meta_path must be a list of "\r
- "import hooks");\r
- goto error_exit;\r
- }\r
- Py_INCREF(meta_path); /* zap guard */\r
- npath = PyList_Size(meta_path);\r
- for (i = 0; i < npath; i++) {\r
- PyObject *loader;\r
- PyObject *hook = PyList_GetItem(meta_path, i);\r
- loader = PyObject_CallMethod(hook, "find_module",\r
- "sO", fullname,\r
- path != NULL ?\r
- path : Py_None);\r
- if (loader == NULL) {\r
- Py_DECREF(meta_path);\r
- goto error_exit; /* true error */\r
- }\r
- if (loader != Py_None) {\r
- /* a loader was found */\r
- *p_loader = loader;\r
- Py_DECREF(meta_path);\r
- PyMem_FREE(name);\r
- return &importhookdescr;\r
- }\r
- Py_DECREF(loader);\r
- }\r
- Py_DECREF(meta_path);\r
- }\r
-\r
- if (path != NULL && PyString_Check(path)) {\r
- /* The only type of submodule allowed inside a "frozen"\r
- package are other frozen modules or packages. */\r
- if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {\r
- PyErr_SetString(PyExc_ImportError,\r
- "full frozen module name too long");\r
- goto error_exit;\r
- }\r
- strcpy(buf, PyString_AsString(path));\r
- strcat(buf, ".");\r
- strcat(buf, name);\r
- strcpy(name, buf);\r
- if (find_frozen(name) != NULL) {\r
- strcpy(buf, name);\r
- PyMem_FREE(name);\r
- return &fd_frozen;\r
- }\r
- PyErr_Format(PyExc_ImportError,\r
- "No frozen submodule named %.200s", name);\r
- goto error_exit;\r
- }\r
- if (path == NULL) {\r
- if (is_builtin(name)) {\r
- strcpy(buf, name);\r
- PyMem_FREE(name);\r
- return &fd_builtin;\r
- }\r
- if ((find_frozen(name)) != NULL) {\r
- strcpy(buf, name);\r
- PyMem_FREE(name);\r
- return &fd_frozen;\r
- }\r
-\r
-#ifdef MS_COREDLL\r
- fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);\r
- if (fp != NULL) {\r
- *p_fp = fp;\r
- PyMem_FREE(name);\r
- return fdp;\r
- }\r
-#endif\r
- path = PySys_GetObject("path");\r
- }\r
- if (path == NULL || !PyList_Check(path)) {\r
- PyErr_SetString(PyExc_RuntimeError,\r
- "sys.path must be a list of directory names");\r
- goto error_exit;\r
- }\r
-\r
- path_hooks = PySys_GetObject("path_hooks");\r
- if (path_hooks == NULL || !PyList_Check(path_hooks)) {\r
- PyErr_SetString(PyExc_RuntimeError,\r
- "sys.path_hooks must be a list of "\r
- "import hooks");\r
- goto error_exit;\r
- }\r
- path_importer_cache = PySys_GetObject("path_importer_cache");\r
- if (path_importer_cache == NULL ||\r
- !PyDict_Check(path_importer_cache)) {\r
- PyErr_SetString(PyExc_RuntimeError,\r
- "sys.path_importer_cache must be a dict");\r
- goto error_exit;\r
- }\r
-\r
- npath = PyList_Size(path);\r
- namelen = strlen(name);\r
- for (i = 0; i < npath; i++) {\r
- PyObject *copy = NULL;\r
- PyObject *v = PyList_GetItem(path, i);\r
- if (!v)\r
- goto error_exit;\r
-#ifdef Py_USING_UNICODE\r
- if (PyUnicode_Check(v)) {\r
- copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),\r
- PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);\r
- if (copy == NULL)\r
- goto error_exit;\r
- v = copy;\r
- }\r
- else\r
-#endif\r
- if (!PyString_Check(v))\r
- continue;\r
- len = PyString_GET_SIZE(v);\r
- if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {\r
- Py_XDECREF(copy);\r
- continue; /* Too long */\r
- }\r
- strcpy(buf, PyString_AS_STRING(v));\r
- if (strlen(buf) != len) {\r
- Py_XDECREF(copy);\r
- continue; /* v contains '\0' */\r
- }\r
-\r
- /* sys.path_hooks import hook */\r
- if (p_loader != NULL) {\r
- PyObject *importer;\r
-\r
- importer = get_path_importer(path_importer_cache,\r
- path_hooks, v);\r
- if (importer == NULL) {\r
- Py_XDECREF(copy);\r
- goto error_exit;\r
- }\r
- /* Note: importer is a borrowed reference */\r
- if (importer != Py_None) {\r
- PyObject *loader;\r
- loader = PyObject_CallMethod(importer,\r
- "find_module",\r
- "s", fullname);\r
- Py_XDECREF(copy);\r
- if (loader == NULL)\r
- goto error_exit; /* error */\r
- if (loader != Py_None) {\r
- /* a loader was found */\r
- *p_loader = loader;\r
- PyMem_FREE(name);\r
- return &importhookdescr;\r
- }\r
- Py_DECREF(loader);\r
- continue;\r
- }\r
- }\r
- /* no hook was found, use builtin import */\r
-\r
- if (len > 0 && buf[len-1] != SEP\r
-#ifdef ALTSEP\r
- && buf[len-1] != ALTSEP\r
-#endif\r
- )\r
- buf[len++] = SEP;\r
- strcpy(buf+len, name);\r
- len += namelen;\r
-\r
- /* Check for package import (buf holds a directory name,\r
- and there's an __init__ module in that directory */\r
- if (isdir(buf) && /* it's an existing directory */\r
- case_ok(buf, len, namelen, name)) { /* case matches */\r
- if (find_init_module(buf)) { /* and has __init__.py */\r
- Py_XDECREF(copy);\r
- PyMem_FREE(name);\r
- return &fd_package;\r
- }\r
- else {\r
- char warnstr[MAXPATHLEN+80];\r
- sprintf(warnstr, "Not importing directory "\r
- "'%.*s': missing __init__.py",\r
- MAXPATHLEN, buf);\r
- if (PyErr_Warn(PyExc_ImportWarning,\r
- warnstr)) {\r
- Py_XDECREF(copy);\r
- goto error_exit;\r
- }\r
- }\r
- }\r
-#if defined(PYOS_OS2)\r
- /* take a snapshot of the module spec for restoration\r
- * after the 8 character DLL hackery\r
- */\r
- saved_buf = strdup(buf);\r
- saved_len = len;\r
- saved_namelen = namelen;\r
-#endif /* PYOS_OS2 */\r
- for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {\r
-#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)\r
- /* OS/2 limits DLLs to 8 character names (w/o\r
- extension)\r
- * so if the name is longer than that and its a\r
- * dynamically loaded module we're going to try,\r
- * truncate the name before trying\r
- */\r
- if (strlen(subname) > 8) {\r
- /* is this an attempt to load a C extension? */\r
- const struct filedescr *scan;\r
- scan = _PyImport_DynLoadFiletab;\r
- while (scan->suffix != NULL) {\r
- if (!strcmp(scan->suffix, fdp->suffix))\r
- break;\r
- else\r
- scan++;\r
- }\r
- if (scan->suffix != NULL) {\r
- /* yes, so truncate the name */\r
- namelen = 8;\r
- len -= strlen(subname) - namelen;\r
- buf[len] = '\0';\r
- }\r
- }\r
-#endif /* PYOS_OS2 */\r
- strcpy(buf+len, fdp->suffix);\r
- if (Py_VerboseFlag > 1)\r
- PySys_WriteStderr("# trying %s\n", buf);\r
- filemode = fdp->mode;\r
- if (filemode[0] == 'U')\r
- filemode = "r" PY_STDIOTEXTMODE;\r
- fp = fopen(buf, filemode);\r
- if (fp != NULL) {\r
- if (case_ok(buf, len, namelen, name))\r
- break;\r
- else { /* continue search */\r
- fclose(fp);\r
- fp = NULL;\r
- }\r
- }\r
-#if defined(PYOS_OS2)\r
- /* restore the saved snapshot */\r
- strcpy(buf, saved_buf);\r
- len = saved_len;\r
- namelen = saved_namelen;\r
-#endif\r
- }\r
-#if defined(PYOS_OS2)\r
- /* don't need/want the module name snapshot anymore */\r
- if (saved_buf)\r
- {\r
- free(saved_buf);\r
- saved_buf = NULL;\r
- }\r
-#endif\r
- Py_XDECREF(copy);\r
- if (fp != NULL)\r
- break;\r
- }\r
- if (fp == NULL) {\r
- PyErr_Format(PyExc_ImportError,\r
- "No module named %.200s", name);\r
- goto error_exit;\r
- }\r
- *p_fp = fp;\r
- PyMem_FREE(name);\r
- return fdp;\r
-\r
-error_exit:\r
- PyMem_FREE(name);\r
- return NULL;\r
-}\r
-\r
-/* Helpers for main.c\r
- * Find the source file corresponding to a named module\r
- */\r
-struct filedescr *\r
-_PyImport_FindModule(const char *name, PyObject *path, char *buf,\r
- size_t buflen, FILE **p_fp, PyObject **p_loader)\r
-{\r
- return find_module((char *) name, (char *) name, path,\r
- buf, buflen, p_fp, p_loader);\r
-}\r
-\r
-PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)\r
-{\r
- return fd->type == PY_SOURCE || fd->type == PY_COMPILED;\r
-}\r
-\r
-/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)\r
- * The arguments here are tricky, best shown by example:\r
- * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0\r
- * ^ ^ ^ ^\r
- * |--------------------- buf ---------------------|\r
- * |------------------- len ------------------|\r
- * |------ name -------|\r
- * |----- namelen -----|\r
- * buf is the full path, but len only counts up to (& exclusive of) the\r
- * extension. name is the module name, also exclusive of extension.\r
- *\r
- * We've already done a successful stat() or fopen() on buf, so know that\r
- * there's some match, possibly case-insensitive.\r
- *\r
- * case_ok() is to return 1 if there's a case-sensitive match for\r
- * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK\r
- * exists.\r
- *\r
- * case_ok() is used to implement case-sensitive import semantics even\r
- * on platforms with case-insensitive filesystems. It's trivial to implement\r
- * for case-sensitive filesystems. It's pretty much a cross-platform\r
- * nightmare for systems with case-insensitive filesystems.\r
- */\r
-\r
-/* First we may need a pile of platform-specific header files; the sequence\r
- * of #if's here should match the sequence in the body of case_ok().\r
- */\r
-#if defined(MS_WINDOWS)\r
-#include <windows.h>\r
-\r
-#elif defined(DJGPP)\r
-#include <dir.h>\r
-\r
-#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)\r
-#include <sys/types.h>\r
-#include <dirent.h>\r
-\r
-#elif defined(PYOS_OS2)\r
-#define INCL_DOS\r
-#define INCL_DOSERRORS\r
-#define INCL_NOPMAPI\r
-#include <os2.h>\r
-\r
-#elif defined(RISCOS)\r
-#include "oslib/osfscontrol.h"\r
-#endif\r
-\r
-static int\r
-case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)\r
-{\r
-/* Pick a platform-specific implementation; the sequence of #if's here should\r
- * match the sequence just above.\r
- */\r
-\r
-/* MS_WINDOWS */\r
-#if defined(MS_WINDOWS)\r
- WIN32_FIND_DATA data;\r
- HANDLE h;\r
-\r
- if (Py_GETENV("PYTHONCASEOK") != NULL)\r
- return 1;\r
-\r
- h = FindFirstFile(buf, &data);\r
- if (h == INVALID_HANDLE_VALUE) {\r
- PyErr_Format(PyExc_NameError,\r
- "Can't find file for module %.100s\n(filename %.300s)",\r
- name, buf);\r
- return 0;\r
- }\r
- FindClose(h);\r
- return strncmp(data.cFileName, name, namelen) == 0;\r
-\r
-/* DJGPP */\r
-#elif defined(DJGPP)\r
- struct ffblk ffblk;\r
- int done;\r
-\r
- if (Py_GETENV("PYTHONCASEOK") != NULL)\r
- return 1;\r
-\r
- done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);\r
- if (done) {\r
- PyErr_Format(PyExc_NameError,\r
- "Can't find file for module %.100s\n(filename %.300s)",\r
- name, buf);\r
- return 0;\r
- }\r
- return strncmp(ffblk.ff_name, name, namelen) == 0;\r
-\r
-/* new-fangled macintosh (macosx) or Cygwin */\r
-#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)\r
- DIR *dirp;\r
- struct dirent *dp;\r
- char dirname[MAXPATHLEN + 1];\r
- const int dirlen = len - namelen - 1; /* don't want trailing SEP */\r
-\r
- if (Py_GETENV("PYTHONCASEOK") != NULL)\r
- return 1;\r
-\r
- /* Copy the dir component into dirname; substitute "." if empty */\r
- if (dirlen <= 0) {\r
- dirname[0] = '.';\r
- dirname[1] = '\0';\r
- }\r
- else {\r
- assert(dirlen <= MAXPATHLEN);\r
- memcpy(dirname, buf, dirlen);\r
- dirname[dirlen] = '\0';\r
- }\r
- /* Open the directory and search the entries for an exact match. */\r
- dirp = opendir(dirname);\r
- if (dirp) {\r
- char *nameWithExt = buf + len - namelen;\r
- while ((dp = readdir(dirp)) != NULL) {\r
- const int thislen =\r
-#ifdef _DIRENT_HAVE_D_NAMELEN\r
- dp->d_namlen;\r
-#else\r
- strlen(dp->d_name);\r
-#endif\r
- if (thislen >= namelen &&\r
- strcmp(dp->d_name, nameWithExt) == 0) {\r
- (void)closedir(dirp);\r
- return 1; /* Found */\r
- }\r
- }\r
- (void)closedir(dirp);\r
- }\r
- return 0 ; /* Not found */\r
-\r
-/* RISC OS */\r
-#elif defined(RISCOS)\r
- char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */\r
- char buf2[MAXPATHLEN+2];\r
- char *nameWithExt = buf+len-namelen;\r
- int canonlen;\r
- os_error *e;\r
-\r
- if (Py_GETENV("PYTHONCASEOK") != NULL)\r
- return 1;\r
-\r
- /* workaround:\r
- append wildcard, otherwise case of filename wouldn't be touched */\r
- strcpy(buf2, buf);\r
- strcat(buf2, "*");\r
-\r
- e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);\r
- canonlen = MAXPATHLEN+1-canonlen;\r
- if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )\r
- return 0;\r
- if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)\r
- return 1; /* match */\r
-\r
- return 0;\r
-\r
-/* OS/2 */\r
-#elif defined(PYOS_OS2)\r
- HDIR hdir = 1;\r
- ULONG srchcnt = 1;\r
- FILEFINDBUF3 ffbuf;\r
- APIRET rc;\r
-\r
- if (Py_GETENV("PYTHONCASEOK") != NULL)\r
- return 1;\r
-\r
- rc = DosFindFirst(buf,\r
- &hdir,\r
- FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,\r
- &ffbuf, sizeof(ffbuf),\r
- &srchcnt,\r
- FIL_STANDARD);\r
- if (rc != NO_ERROR)\r
- return 0;\r
- return strncmp(ffbuf.achName, name, namelen) == 0;\r
-\r
-/* assuming it's a case-sensitive filesystem, so there's nothing to do! */\r
-#else\r
- return 1;\r
-\r
-#endif\r
-}\r
-\r
-\r
-#ifdef HAVE_STAT\r
-/* Helper to look for __init__.py or __init__.py[co] in potential package */\r
-static int\r
-find_init_module(char *buf)\r
-{\r
- const size_t save_len = strlen(buf);\r
- size_t i = save_len;\r
- char *pname; /* pointer to start of __init__ */\r
- struct stat statbuf;\r
-\r
-/* For calling case_ok(buf, len, namelen, name):\r
- * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0\r
- * ^ ^ ^ ^\r
- * |--------------------- buf ---------------------|\r
- * |------------------- len ------------------|\r
- * |------ name -------|\r
- * |----- namelen -----|\r
- */\r
- if (save_len + 13 >= MAXPATHLEN)\r
- return 0;\r
- buf[i++] = SEP;\r
- pname = buf + i;\r
- strcpy(pname, "__init__.py");\r
- if (stat(buf, &statbuf) == 0) {\r
- if (case_ok(buf,\r
- save_len + 9, /* len("/__init__") */\r
- 8, /* len("__init__") */\r
- pname)) {\r
- buf[save_len] = '\0';\r
- return 1;\r
- }\r
- }\r
- i += strlen(pname);\r
- strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");\r
- if (stat(buf, &statbuf) == 0) {\r
- if (case_ok(buf,\r
- save_len + 9, /* len("/__init__") */\r
- 8, /* len("__init__") */\r
- pname)) {\r
- buf[save_len] = '\0';\r
- return 1;\r
- }\r
- }\r
- buf[save_len] = '\0';\r
- return 0;\r
-}\r
-\r
-#else\r
-\r
-#ifdef RISCOS\r
-static int\r
-find_init_module(buf)\r
- char *buf;\r
-{\r
- int save_len = strlen(buf);\r
- int i = save_len;\r
-\r
- if (save_len + 13 >= MAXPATHLEN)\r
- return 0;\r
- buf[i++] = SEP;\r
- strcpy(buf+i, "__init__/py");\r
- if (isfile(buf)) {\r
- buf[save_len] = '\0';\r
- return 1;\r
- }\r
-\r
- if (Py_OptimizeFlag)\r
- strcpy(buf+i, "o");\r
- else\r
- strcpy(buf+i, "c");\r
- if (isfile(buf)) {\r
- buf[save_len] = '\0';\r
- return 1;\r
- }\r
- buf[save_len] = '\0';\r
- return 0;\r
-}\r
-#endif /*RISCOS*/\r
-\r
-#endif /* HAVE_STAT */\r
-\r
-\r
-static int init_builtin(char *); /* Forward */\r
-\r
-/* Load an external module using the default search path and return\r
- its module object WITH INCREMENTED REFERENCE COUNT */\r
-\r
-static PyObject *\r
-load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)\r
-{\r
- PyObject *modules;\r
- PyObject *m;\r
- int err;\r
-\r
- /* First check that there's an open file (if we need one) */\r
- switch (type) {\r
- case PY_SOURCE:\r
- case PY_COMPILED:\r
- if (fp == NULL) {\r
- PyErr_Format(PyExc_ValueError,\r
- "file object required for import (type code %d)",\r
- type);\r
- return NULL;\r
- }\r
- }\r
-\r
- switch (type) {\r
-\r
- case PY_SOURCE:\r
- m = load_source_module(name, pathname, fp);\r
- break;\r
-\r
- case PY_COMPILED:\r
- m = load_compiled_module(name, pathname, fp);\r
- break;\r
-\r
-#ifdef HAVE_DYNAMIC_LOADING\r
- case C_EXTENSION:\r
- m = _PyImport_LoadDynamicModule(name, pathname, fp);\r
- break;\r
-#endif\r
-\r
- case PKG_DIRECTORY:\r
- m = load_package(name, pathname);\r
- break;\r
-\r
- case C_BUILTIN:\r
- case PY_FROZEN:\r
- if (pathname != NULL && pathname[0] != '\0')\r
- name = pathname;\r
- if (type == C_BUILTIN)\r
- err = init_builtin(name);\r
- else\r
- err = PyImport_ImportFrozenModule(name);\r
- if (err < 0)\r
- return NULL;\r
- if (err == 0) {\r
- PyErr_Format(PyExc_ImportError,\r
- "Purported %s module %.200s not found",\r
- type == C_BUILTIN ?\r
- "builtin" : "frozen",\r
- name);\r
- return NULL;\r
- }\r
- modules = PyImport_GetModuleDict();\r
- m = PyDict_GetItemString(modules, name);\r
- if (m == NULL) {\r
- PyErr_Format(\r
- PyExc_ImportError,\r
- "%s module %.200s not properly initialized",\r
- type == C_BUILTIN ?\r
- "builtin" : "frozen",\r
- name);\r
- return NULL;\r
- }\r
- Py_INCREF(m);\r
- break;\r
-\r
- case IMP_HOOK: {\r
- if (loader == NULL) {\r
- PyErr_SetString(PyExc_ImportError,\r
- "import hook without loader");\r
- return NULL;\r
- }\r
- m = PyObject_CallMethod(loader, "load_module", "s", name);\r
- break;\r
- }\r
-\r
- default:\r
- PyErr_Format(PyExc_ImportError,\r
- "Don't know how to import %.200s (type code %d)",\r
- name, type);\r
- m = NULL;\r
-\r
- }\r
-\r
- return m;\r
-}\r
-\r
-\r
-/* Initialize a built-in module.\r
- Return 1 for success, 0 if the module is not found, and -1 with\r
- an exception set if the initialization failed. */\r
-\r
-static int\r
-init_builtin(char *name)\r
-{\r
- struct _inittab *p;\r
-\r
- if (_PyImport_FindExtension(name, name) != NULL)\r
- return 1;\r
-\r
- for (p = PyImport_Inittab; p->name != NULL; p++) {\r
- if (strcmp(name, p->name) == 0) {\r
- if (p->initfunc == NULL) {\r
- PyErr_Format(PyExc_ImportError,\r
- "Cannot re-init internal module %.200s",\r
- name);\r
- return -1;\r
- }\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("import %s # builtin\n", name);\r
- (*p->initfunc)();\r
- if (PyErr_Occurred())\r
- return -1;\r
- if (_PyImport_FixupExtension(name, name) == NULL)\r
- return -1;\r
- return 1;\r
- }\r
- }\r
- return 0;\r
-}\r
-\r
-\r
-/* Frozen modules */\r
-\r
-static struct _frozen *\r
-find_frozen(char *name)\r
-{\r
- struct _frozen *p;\r
-\r
- for (p = PyImport_FrozenModules; ; p++) {\r
- if (p->name == NULL)\r
- return NULL;\r
- if (strcmp(p->name, name) == 0)\r
- break;\r
- }\r
- return p;\r
-}\r
-\r
-static PyObject *\r
-get_frozen_object(char *name)\r
-{\r
- struct _frozen *p = find_frozen(name);\r
- int size;\r
-\r
- if (p == NULL) {\r
- PyErr_Format(PyExc_ImportError,\r
- "No such frozen object named %.200s",\r
- name);\r
- return NULL;\r
- }\r
- if (p->code == NULL) {\r
- PyErr_Format(PyExc_ImportError,\r
- "Excluded frozen object named %.200s",\r
- name);\r
- return NULL;\r
- }\r
- size = p->size;\r
- if (size < 0)\r
- size = -size;\r
- return PyMarshal_ReadObjectFromString((char *)p->code, size);\r
-}\r
-\r
-/* Initialize a frozen module.\r
- Return 1 for succes, 0 if the module is not found, and -1 with\r
- an exception set if the initialization failed.\r
- This function is also used from frozenmain.c */\r
-\r
-int\r
-PyImport_ImportFrozenModule(char *name)\r
-{\r
- struct _frozen *p = find_frozen(name);\r
- PyObject *co;\r
- PyObject *m;\r
- int ispackage;\r
- int size;\r
-\r
- if (p == NULL)\r
- return 0;\r
- if (p->code == NULL) {\r
- PyErr_Format(PyExc_ImportError,\r
- "Excluded frozen object named %.200s",\r
- name);\r
- return -1;\r
- }\r
- size = p->size;\r
- ispackage = (size < 0);\r
- if (ispackage)\r
- size = -size;\r
- if (Py_VerboseFlag)\r
- PySys_WriteStderr("import %s # frozen%s\n",\r
- name, ispackage ? " package" : "");\r
- co = PyMarshal_ReadObjectFromString((char *)p->code, size);\r
- if (co == NULL)\r
- return -1;\r
- if (!PyCode_Check(co)) {\r
- PyErr_Format(PyExc_TypeError,\r
- "frozen object %.200s is not a code object",\r
- name);\r
- goto err_return;\r
- }\r
- if (ispackage) {\r
- /* Set __path__ to the package name */\r
- PyObject *d, *s;\r
- int err;\r
- m = PyImport_AddModule(name);\r
- if (m == NULL)\r
- goto err_return;\r
- d = PyModule_GetDict(m);\r
- s = PyString_InternFromString(name);\r
- if (s == NULL)\r
- goto err_return;\r
- err = PyDict_SetItemString(d, "__path__", s);\r
- Py_DECREF(s);\r
- if (err != 0)\r
- goto err_return;\r
- }\r
- m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");\r
- if (m == NULL)\r
- goto err_return;\r
- Py_DECREF(co);\r
- Py_DECREF(m);\r
- return 1;\r
-err_return:\r
- Py_DECREF(co);\r
- return -1;\r
-}\r
-\r
-\r
-/* Import a module, either built-in, frozen, or external, and return\r
- its module object WITH INCREMENTED REFERENCE COUNT */\r
-\r
-PyObject *\r
-PyImport_ImportModule(const char *name)\r
-{\r
- PyObject *pname;\r
- PyObject *result;\r
-\r
- pname = PyString_FromString(name);\r
- if (pname == NULL)\r
- return NULL;\r
- result = PyImport_Import(pname);\r
- Py_DECREF(pname);\r
- return result;\r
-}\r
-\r
-/* Import a module without blocking\r
- *\r
- * At first it tries to fetch the module from sys.modules. If the module was\r
- * never loaded before it loads it with PyImport_ImportModule() unless another\r
- * thread holds the import lock. In the latter case the function raises an\r
- * ImportError instead of blocking.\r
- *\r
- * Returns the module object with incremented ref count.\r
- */\r
-PyObject *\r
-PyImport_ImportModuleNoBlock(const char *name)\r
-{\r
- PyObject *result;\r
- PyObject *modules;\r
-#ifdef WITH_THREAD\r
- long me;\r
-#endif\r
-\r
- /* Try to get the module from sys.modules[name] */\r
- modules = PyImport_GetModuleDict();\r
- if (modules == NULL)\r
- return NULL;\r
-\r
- result = PyDict_GetItemString(modules, name);\r
- if (result != NULL) {\r
- Py_INCREF(result);\r
- return result;\r
- }\r
- else {\r
- PyErr_Clear();\r
- }\r
-#ifdef WITH_THREAD\r
- /* check the import lock\r
- * me might be -1 but I ignore the error here, the lock function\r
- * takes care of the problem */\r
- me = PyThread_get_thread_ident();\r
- if (import_lock_thread == -1 || import_lock_thread == me) {\r
- /* no thread or me is holding the lock */\r
- return PyImport_ImportModule(name);\r
- }\r
- else {\r
- PyErr_Format(PyExc_ImportError,\r
- "Failed to import %.200s because the import lock"\r
- "is held by another thread.",\r
- name);\r
- return NULL;\r
- }\r
-#else\r
- return PyImport_ImportModule(name);\r
-#endif\r
-}\r
-\r
-/* Forward declarations for helper routines */\r
-static PyObject *get_parent(PyObject *globals, char *buf,\r
- Py_ssize_t *p_buflen, int level);\r
-static PyObject *load_next(PyObject *mod, PyObject *altmod,\r
- char **p_name, char *buf, Py_ssize_t *p_buflen);\r
-static int mark_miss(char *name);\r
-static int ensure_fromlist(PyObject *mod, PyObject *fromlist,\r
- char *buf, Py_ssize_t buflen, int recursive);\r
-static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);\r
-\r
-/* The Magnum Opus of dotted-name import :-) */\r
-\r
-static PyObject *\r
-import_module_level(char *name, PyObject *globals, PyObject *locals,\r
- PyObject *fromlist, int level)\r
-{\r
- char *buf;\r
- Py_ssize_t buflen = 0;\r
- PyObject *parent, *head, *next, *tail;\r
-\r
- if (strchr(name, '/') != NULL\r
-#ifdef MS_WINDOWS\r
- || strchr(name, '\\') != NULL\r
-#endif\r
- ) {\r
- PyErr_SetString(PyExc_ImportError,\r
- "Import by filename is not supported.");\r
- return NULL;\r
- }\r
-\r
- buf = PyMem_MALLOC(MAXPATHLEN+1);\r
- if (buf == NULL) {\r
- return PyErr_NoMemory();\r
- }\r
- parent = get_parent(globals, buf, &buflen, level);\r
- if (parent == NULL)\r
- goto error_exit;\r
-\r
- head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,\r
- &buflen);\r
- if (head == NULL)\r
- goto error_exit;\r
-\r
- tail = head;\r
- Py_INCREF(tail);\r
- while (name) {\r
- next = load_next(tail, tail, &name, buf, &buflen);\r
- Py_DECREF(tail);\r
- if (next == NULL) {\r
- Py_DECREF(head);\r
- goto error_exit;\r
- }\r
- tail = next;\r
- }\r
- if (tail == Py_None) {\r
- /* If tail is Py_None, both get_parent and load_next found\r
- an empty module name: someone called __import__("") or\r
- doctored faulty bytecode */\r
- Py_DECREF(tail);\r
- Py_DECREF(head);\r
- PyErr_SetString(PyExc_ValueError,\r
- "Empty module name");\r
- goto error_exit;\r
- }\r
-\r
- if (fromlist != NULL) {\r
- int b = (fromlist == Py_None) ? 0 : PyObject_IsTrue(fromlist);\r
- if (b < 0) {\r
- Py_DECREF(tail);\r
- Py_DECREF(head);\r
- goto error_exit;\r
- }\r
- if (!b)\r
- fromlist = NULL;\r
- }\r
-\r
- if (fromlist == NULL) {\r
- Py_DECREF(tail);\r
- PyMem_FREE(buf);\r
- return head;\r
- }\r
-\r
- Py_DECREF(head);\r
- if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {\r
- Py_DECREF(tail);\r
- goto error_exit;\r
- }\r
-\r
- PyMem_FREE(buf);\r
- return tail;\r
-\r
-error_exit:\r
- PyMem_FREE(buf);\r
- return NULL;\r
-}\r
-\r
-PyObject *\r
-PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,\r
- PyObject *fromlist, int level)\r
-{\r
- PyObject *result;\r
- _PyImport_AcquireLock();\r
- result = import_module_level(name, globals, locals, fromlist, level);\r
- if (_PyImport_ReleaseLock() < 0) {\r
- Py_XDECREF(result);\r
- PyErr_SetString(PyExc_RuntimeError,\r
- "not holding the import lock");\r
- return NULL;\r
- }\r
- return result;\r
-}\r
-\r
-/* Return the package that an import is being performed in. If globals comes\r
- from the module foo.bar.bat (not itself a package), this returns the\r
- sys.modules entry for foo.bar. If globals is from a package's __init__.py,\r
- the package's entry in sys.modules is returned, as a borrowed reference.\r
-\r
- The *name* of the returned package is returned in buf, with the length of\r
- the name in *p_buflen.\r
-\r
- If globals doesn't come from a package or a module in a package, or a\r
- corresponding entry is not found in sys.modules, Py_None is returned.\r
-*/\r
-static PyObject *\r
-get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)\r
-{\r
- static PyObject *namestr = NULL;\r
- static PyObject *pathstr = NULL;\r
- static PyObject *pkgstr = NULL;\r
- PyObject *pkgname, *modname, *modpath, *modules, *parent;\r
- int orig_level = level;\r
-\r
- if (globals == NULL || !PyDict_Check(globals) || !level)\r
- return Py_None;\r
-\r
- if (namestr == NULL) {\r
- namestr = PyString_InternFromString("__name__");\r
- if (namestr == NULL)\r
- return NULL;\r
- }\r
- if (pathstr == NULL) {\r
- pathstr = PyString_InternFromString("__path__");\r
- if (pathstr == NULL)\r
- return NULL;\r
- }\r
- if (pkgstr == NULL) {\r
- pkgstr = PyString_InternFromString("__package__");\r
- if (pkgstr == NULL)\r
- return NULL;\r
- }\r
-\r
- *buf = '\0';\r
- *p_buflen = 0;\r
- pkgname = PyDict_GetItem(globals, pkgstr);\r
-\r
- if ((pkgname != NULL) && (pkgname != Py_None)) {\r
- /* __package__ is set, so use it */\r
- Py_ssize_t len;\r
- if (!PyString_Check(pkgname)) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "__package__ set to non-string");\r
- return NULL;\r
- }\r
- len = PyString_GET_SIZE(pkgname);\r
- if (len == 0) {\r
- if (level > 0) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Attempted relative import in non-package");\r
- return NULL;\r
- }\r
- return Py_None;\r
- }\r
- if (len > MAXPATHLEN) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Package name too long");\r
- return NULL;\r
- }\r
- strcpy(buf, PyString_AS_STRING(pkgname));\r
- } else {\r
- /* __package__ not set, so figure it out and set it */\r
- modname = PyDict_GetItem(globals, namestr);\r
- if (modname == NULL || !PyString_Check(modname))\r
- return Py_None;\r
-\r
- modpath = PyDict_GetItem(globals, pathstr);\r
- if (modpath != NULL) {\r
- /* __path__ is set, so modname is already the package name */\r
- Py_ssize_t len = PyString_GET_SIZE(modname);\r
- int error;\r
- if (len > MAXPATHLEN) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Module name too long");\r
- return NULL;\r
- }\r
- strcpy(buf, PyString_AS_STRING(modname));\r
- error = PyDict_SetItem(globals, pkgstr, modname);\r
- if (error) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Could not set __package__");\r
- return NULL;\r
- }\r
- } else {\r
- /* Normal module, so work out the package name if any */\r
- char *start = PyString_AS_STRING(modname);\r
- char *lastdot = strrchr(start, '.');\r
- size_t len;\r
- int error;\r
- if (lastdot == NULL && level > 0) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Attempted relative import in non-package");\r
- return NULL;\r
- }\r
- if (lastdot == NULL) {\r
- error = PyDict_SetItem(globals, pkgstr, Py_None);\r
- if (error) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Could not set __package__");\r
- return NULL;\r
- }\r
- return Py_None;\r
- }\r
- len = lastdot - start;\r
- if (len >= MAXPATHLEN) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Module name too long");\r
- return NULL;\r
- }\r
- strncpy(buf, start, len);\r
- buf[len] = '\0';\r
- pkgname = PyString_FromString(buf);\r
- if (pkgname == NULL) {\r
- return NULL;\r
- }\r
- error = PyDict_SetItem(globals, pkgstr, pkgname);\r
- Py_DECREF(pkgname);\r
- if (error) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Could not set __package__");\r
- return NULL;\r
- }\r
- }\r
- }\r
- while (--level > 0) {\r
- char *dot = strrchr(buf, '.');\r
- if (dot == NULL) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Attempted relative import beyond "\r
- "toplevel package");\r
- return NULL;\r
- }\r
- *dot = '\0';\r
- }\r
- *p_buflen = strlen(buf);\r
-\r
- modules = PyImport_GetModuleDict();\r
- parent = PyDict_GetItemString(modules, buf);\r
- if (parent == NULL) {\r
- if (orig_level < 1) {\r
- PyObject *err_msg = PyString_FromFormat(\r
- "Parent module '%.200s' not found "\r
- "while handling absolute import", buf);\r
- if (err_msg == NULL) {\r
- return NULL;\r
- }\r
- if (!PyErr_WarnEx(PyExc_RuntimeWarning,\r
- PyString_AsString(err_msg), 1)) {\r
- *buf = '\0';\r
- *p_buflen = 0;\r
- parent = Py_None;\r
- }\r
- Py_DECREF(err_msg);\r
- } else {\r
- PyErr_Format(PyExc_SystemError,\r
- "Parent module '%.200s' not loaded, "\r
- "cannot perform relative import", buf);\r
- }\r
- }\r
- return parent;\r
- /* We expect, but can't guarantee, if parent != None, that:\r
- - parent.__name__ == buf\r
- - parent.__dict__ is globals\r
- If this is violated... Who cares? */\r
-}\r
-\r
-/* altmod is either None or same as mod */\r
-static PyObject *\r
-load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,\r
- Py_ssize_t *p_buflen)\r
-{\r
- char *name = *p_name;\r
- char *dot = strchr(name, '.');\r
- size_t len;\r
- char *p;\r
- PyObject *result;\r
-\r
- if (strlen(name) == 0) {\r
- /* completely empty module name should only happen in\r
- 'from . import' (or '__import__("")')*/\r
- Py_INCREF(mod);\r
- *p_name = NULL;\r
- return mod;\r
- }\r
-\r
- if (dot == NULL) {\r
- *p_name = NULL;\r
- len = strlen(name);\r
- }\r
- else {\r
- *p_name = dot+1;\r
- len = dot-name;\r
- }\r
- if (len == 0) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Empty module name");\r
- return NULL;\r
- }\r
-\r
- p = buf + *p_buflen;\r
- if (p != buf)\r
- *p++ = '.';\r
- if (p+len-buf >= MAXPATHLEN) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Module name too long");\r
- return NULL;\r
- }\r
- strncpy(p, name, len);\r
- p[len] = '\0';\r
- *p_buflen = p+len-buf;\r
-\r
- result = import_submodule(mod, p, buf);\r
- if (result == Py_None && altmod != mod) {\r
- Py_DECREF(result);\r
- /* Here, altmod must be None and mod must not be None */\r
- result = import_submodule(altmod, p, p);\r
- if (result != NULL && result != Py_None) {\r
- if (mark_miss(buf) != 0) {\r
- Py_DECREF(result);\r
- return NULL;\r
- }\r
- strncpy(buf, name, len);\r
- buf[len] = '\0';\r
- *p_buflen = len;\r
- }\r
- }\r
- if (result == NULL)\r
- return NULL;\r
-\r
- if (result == Py_None) {\r
- Py_DECREF(result);\r
- PyErr_Format(PyExc_ImportError,\r
- "No module named %.200s", name);\r
- return NULL;\r
- }\r
-\r
- return result;\r
-}\r
-\r
-static int\r
-mark_miss(char *name)\r
-{\r
- PyObject *modules = PyImport_GetModuleDict();\r
- return PyDict_SetItemString(modules, name, Py_None);\r
-}\r
-\r
-static int\r
-ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,\r
- int recursive)\r
-{\r
- int i;\r
-\r
- if (!PyObject_HasAttrString(mod, "__path__"))\r
- return 1;\r
-\r
- for (i = 0; ; i++) {\r
- PyObject *item = PySequence_GetItem(fromlist, i);\r
- int hasit;\r
- if (item == NULL) {\r
- if (PyErr_ExceptionMatches(PyExc_IndexError)) {\r
- PyErr_Clear();\r
- return 1;\r
- }\r
- return 0;\r
- }\r
- if (!PyString_Check(item)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "Item in ``from list'' not a string");\r
- Py_DECREF(item);\r
- return 0;\r
- }\r
- if (PyString_AS_STRING(item)[0] == '*') {\r
- PyObject *all;\r
- Py_DECREF(item);\r
- /* See if the package defines __all__ */\r
- if (recursive)\r
- continue; /* Avoid endless recursion */\r
- all = PyObject_GetAttrString(mod, "__all__");\r
- if (all == NULL)\r
- PyErr_Clear();\r
- else {\r
- int ret = ensure_fromlist(mod, all, buf, buflen, 1);\r
- Py_DECREF(all);\r
- if (!ret)\r
- return 0;\r
- }\r
- continue;\r
- }\r
- hasit = PyObject_HasAttr(mod, item);\r
- if (!hasit) {\r
- char *subname = PyString_AS_STRING(item);\r
- PyObject *submod;\r
- char *p;\r
- if (buflen + strlen(subname) >= MAXPATHLEN) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "Module name too long");\r
- Py_DECREF(item);\r
- return 0;\r
- }\r
- p = buf + buflen;\r
- *p++ = '.';\r
- strcpy(p, subname);\r
- submod = import_submodule(mod, subname, buf);\r
- Py_XDECREF(submod);\r
- if (submod == NULL) {\r
- Py_DECREF(item);\r
- return 0;\r
- }\r
- }\r
- Py_DECREF(item);\r
- }\r
-\r
- /* NOTREACHED */\r
-}\r
-\r
-static int\r
-add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,\r
- PyObject *modules)\r
-{\r
- if (mod == Py_None)\r
- return 1;\r
- /* Irrespective of the success of this load, make a\r
- reference to it in the parent package module. A copy gets\r
- saved in the modules dictionary under the full name, so get a\r
- reference from there, if need be. (The exception is when the\r
- load failed with a SyntaxError -- then there's no trace in\r
- sys.modules. In that case, of course, do nothing extra.) */\r
- if (submod == NULL) {\r
- submod = PyDict_GetItemString(modules, fullname);\r
- if (submod == NULL)\r
- return 1;\r
- }\r
- if (PyModule_Check(mod)) {\r
- /* We can't use setattr here since it can give a\r
- * spurious warning if the submodule name shadows a\r
- * builtin name */\r
- PyObject *dict = PyModule_GetDict(mod);\r
- if (!dict)\r
- return 0;\r
- if (PyDict_SetItemString(dict, subname, submod) < 0)\r
- return 0;\r
- }\r
- else {\r
- if (PyObject_SetAttrString(mod, subname, submod) < 0)\r
- return 0;\r
- }\r
- return 1;\r
-}\r
-\r
-static PyObject *\r
-import_submodule(PyObject *mod, char *subname, char *fullname)\r
-{\r
- PyObject *modules = PyImport_GetModuleDict();\r
- PyObject *m = NULL;\r
-\r
- /* Require:\r
- if mod == None: subname == fullname\r
- else: mod.__name__ + "." + subname == fullname\r
- */\r
-\r
- if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {\r
- Py_INCREF(m);\r
- }\r
- else {\r
- PyObject *path, *loader = NULL;\r
- char *buf;\r
- struct filedescr *fdp;\r
- FILE *fp = NULL;\r
-\r
- if (mod == Py_None)\r
- path = NULL;\r
- else {\r
- path = PyObject_GetAttrString(mod, "__path__");\r
- if (path == NULL) {\r
- PyErr_Clear();\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
- }\r
- }\r
-\r
- buf = PyMem_MALLOC(MAXPATHLEN+1);\r
- if (buf == NULL) {\r
- return PyErr_NoMemory();\r
- }\r
- buf[0] = '\0';\r
- fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,\r
- &fp, &loader);\r
- Py_XDECREF(path);\r
- if (fdp == NULL) {\r
- PyMem_FREE(buf);\r
- if (!PyErr_ExceptionMatches(PyExc_ImportError))\r
- return NULL;\r
- PyErr_Clear();\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
- }\r
- m = load_module(fullname, fp, buf, fdp->type, loader);\r
- Py_XDECREF(loader);\r
- if (fp)\r
- fclose(fp);\r
- if (!add_submodule(mod, m, fullname, subname, modules)) {\r
- Py_XDECREF(m);\r
- m = NULL;\r
- }\r
- PyMem_FREE(buf);\r
- }\r
-\r
- return m;\r
-}\r
-\r
-\r
-/* Re-import a module of any kind and return its module object, WITH\r
- INCREMENTED REFERENCE COUNT */\r
-\r
-PyObject *\r
-PyImport_ReloadModule(PyObject *m)\r
-{\r
- PyInterpreterState *interp = PyThreadState_Get()->interp;\r
- PyObject *modules_reloading = interp->modules_reloading;\r
- PyObject *modules = PyImport_GetModuleDict();\r
- PyObject *path = NULL, *loader = NULL, *existing_m = NULL;\r
- char *name, *subname;\r
- char *buf;\r
- struct filedescr *fdp;\r
- FILE *fp = NULL;\r
- PyObject *newm;\r
-\r
- if (modules_reloading == NULL) {\r
- Py_FatalError("PyImport_ReloadModule: "\r
- "no modules_reloading dictionary!");\r
- return NULL;\r
- }\r
-\r
- if (m == NULL || !PyModule_Check(m)) {\r
- PyErr_SetString(PyExc_TypeError,\r
- "reload() argument must be module");\r
- return NULL;\r
- }\r
- name = PyModule_GetName(m);\r
- if (name == NULL)\r
- return NULL;\r
- if (m != PyDict_GetItemString(modules, name)) {\r
- PyErr_Format(PyExc_ImportError,\r
- "reload(): module %.200s not in sys.modules",\r
- name);\r
- return NULL;\r
- }\r
- existing_m = PyDict_GetItemString(modules_reloading, name);\r
- if (existing_m != NULL) {\r
- /* Due to a recursive reload, this module is already\r
- being reloaded. */\r
- Py_INCREF(existing_m);\r
- return existing_m;\r
- }\r
- if (PyDict_SetItemString(modules_reloading, name, m) < 0)\r
- return NULL;\r
-\r
- subname = strrchr(name, '.');\r
- if (subname == NULL)\r
- subname = name;\r
- else {\r
- PyObject *parentname, *parent;\r
- parentname = PyString_FromStringAndSize(name, (subname-name));\r
- if (parentname == NULL) {\r
- imp_modules_reloading_clear();\r
- return NULL;\r
- }\r
- parent = PyDict_GetItem(modules, parentname);\r
- if (parent == NULL) {\r
- PyErr_Format(PyExc_ImportError,\r
- "reload(): parent %.200s not in sys.modules",\r
- PyString_AS_STRING(parentname));\r
- Py_DECREF(parentname);\r
- imp_modules_reloading_clear();\r
- return NULL;\r
- }\r
- Py_DECREF(parentname);\r
- subname++;\r
- path = PyObject_GetAttrString(parent, "__path__");\r
- if (path == NULL)\r
- PyErr_Clear();\r
- }\r
- buf = PyMem_MALLOC(MAXPATHLEN+1);\r
- if (buf == NULL) {\r
- Py_XDECREF(path);\r
- return PyErr_NoMemory();\r
- }\r
- buf[0] = '\0';\r
- fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);\r
- Py_XDECREF(path);\r
-\r
- if (fdp == NULL) {\r
- Py_XDECREF(loader);\r
- imp_modules_reloading_clear();\r
- PyMem_FREE(buf);\r
- return NULL;\r
- }\r
-\r
- newm = load_module(name, fp, buf, fdp->type, loader);\r
- Py_XDECREF(loader);\r
-\r
- if (fp)\r
- fclose(fp);\r
- if (newm == NULL) {\r
- /* load_module probably removed name from modules because of\r
- * the error. Put back the original module object. We're\r
- * going to return NULL in this case regardless of whether\r
- * replacing name succeeds, so the return value is ignored.\r
- */\r
- PyDict_SetItemString(modules, name, m);\r
- }\r
- imp_modules_reloading_clear();\r
- PyMem_FREE(buf);\r
- return newm;\r
-}\r
-\r
-\r
-/* Higher-level import emulator which emulates the "import" statement\r
- more accurately -- it invokes the __import__() function from the\r
- builtins of the current globals. This means that the import is\r
- done using whatever import hooks are installed in the current\r
- environment, e.g. by "rexec".\r
- A dummy list ["__doc__"] is passed as the 4th argument so that\r
- e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))\r
- will return <module "gencache"> instead of <module "win32com">. */\r
-\r
-PyObject *\r
-PyImport_Import(PyObject *module_name)\r
-{\r
- static PyObject *silly_list = NULL;\r
- static PyObject *builtins_str = NULL;\r
- static PyObject *import_str = NULL;\r
- PyObject *globals = NULL;\r
- PyObject *import = NULL;\r
- PyObject *builtins = NULL;\r
- PyObject *r = NULL;\r
-\r
- /* Initialize constant string objects */\r
- if (silly_list == NULL) {\r
- import_str = PyString_InternFromString("__import__");\r
- if (import_str == NULL)\r
- return NULL;\r
- builtins_str = PyString_InternFromString("__builtins__");\r
- if (builtins_str == NULL)\r
- return NULL;\r
- silly_list = Py_BuildValue("[s]", "__doc__");\r
- if (silly_list == NULL)\r
- return NULL;\r
- }\r
-\r
- /* Get the builtins from current globals */\r
- globals = PyEval_GetGlobals();\r
- if (globals != NULL) {\r
- Py_INCREF(globals);\r
- builtins = PyObject_GetItem(globals, builtins_str);\r
- if (builtins == NULL)\r
- goto err;\r
- }\r
- else {\r
- /* No globals -- use standard builtins, and fake globals */\r
- builtins = PyImport_ImportModuleLevel("__builtin__",\r
- NULL, NULL, NULL, 0);\r
- if (builtins == NULL)\r
- return NULL;\r
- globals = Py_BuildValue("{OO}", builtins_str, builtins);\r
- if (globals == NULL)\r
- goto err;\r
- }\r
-\r
- /* Get the __import__ function from the builtins */\r
- if (PyDict_Check(builtins)) {\r
- import = PyObject_GetItem(builtins, import_str);\r
- if (import == NULL)\r
- PyErr_SetObject(PyExc_KeyError, import_str);\r
- }\r
- else\r
- import = PyObject_GetAttr(builtins, import_str);\r
- if (import == NULL)\r
- goto err;\r
-\r
- /* Call the __import__ function with the proper argument list\r
- * Always use absolute import here. */\r
- r = PyObject_CallFunction(import, "OOOOi", module_name, globals,\r
- globals, silly_list, 0, NULL);\r
-\r
- err:\r
- Py_XDECREF(globals);\r
- Py_XDECREF(builtins);\r
- Py_XDECREF(import);\r
-\r
- return r;\r
-}\r
-\r
-\r
-/* Module 'imp' provides Python access to the primitives used for\r
- importing modules.\r
-*/\r
-\r
-static PyObject *\r
-imp_get_magic(PyObject *self, PyObject *noargs)\r
-{\r
- char buf[4];\r
-\r
- buf[0] = (char) ((pyc_magic >> 0) & 0xff);\r
- buf[1] = (char) ((pyc_magic >> 8) & 0xff);\r
- buf[2] = (char) ((pyc_magic >> 16) & 0xff);\r
- buf[3] = (char) ((pyc_magic >> 24) & 0xff);\r
-\r
- return PyString_FromStringAndSize(buf, 4);\r
-}\r
-\r
-static PyObject *\r
-imp_get_suffixes(PyObject *self, PyObject *noargs)\r
-{\r
- PyObject *list;\r
- struct filedescr *fdp;\r
-\r
- list = PyList_New(0);\r
- if (list == NULL)\r
- return NULL;\r
- for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {\r
- PyObject *item = Py_BuildValue("ssi",\r
- fdp->suffix, fdp->mode, fdp->type);\r
- if (item == NULL) {\r
- Py_DECREF(list);\r
- return NULL;\r
- }\r
- if (PyList_Append(list, item) < 0) {\r
- Py_DECREF(list);\r
- Py_DECREF(item);\r
- return NULL;\r
- }\r
- Py_DECREF(item);\r
- }\r
- return list;\r
-}\r
-\r
-static PyObject *\r
-call_find_module(char *name, PyObject *path)\r
-{\r
- extern int fclose(FILE *);\r
- PyObject *fob, *ret;\r
- struct filedescr *fdp;\r
- char *pathname;\r
- FILE *fp = NULL;\r
-\r
- pathname = PyMem_MALLOC(MAXPATHLEN+1);\r
- if (pathname == NULL) {\r
- return PyErr_NoMemory();\r
- }\r
- pathname[0] = '\0';\r
- if (path == Py_None)\r
- path = NULL;\r
- fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);\r
- if (fdp == NULL) {\r
- PyMem_FREE(pathname);\r
- return NULL;\r
- }\r
- if (fp != NULL) {\r
- fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);\r
- if (fob == NULL) {\r
- PyMem_FREE(pathname);\r
- return NULL;\r
- }\r
- }\r
- else {\r
- fob = Py_None;\r
- Py_INCREF(fob);\r
- }\r
- ret = Py_BuildValue("Os(ssi)",\r
- fob, pathname, fdp->suffix, fdp->mode, fdp->type);\r
- Py_DECREF(fob);\r
- PyMem_FREE(pathname);\r
- return ret;\r
-}\r
-\r
-static PyObject *\r
-imp_find_module(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- PyObject *path = NULL;\r
- if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))\r
- return NULL;\r
- return call_find_module(name, path);\r
-}\r
-\r
-static PyObject *\r
-imp_init_builtin(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- int ret;\r
- PyObject *m;\r
- if (!PyArg_ParseTuple(args, "s:init_builtin", &name))\r
- return NULL;\r
- ret = init_builtin(name);\r
- if (ret < 0)\r
- return NULL;\r
- if (ret == 0) {\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
- }\r
- m = PyImport_AddModule(name);\r
- Py_XINCREF(m);\r
- return m;\r
-}\r
-\r
-static PyObject *\r
-imp_init_frozen(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- int ret;\r
- PyObject *m;\r
- if (!PyArg_ParseTuple(args, "s:init_frozen", &name))\r
- return NULL;\r
- ret = PyImport_ImportFrozenModule(name);\r
- if (ret < 0)\r
- return NULL;\r
- if (ret == 0) {\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
- }\r
- m = PyImport_AddModule(name);\r
- Py_XINCREF(m);\r
- return m;\r
-}\r
-\r
-static PyObject *\r
-imp_get_frozen_object(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
-\r
- if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))\r
- return NULL;\r
- return get_frozen_object(name);\r
-}\r
-\r
-static PyObject *\r
-imp_is_builtin(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- if (!PyArg_ParseTuple(args, "s:is_builtin", &name))\r
- return NULL;\r
- return PyInt_FromLong(is_builtin(name));\r
-}\r
-\r
-static PyObject *\r
-imp_is_frozen(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- struct _frozen *p;\r
- if (!PyArg_ParseTuple(args, "s:is_frozen", &name))\r
- return NULL;\r
- p = find_frozen(name);\r
- return PyBool_FromLong((long) (p == NULL ? 0 : p->size));\r
-}\r
-\r
-static FILE *\r
-get_file(char *pathname, PyObject *fob, char *mode)\r
-{\r
- FILE *fp;\r
- if (fob == NULL) {\r
- if (mode[0] == 'U')\r
- mode = "r" PY_STDIOTEXTMODE;\r
- fp = fopen(pathname, mode);\r
- if (fp == NULL)\r
- PyErr_SetFromErrno(PyExc_IOError);\r
- }\r
- else {\r
- fp = PyFile_AsFile(fob);\r
- if (fp == NULL)\r
- PyErr_SetString(PyExc_ValueError,\r
- "bad/closed file object");\r
- }\r
- return fp;\r
-}\r
-\r
-static PyObject *\r
-imp_load_compiled(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- char *pathname;\r
- PyObject *fob = NULL;\r
- PyObject *m;\r
- FILE *fp;\r
- if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,\r
- &PyFile_Type, &fob))\r
- return NULL;\r
- fp = get_file(pathname, fob, "rb");\r
- if (fp == NULL)\r
- return NULL;\r
- m = load_compiled_module(name, pathname, fp);\r
- if (fob == NULL)\r
- fclose(fp);\r
- return m;\r
-}\r
-\r
-#ifdef HAVE_DYNAMIC_LOADING\r
-\r
-static PyObject *\r
-imp_load_dynamic(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- char *pathname;\r
- PyObject *fob = NULL;\r
- PyObject *m;\r
- FILE *fp = NULL;\r
- if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,\r
- &PyFile_Type, &fob))\r
- return NULL;\r
- if (fob) {\r
- fp = get_file(pathname, fob, "r");\r
- if (fp == NULL)\r
- return NULL;\r
- }\r
- m = _PyImport_LoadDynamicModule(name, pathname, fp);\r
- return m;\r
-}\r
-\r
-#endif /* HAVE_DYNAMIC_LOADING */\r
-\r
-static PyObject *\r
-imp_load_source(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- char *pathname;\r
- PyObject *fob = NULL;\r
- PyObject *m;\r
- FILE *fp;\r
- if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,\r
- &PyFile_Type, &fob))\r
- return NULL;\r
- fp = get_file(pathname, fob, "r");\r
- if (fp == NULL)\r
- return NULL;\r
- m = load_source_module(name, pathname, fp);\r
- if (fob == NULL)\r
- fclose(fp);\r
- return m;\r
-}\r
-\r
-static PyObject *\r
-imp_load_module(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- PyObject *fob;\r
- char *pathname;\r
- char *suffix; /* Unused */\r
- char *mode;\r
- int type;\r
- FILE *fp;\r
-\r
- if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",\r
- &name, &fob, &pathname,\r
- &suffix, &mode, &type))\r
- return NULL;\r
- if (*mode) {\r
- /* Mode must start with 'r' or 'U' and must not contain '+'.\r
- Implicit in this test is the assumption that the mode\r
- may contain other modifiers like 'b' or 't'. */\r
-\r
- if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {\r
- PyErr_Format(PyExc_ValueError,\r
- "invalid file open mode %.200s", mode);\r
- return NULL;\r
- }\r
- }\r
- if (fob == Py_None)\r
- fp = NULL;\r
- else {\r
- if (!PyFile_Check(fob)) {\r
- PyErr_SetString(PyExc_ValueError,\r
- "load_module arg#2 should be a file or None");\r
- return NULL;\r
- }\r
- fp = get_file(pathname, fob, mode);\r
- if (fp == NULL)\r
- return NULL;\r
- }\r
- return load_module(name, fp, pathname, type, NULL);\r
-}\r
-\r
-static PyObject *\r
-imp_load_package(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- char *pathname;\r
- if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))\r
- return NULL;\r
- return load_package(name, pathname);\r
-}\r
-\r
-static PyObject *\r
-imp_new_module(PyObject *self, PyObject *args)\r
-{\r
- char *name;\r
- if (!PyArg_ParseTuple(args, "s:new_module", &name))\r
- return NULL;\r
- return PyModule_New(name);\r
-}\r
-\r
-static PyObject *\r
-imp_reload(PyObject *self, PyObject *v)\r
-{\r
- return PyImport_ReloadModule(v);\r
-}\r
-\r
-\r
-/* Doc strings */\r
-\r
-PyDoc_STRVAR(doc_imp,\r
-"This module provides the components needed to build your own\n\\r
-__import__ function. Undocumented functions are obsolete.");\r
-\r
-PyDoc_STRVAR(doc_reload,\r
-"reload(module) -> module\n\\r
-\n\\r
-Reload the module. The module must have been successfully imported before.");\r
-\r
-PyDoc_STRVAR(doc_find_module,\r
-"find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\\r
-Search for a module. If path is omitted or None, search for a\n\\r
-built-in, frozen or special module and continue search in sys.path.\n\\r
-The module name cannot contain '.'; to search for a submodule of a\n\\r
-package, pass the submodule name and the package's __path__.");\r
-\r
-PyDoc_STRVAR(doc_load_module,\r
-"load_module(name, file, filename, (suffix, mode, type)) -> module\n\\r
-Load a module, given information returned by find_module().\n\\r
-The module name must include the full package name, if any.");\r
-\r
-PyDoc_STRVAR(doc_get_magic,\r
-"get_magic() -> string\n\\r
-Return the magic number for .pyc or .pyo files.");\r
-\r
-PyDoc_STRVAR(doc_get_suffixes,\r
-"get_suffixes() -> [(suffix, mode, type), ...]\n\\r
-Return a list of (suffix, mode, type) tuples describing the files\n\\r
-that find_module() looks for.");\r
-\r
-PyDoc_STRVAR(doc_new_module,\r
-"new_module(name) -> module\n\\r
-Create a new module. Do not enter it in sys.modules.\n\\r
-The module name must include the full package name, if any.");\r
-\r
-PyDoc_STRVAR(doc_lock_held,\r
-"lock_held() -> boolean\n\\r
-Return True if the import lock is currently held, else False.\n\\r
-On platforms without threads, return False.");\r
-\r
-PyDoc_STRVAR(doc_acquire_lock,\r
-"acquire_lock() -> None\n\\r
-Acquires the interpreter's import lock for the current thread.\n\\r
-This lock should be used by import hooks to ensure thread-safety\n\\r
-when importing modules.\n\\r
-On platforms without threads, this function does nothing.");\r
-\r
-PyDoc_STRVAR(doc_release_lock,\r
-"release_lock() -> None\n\\r
-Release the interpreter's import lock.\n\\r
-On platforms without threads, this function does nothing.");\r
-\r
-static PyMethodDef imp_methods[] = {\r
- {"reload", imp_reload, METH_O, doc_reload},\r
- {"find_module", imp_find_module, METH_VARARGS, doc_find_module},\r
- {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},\r
- {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},\r
- {"load_module", imp_load_module, METH_VARARGS, doc_load_module},\r
- {"new_module", imp_new_module, METH_VARARGS, doc_new_module},\r
- {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},\r
- {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},\r
- {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},\r
- /* The rest are obsolete */\r
- {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},\r
- {"init_builtin", imp_init_builtin, METH_VARARGS},\r
- {"init_frozen", imp_init_frozen, METH_VARARGS},\r
- {"is_builtin", imp_is_builtin, METH_VARARGS},\r
- {"is_frozen", imp_is_frozen, METH_VARARGS},\r
- {"load_compiled", imp_load_compiled, METH_VARARGS},\r
-#ifdef HAVE_DYNAMIC_LOADING\r
- {"load_dynamic", imp_load_dynamic, METH_VARARGS},\r
-#endif\r
- {"load_package", imp_load_package, METH_VARARGS},\r
- {"load_source", imp_load_source, METH_VARARGS},\r
- {NULL, NULL} /* sentinel */\r
-};\r
-\r
-static int\r
-setint(PyObject *d, char *name, int value)\r
-{\r
- PyObject *v;\r
- int err;\r
-\r
- v = PyInt_FromLong((long)value);\r
- err = PyDict_SetItemString(d, name, v);\r
- Py_XDECREF(v);\r
- return err;\r
-}\r
-\r
-typedef struct {\r
- PyObject_HEAD\r
-} NullImporter;\r
-\r
-static int\r
-NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)\r
-{\r
- char *path;\r
- Py_ssize_t pathlen;\r
-\r
- if (!_PyArg_NoKeywords("NullImporter()", kwds))\r
- return -1;\r
-\r
- if (!PyArg_ParseTuple(args, "s:NullImporter",\r
- &path))\r
- return -1;\r
-\r
- pathlen = strlen(path);\r
- if (pathlen == 0) {\r
- PyErr_SetString(PyExc_ImportError, "empty pathname");\r
- return -1;\r
- } else {\r
- if(isdir(path)) {\r
- PyErr_SetString(PyExc_ImportError,\r
- "existing directory");\r
- return -1;\r
- }\r
- }\r
- return 0;\r
-}\r
-\r
-static PyObject *\r
-NullImporter_find_module(NullImporter *self, PyObject *args)\r
-{\r
- Py_RETURN_NONE;\r
-}\r
-\r
-static PyMethodDef NullImporter_methods[] = {\r
- {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,\r
- "Always return None"\r
- },\r
- {NULL} /* Sentinel */\r
-};\r
-\r
-\r
-PyTypeObject PyNullImporter_Type = {\r
- PyVarObject_HEAD_INIT(NULL, 0)\r
- "imp.NullImporter", /*tp_name*/\r
- sizeof(NullImporter), /*tp_basicsize*/\r
- 0, /*tp_itemsize*/\r
- 0, /*tp_dealloc*/\r
- 0, /*tp_print*/\r
- 0, /*tp_getattr*/\r
- 0, /*tp_setattr*/\r
- 0, /*tp_compare*/\r
- 0, /*tp_repr*/\r
- 0, /*tp_as_number*/\r
- 0, /*tp_as_sequence*/\r
- 0, /*tp_as_mapping*/\r
- 0, /*tp_hash */\r
- 0, /*tp_call*/\r
- 0, /*tp_str*/\r
- 0, /*tp_getattro*/\r
- 0, /*tp_setattro*/\r
- 0, /*tp_as_buffer*/\r
- Py_TPFLAGS_DEFAULT, /*tp_flags*/\r
- "Null importer object", /* tp_doc */\r
- 0, /* tp_traverse */\r
- 0, /* tp_clear */\r
- 0, /* tp_richcompare */\r
- 0, /* tp_weaklistoffset */\r
- 0, /* tp_iter */\r
- 0, /* tp_iternext */\r
- NullImporter_methods, /* tp_methods */\r
- 0, /* tp_members */\r
- 0, /* tp_getset */\r
- 0, /* tp_base */\r
- 0, /* tp_dict */\r
- 0, /* tp_descr_get */\r
- 0, /* tp_descr_set */\r
- 0, /* tp_dictoffset */\r
- (initproc)NullImporter_init, /* tp_init */\r
- 0, /* tp_alloc */\r
- PyType_GenericNew /* tp_new */\r
-};\r
-\r
-\r
-PyMODINIT_FUNC\r
-initimp(void)\r
-{\r
- PyObject *m, *d;\r
-\r
- if (PyType_Ready(&PyNullImporter_Type) < 0)\r
- goto failure;\r
-\r
- m = Py_InitModule4("imp", imp_methods, doc_imp,\r
- NULL, PYTHON_API_VERSION);\r
- if (m == NULL)\r
- goto failure;\r
- d = PyModule_GetDict(m);\r
- if (d == NULL)\r
- goto failure;\r
-\r
- if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;\r
- if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;\r
- if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;\r
- if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;\r
- if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;\r
- if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;\r
- if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;\r
- if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;\r
- if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;\r
- if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;\r
-\r
- Py_INCREF(&PyNullImporter_Type);\r
- PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);\r
- failure:\r
- ;\r
-}\r
-\r
-\r
-/* API for embedding applications that want to add their own entries\r
- to the table of built-in modules. This should normally be called\r
- *before* Py_Initialize(). When the table resize fails, -1 is\r
- returned and the existing table is unchanged.\r
-\r
- After a similar function by Just van Rossum. */\r
-\r
-int\r
-PyImport_ExtendInittab(struct _inittab *newtab)\r
-{\r
- static struct _inittab *our_copy = NULL;\r
- struct _inittab *p;\r
- int i, n;\r
-\r
- /* Count the number of entries in both tables */\r
- for (n = 0; newtab[n].name != NULL; n++)\r
- ;\r
- if (n == 0)\r
- return 0; /* Nothing to do */\r
- for (i = 0; PyImport_Inittab[i].name != NULL; i++)\r
- ;\r
-\r
- /* Allocate new memory for the combined table */\r
- p = our_copy;\r
- PyMem_RESIZE(p, struct _inittab, i+n+1);\r
- if (p == NULL)\r
- return -1;\r
-\r
- /* Copy the tables into the new memory */\r
- if (our_copy != PyImport_Inittab)\r
- memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));\r
- PyImport_Inittab = our_copy = p;\r
- memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));\r
-\r
- return 0;\r
-}\r
-\r
-/* Shorthand to add a single entry given a name and a function */\r
-\r
-int\r
-PyImport_AppendInittab(const char *name, void (*initfunc)(void))\r
-{\r
- struct _inittab newtab[2];\r
-\r
- memset(newtab, '\0', sizeof newtab);\r
-\r
- newtab[0].name = (char *)name;\r
- newtab[0].initfunc = initfunc;\r
-\r
- return PyImport_ExtendInittab(newtab);\r
-}\r
-\r
-#ifdef __cplusplus\r
-}\r
-#endif\r