You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3422 lines
98 KiB

36 years ago
36 years ago
36 years ago
16 years ago
14 years ago
14 years ago
14 years ago
36 years ago
36 years ago
36 years ago
36 years ago
16 years ago
36 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
36 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
36 years ago
36 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
14 years ago
First part of package support. This doesn't yet support "import a.b.c" or "from a.b.c import x", but it does recognize directories. When importing a directory, it initializes __path__ to a list containing the directory name, and loads the __init__ module if found. The (internal) find_module() and load_module() functions are restructured so that they both also handle built-in and frozen modules and Mac resources (and directories of course). The imp module's find_module() and (new) load_module() also have this functionality. Moreover, imp unconditionally defines constants for all module types, and has two more new functions: find_module_in_package() and find_module_in_directory(). There's also a new API function, PyImport_ImportModuleEx(), which takes all four __import__ arguments (name, globals, locals, fromlist). The last three may be NULL. This is currently the same as PyImport_ImportModule() but in the future it will be able to do relative dotted-path imports. Other changes: - bltinmodule.c: in __import__, call PyImport_ImportModuleEx(). - ceval.c: always pass the fromlist to __import__, even if it is a C function, so PyImport_ImportModuleEx() is useful. - getmtime.c: the function has a second argument, the FILE*, on which it applies fstat(). According to Sjoerd this is much faster. The first (pathname) argument is ignored, but remains for backward compatibility (so the Mac version still works without changes). By cleverly combining the new imp functionality, the full support for dotted names in Python (mini.py, not checked in) is now about 7K, lavishly commented (vs. 14K for ni plus 11K for ihooks, also lavishly commented). Good night!
29 years ago
  1. /* Module definition and import implementation */
  2. #include "Python.h"
  3. #include "Python-ast.h"
  4. #undef Yield /* undefine macro conflicting with winbase.h */
  5. #include "pyarena.h"
  6. #include "pythonrun.h"
  7. #include "errcode.h"
  8. #include "marshal.h"
  9. #include "code.h"
  10. #include "compile.h"
  11. #include "eval.h"
  12. #include "osdefs.h"
  13. #include "importdl.h"
  14. #ifdef HAVE_FCNTL_H
  15. #include <fcntl.h>
  16. #endif
  17. #ifdef __cplusplus
  18. extern "C" {
  19. #endif
  20. #ifdef MS_WINDOWS
  21. /* for stat.st_mode */
  22. typedef unsigned short mode_t;
  23. #endif
  24. /* Magic word to reject .pyc files generated by other Python versions.
  25. It should change for each incompatible change to the bytecode.
  26. The value of CR and LF is incorporated so if you ever read or write
  27. a .pyc file in text mode the magic number will be wrong; also, the
  28. Apple MPW compiler swaps their values, botching string constants.
  29. The magic numbers must be spaced apart atleast 2 values, as the
  30. -U interpeter flag will cause MAGIC+1 being used. They have been
  31. odd numbers for some time now.
  32. There were a variety of old schemes for setting the magic number.
  33. The current working scheme is to increment the previous value by
  34. 10.
  35. Known values:
  36. Python 1.5: 20121
  37. Python 1.5.1: 20121
  38. Python 1.5.2: 20121
  39. Python 1.6: 50428
  40. Python 2.0: 50823
  41. Python 2.0.1: 50823
  42. Python 2.1: 60202
  43. Python 2.1.1: 60202
  44. Python 2.1.2: 60202
  45. Python 2.2: 60717
  46. Python 2.3a0: 62011
  47. Python 2.3a0: 62021
  48. Python 2.3a0: 62011 (!)
  49. Python 2.4a0: 62041
  50. Python 2.4a3: 62051
  51. Python 2.4b1: 62061
  52. Python 2.5a0: 62071
  53. Python 2.5a0: 62081 (ast-branch)
  54. Python 2.5a0: 62091 (with)
  55. Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
  56. Python 2.5b3: 62101 (fix wrong code: for x, in ...)
  57. Python 2.5b3: 62111 (fix wrong code: x += yield)
  58. Python 2.5c1: 62121 (fix wrong lnotab with for loops and
  59. storing constants that should have been removed)
  60. Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
  61. Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
  62. Python 2.6a1: 62161 (WITH_CLEANUP optimization)
  63. Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
  64. Python 2.7a0: 62181 (optimize conditional branches:
  65. introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
  66. Python 2.7a0 62191 (introduce SETUP_WITH)
  67. Python 2.7a0 62201 (introduce BUILD_SET)
  68. Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD)
  69. .
  70. */
  71. #define MAGIC (62211 | ((long)'\r'<<16) | ((long)'\n'<<24))
  72. /* Magic word as global; note that _PyImport_Init() can change the
  73. value of this global to accommodate for alterations of how the
  74. compiler works which are enabled by command line switches. */
  75. static long pyc_magic = MAGIC;
  76. /* See _PyImport_FixupExtension() below */
  77. static PyObject *extensions = NULL;
  78. /* This table is defined in config.c: */
  79. extern struct _inittab _PyImport_Inittab[];
  80. struct _inittab *PyImport_Inittab = _PyImport_Inittab;
  81. /* these tables define the module suffixes that Python recognizes */
  82. struct filedescr * _PyImport_Filetab = NULL;
  83. #ifdef RISCOS
  84. static const struct filedescr _PyImport_StandardFiletab[] = {
  85. {"/py", "U", PY_SOURCE},
  86. {"/pyc", "rb", PY_COMPILED},
  87. {0, 0}
  88. };
  89. #else
  90. static const struct filedescr _PyImport_StandardFiletab[] = {
  91. {".py", "U", PY_SOURCE},
  92. #ifdef MS_WINDOWS
  93. {".pyw", "U", PY_SOURCE},
  94. #endif
  95. {".pyc", "rb", PY_COMPILED},
  96. {0, 0}
  97. };
  98. #endif
  99. #ifdef MS_WINDOWS
  100. int isdir(char *path) {
  101. DWORD rv;
  102. /* see issue1293 and issue3677:
  103. * stat() on Windows doesn't recognise paths like
  104. * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
  105. * Also reference issue6727:
  106. * stat() on Windows is broken and doesn't resolve symlinks properly.
  107. */
  108. rv = GetFileAttributesA(path);
  109. return rv != INVALID_FILE_ATTRIBUTES && rv & FILE_ATTRIBUTE_DIRECTORY;
  110. }
  111. #else
  112. #ifdef HAVE_STAT
  113. int isdir(char *path) {
  114. struct stat statbuf;
  115. return stat(path, &statbuf) == 0 && S_ISDIR(statbuf.st_mode);
  116. }
  117. #else
  118. #ifdef RISCOS
  119. /* with RISCOS, isdir is in unixstuff */
  120. #else
  121. int isdir(char *path) {
  122. return 0;
  123. }
  124. #endif /* RISCOS */
  125. #endif /* HAVE_STAT */
  126. #endif /* MS_WINDOWS */
  127. /* Initialize things */
  128. void
  129. _PyImport_Init(void)
  130. {
  131. const struct filedescr *scan;
  132. struct filedescr *filetab;
  133. int countD = 0;
  134. int countS = 0;
  135. /* prepare _PyImport_Filetab: copy entries from
  136. _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
  137. */
  138. #ifdef HAVE_DYNAMIC_LOADING
  139. for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
  140. ++countD;
  141. #endif
  142. for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
  143. ++countS;
  144. filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
  145. if (filetab == NULL)
  146. Py_FatalError("Can't initialize import file table.");
  147. #ifdef HAVE_DYNAMIC_LOADING
  148. memcpy(filetab, _PyImport_DynLoadFiletab,
  149. countD * sizeof(struct filedescr));
  150. #endif
  151. memcpy(filetab + countD, _PyImport_StandardFiletab,
  152. countS * sizeof(struct filedescr));
  153. filetab[countD + countS].suffix = NULL;
  154. _PyImport_Filetab = filetab;
  155. if (Py_OptimizeFlag) {
  156. /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
  157. for (; filetab->suffix != NULL; filetab++) {
  158. #ifndef RISCOS
  159. if (strcmp(filetab->suffix, ".pyc") == 0)
  160. filetab->suffix = ".pyo";
  161. #else
  162. if (strcmp(filetab->suffix, "/pyc") == 0)
  163. filetab->suffix = "/pyo";
  164. #endif
  165. }
  166. }
  167. if (Py_UnicodeFlag) {
  168. /* Fix the pyc_magic so that byte compiled code created
  169. using the all-Unicode method doesn't interfere with
  170. code created in normal operation mode. */
  171. pyc_magic = MAGIC + 1;
  172. }
  173. }
  174. void
  175. _PyImportHooks_Init(void)
  176. {
  177. PyObject *v, *path_hooks = NULL, *zimpimport;
  178. int err = 0;
  179. /* adding sys.path_hooks and sys.path_importer_cache, setting up
  180. zipimport */
  181. if (PyType_Ready(&PyNullImporter_Type) < 0)
  182. goto error;
  183. if (Py_VerboseFlag)
  184. PySys_WriteStderr("# installing zipimport hook\n");
  185. v = PyList_New(0);
  186. if (v == NULL)
  187. goto error;
  188. err = PySys_SetObject("meta_path", v);
  189. Py_DECREF(v);
  190. if (err)
  191. goto error;
  192. v = PyDict_New();
  193. if (v == NULL)
  194. goto error;
  195. err = PySys_SetObject("path_importer_cache", v);
  196. Py_DECREF(v);
  197. if (err)
  198. goto error;
  199. path_hooks = PyList_New(0);
  200. if (path_hooks == NULL)
  201. goto error;
  202. err = PySys_SetObject("path_hooks", path_hooks);
  203. if (err) {
  204. error:
  205. PyErr_Print();
  206. Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
  207. "path_importer_cache, or NullImporter failed"
  208. );
  209. }
  210. zimpimport = PyImport_ImportModule("zipimport");
  211. if (zimpimport == NULL) {
  212. PyErr_Clear(); /* No zip import module -- okay */
  213. if (Py_VerboseFlag)
  214. PySys_WriteStderr("# can't import zipimport\n");
  215. }
  216. else {
  217. PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
  218. "zipimporter");
  219. Py_DECREF(zimpimport);
  220. if (zipimporter == NULL) {
  221. PyErr_Clear(); /* No zipimporter object -- okay */
  222. if (Py_VerboseFlag)
  223. PySys_WriteStderr(
  224. "# can't import zipimport.zipimporter\n");
  225. }
  226. else {
  227. /* sys.path_hooks.append(zipimporter) */
  228. err = PyList_Append(path_hooks, zipimporter);
  229. Py_DECREF(zipimporter);
  230. if (err)
  231. goto error;
  232. if (Py_VerboseFlag)
  233. PySys_WriteStderr(
  234. "# installed zipimport hook\n");
  235. }
  236. }
  237. Py_DECREF(path_hooks);
  238. }
  239. void
  240. _PyImport_Fini(void)
  241. {
  242. Py_XDECREF(extensions);
  243. extensions = NULL;
  244. PyMem_DEL(_PyImport_Filetab);
  245. _PyImport_Filetab = NULL;
  246. }
  247. /* Locking primitives to prevent parallel imports of the same module
  248. in different threads to return with a partially loaded module.
  249. These calls are serialized by the global interpreter lock. */
  250. #ifdef WITH_THREAD
  251. #include "pythread.h"
  252. static PyThread_type_lock import_lock = 0;
  253. static long import_lock_thread = -1;
  254. static int import_lock_level = 0;
  255. void
  256. _PyImport_AcquireLock(void)
  257. {
  258. long me = PyThread_get_thread_ident();
  259. if (me == -1)
  260. return; /* Too bad */
  261. if (import_lock == NULL) {
  262. import_lock = PyThread_allocate_lock();
  263. if (import_lock == NULL)
  264. return; /* Nothing much we can do. */
  265. }
  266. if (import_lock_thread == me) {
  267. import_lock_level++;
  268. return;
  269. }
  270. if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
  271. {
  272. PyThreadState *tstate = PyEval_SaveThread();
  273. PyThread_acquire_lock(import_lock, 1);
  274. PyEval_RestoreThread(tstate);
  275. }
  276. import_lock_thread = me;
  277. import_lock_level = 1;
  278. }
  279. int
  280. _PyImport_ReleaseLock(void)
  281. {
  282. long me = PyThread_get_thread_ident();
  283. if (me == -1 || import_lock == NULL)
  284. return 0; /* Too bad */
  285. if (import_lock_thread != me)
  286. return -1;
  287. import_lock_level--;
  288. if (import_lock_level == 0) {
  289. import_lock_thread = -1;
  290. PyThread_release_lock(import_lock);
  291. }
  292. return 1;
  293. }
  294. /* This function is called from PyOS_AfterFork to ensure that newly
  295. created child processes do not share locks with the parent.
  296. We now acquire the import lock around fork() calls but on some platforms
  297. (Solaris 9 and earlier? see isue7242) that still left us with problems. */
  298. void
  299. _PyImport_ReInitLock(void)
  300. {
  301. if (import_lock != NULL)
  302. import_lock = PyThread_allocate_lock();
  303. import_lock_thread = -1;
  304. import_lock_level = 0;
  305. }
  306. #endif
  307. static PyObject *
  308. imp_lock_held(PyObject *self, PyObject *noargs)
  309. {
  310. #ifdef WITH_THREAD
  311. return PyBool_FromLong(import_lock_thread != -1);
  312. #else
  313. return PyBool_FromLong(0);
  314. #endif
  315. }
  316. static PyObject *
  317. imp_acquire_lock(PyObject *self, PyObject *noargs)
  318. {
  319. #ifdef WITH_THREAD
  320. _PyImport_AcquireLock();
  321. #endif
  322. Py_INCREF(Py_None);
  323. return Py_None;
  324. }
  325. static PyObject *
  326. imp_release_lock(PyObject *self, PyObject *noargs)
  327. {
  328. #ifdef WITH_THREAD
  329. if (_PyImport_ReleaseLock() < 0) {
  330. PyErr_SetString(PyExc_RuntimeError,
  331. "not holding the import lock");
  332. return NULL;
  333. }
  334. #endif
  335. Py_INCREF(Py_None);
  336. return Py_None;
  337. }
  338. static void
  339. imp_modules_reloading_clear(void)
  340. {
  341. PyInterpreterState *interp = PyThreadState_Get()->interp;
  342. if (interp->modules_reloading != NULL)
  343. PyDict_Clear(interp->modules_reloading);
  344. }
  345. /* Helper for sys */
  346. PyObject *
  347. PyImport_GetModuleDict(void)
  348. {
  349. PyInterpreterState *interp = PyThreadState_GET()->interp;
  350. if (interp->modules == NULL)
  351. Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
  352. return interp->modules;
  353. }
  354. /* List of names to clear in sys */
  355. static char* sys_deletes[] = {
  356. "path", "argv", "ps1", "ps2", "exitfunc",
  357. "exc_type", "exc_value", "exc_traceback",
  358. "last_type", "last_value", "last_traceback",
  359. "path_hooks", "path_importer_cache", "meta_path",
  360. /* misc stuff */
  361. "flags", "float_info",
  362. NULL
  363. };
  364. static char* sys_files[] = {
  365. "stdin", "__stdin__",
  366. "stdout", "__stdout__",
  367. "stderr", "__stderr__",
  368. NULL
  369. };
  370. /* Un-initialize things, as good as we can */
  371. void
  372. PyImport_Cleanup(void)
  373. {
  374. Py_ssize_t pos, ndone;
  375. char *name;
  376. PyObject *key, *value, *dict;
  377. PyInterpreterState *interp = PyThreadState_GET()->interp;
  378. PyObject *modules = interp->modules;
  379. if (modules == NULL)
  380. return; /* Already done */
  381. /* Delete some special variables first. These are common
  382. places where user values hide and people complain when their
  383. destructors fail. Since the modules containing them are
  384. deleted *last* of all, they would come too late in the normal
  385. destruction order. Sigh. */
  386. value = PyDict_GetItemString(modules, "__builtin__");
  387. if (value != NULL && PyModule_Check(value)) {
  388. dict = PyModule_GetDict(value);
  389. if (Py_VerboseFlag)
  390. PySys_WriteStderr("# clear __builtin__._\n");
  391. PyDict_SetItemString(dict, "_", Py_None);
  392. }
  393. value = PyDict_GetItemString(modules, "sys");
  394. if (value != NULL && PyModule_Check(value)) {
  395. char **p;
  396. PyObject *v;
  397. dict = PyModule_GetDict(value);
  398. for (p = sys_deletes; *p != NULL; p++) {
  399. if (Py_VerboseFlag)
  400. PySys_WriteStderr("# clear sys.%s\n", *p);
  401. PyDict_SetItemString(dict, *p, Py_None);
  402. }
  403. for (p = sys_files; *p != NULL; p+=2) {
  404. if (Py_VerboseFlag)
  405. PySys_WriteStderr("# restore sys.%s\n", *p);
  406. v = PyDict_GetItemString(dict, *(p+1));
  407. if (v == NULL)
  408. v = Py_None;
  409. PyDict_SetItemString(dict, *p, v);
  410. }
  411. }
  412. /* First, delete __main__ */
  413. value = PyDict_GetItemString(modules, "__main__");
  414. if (value != NULL && PyModule_Check(value)) {
  415. if (Py_VerboseFlag)
  416. PySys_WriteStderr("# cleanup __main__\n");
  417. _PyModule_Clear(value);
  418. PyDict_SetItemString(modules, "__main__", Py_None);
  419. }
  420. /* The special treatment of __builtin__ here is because even
  421. when it's not referenced as a module, its dictionary is
  422. referenced by almost every module's __builtins__. Since
  423. deleting a module clears its dictionary (even if there are
  424. references left to it), we need to delete the __builtin__
  425. module last. Likewise, we don't delete sys until the very
  426. end because it is implicitly referenced (e.g. by print).
  427. Also note that we 'delete' modules by replacing their entry
  428. in the modules dict with None, rather than really deleting
  429. them; this avoids a rehash of the modules dictionary and
  430. also marks them as "non existent" so they won't be
  431. re-imported. */
  432. /* Next, repeatedly delete modules with a reference count of
  433. one (skipping __builtin__ and sys) and delete them */
  434. do {
  435. ndone = 0;
  436. pos = 0;
  437. while (PyDict_Next(modules, &pos, &key, &value)) {
  438. if (value->ob_refcnt != 1)
  439. continue;
  440. if (PyString_Check(key) && PyModule_Check(value)) {
  441. name = PyString_AS_STRING(key);
  442. if (strcmp(name, "__builtin__") == 0)
  443. continue;
  444. if (strcmp(name, "sys") == 0)
  445. continue;
  446. if (Py_VerboseFlag)
  447. PySys_WriteStderr(
  448. "# cleanup[1] %s\n", name);
  449. _PyModule_Clear(value);
  450. PyDict_SetItem(modules, key, Py_None);
  451. ndone++;
  452. }
  453. }
  454. } while (ndone > 0);
  455. /* Next, delete all modules (still skipping __builtin__ and sys) */
  456. pos = 0;
  457. while (PyDict_Next(modules, &pos, &key, &value)) {
  458. if (PyString_Check(key) && PyModule_Check(value)) {
  459. name = PyString_AS_STRING(key);
  460. if (strcmp(name, "__builtin__") == 0)
  461. continue;
  462. if (strcmp(name, "sys") == 0)
  463. continue;
  464. if (Py_VerboseFlag)
  465. PySys_WriteStderr("# cleanup[2] %s\n", name);
  466. _PyModule_Clear(value);
  467. PyDict_SetItem(modules, key, Py_None);
  468. }
  469. }
  470. /* Next, delete sys and __builtin__ (in that order) */
  471. value = PyDict_GetItemString(modules, "sys");
  472. if (value != NULL && PyModule_Check(value)) {
  473. if (Py_VerboseFlag)
  474. PySys_WriteStderr("# cleanup sys\n");
  475. _PyModule_Clear(value);
  476. PyDict_SetItemString(modules, "sys", Py_None);
  477. }
  478. value = PyDict_GetItemString(modules, "__builtin__");
  479. if (value != NULL && PyModule_Check(value)) {
  480. if (Py_VerboseFlag)
  481. PySys_WriteStderr("# cleanup __builtin__\n");
  482. _PyModule_Clear(value);
  483. PyDict_SetItemString(modules, "__builtin__", Py_None);
  484. }
  485. /* Finally, clear and delete the modules directory */
  486. PyDict_Clear(modules);
  487. interp->modules = NULL;
  488. Py_DECREF(modules);
  489. Py_CLEAR(interp->modules_reloading);
  490. }
  491. /* Helper for pythonrun.c -- return magic number */
  492. long
  493. PyImport_GetMagicNumber(void)
  494. {
  495. return pyc_magic;
  496. }
  497. /* Magic for extension modules (built-in as well as dynamically
  498. loaded). To prevent initializing an extension module more than
  499. once, we keep a static dictionary 'extensions' keyed by module name
  500. (for built-in modules) or by filename (for dynamically loaded
  501. modules), containing these modules. A copy of the module's
  502. dictionary is stored by calling _PyImport_FixupExtension()
  503. immediately after the module initialization function succeeds. A
  504. copy can be retrieved from there by calling
  505. _PyImport_FindExtension(). */
  506. PyObject *
  507. _PyImport_FixupExtension(char *name, char *filename)
  508. {
  509. PyObject *modules, *mod, *dict, *copy;
  510. if (extensions == NULL) {
  511. extensions = PyDict_New();
  512. if (extensions == NULL)
  513. return NULL;
  514. }
  515. modules = PyImport_GetModuleDict();
  516. mod = PyDict_GetItemString(modules, name);
  517. if (mod == NULL || !PyModule_Check(mod)) {
  518. PyErr_Format(PyExc_SystemError,
  519. "_PyImport_FixupExtension: module %.200s not loaded", name);
  520. return NULL;
  521. }
  522. dict = PyModule_GetDict(mod);
  523. if (dict == NULL)
  524. return NULL;
  525. copy = PyDict_Copy(dict);
  526. if (copy == NULL)
  527. return NULL;
  528. PyDict_SetItemString(extensions, filename, copy);
  529. Py_DECREF(copy);
  530. return copy;
  531. }
  532. PyObject *
  533. _PyImport_FindExtension(char *name, char *filename)
  534. {
  535. PyObject *dict, *mod, *mdict;
  536. if (extensions == NULL)
  537. return NULL;
  538. dict = PyDict_GetItemString(extensions, filename);
  539. if (dict == NULL)
  540. return NULL;
  541. mod = PyImport_AddModule(name);
  542. if (mod == NULL)
  543. return NULL;
  544. mdict = PyModule_GetDict(mod);
  545. if (mdict == NULL)
  546. return NULL;
  547. if (PyDict_Update(mdict, dict))
  548. return NULL;
  549. if (Py_VerboseFlag)
  550. PySys_WriteStderr("import %s # previously loaded (%s)\n",
  551. name, filename);
  552. return mod;
  553. }
  554. /* Get the module object corresponding to a module name.
  555. First check the modules dictionary if there's one there,
  556. if not, create a new one and insert it in the modules dictionary.
  557. Because the former action is most common, THIS DOES NOT RETURN A
  558. 'NEW' REFERENCE! */
  559. PyObject *
  560. PyImport_AddModule(const char *name)
  561. {
  562. PyObject *modules = PyImport_GetModuleDict();
  563. PyObject *m;
  564. if ((m = PyDict_GetItemString(modules, name)) != NULL &&
  565. PyModule_Check(m))
  566. return m;
  567. m = PyModule_New(name);
  568. if (m == NULL)
  569. return NULL;
  570. if (PyDict_SetItemString(modules, name, m) != 0) {
  571. Py_DECREF(m);
  572. return NULL;
  573. }
  574. Py_DECREF(m); /* Yes, it still exists, in modules! */
  575. return m;
  576. }
  577. /* Remove name from sys.modules, if it's there. */
  578. static void
  579. remove_module(const char *name)
  580. {
  581. PyObject *modules = PyImport_GetModuleDict();
  582. if (PyDict_GetItemString(modules, name) == NULL)
  583. return;
  584. if (PyDict_DelItemString(modules, name) < 0)
  585. Py_FatalError("import: deleting existing key in"
  586. "sys.modules failed");
  587. }
  588. /* Execute a code object in a module and return the module object
  589. * WITH INCREMENTED REFERENCE COUNT. If an error occurs, name is
  590. * removed from sys.modules, to avoid leaving damaged module objects
  591. * in sys.modules. The caller may wish to restore the original
  592. * module object (if any) in this case; PyImport_ReloadModule is an
  593. * example.
  594. */
  595. PyObject *
  596. PyImport_ExecCodeModule(char *name, PyObject *co)
  597. {
  598. return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
  599. }
  600. PyObject *
  601. PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
  602. {
  603. PyObject *modules = PyImport_GetModuleDict();
  604. PyObject *m, *d, *v;
  605. m = PyImport_AddModule(name);
  606. if (m == NULL)
  607. return NULL;
  608. /* If the module is being reloaded, we get the old module back
  609. and re-use its dict to exec the new code. */
  610. d = PyModule_GetDict(m);
  611. if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  612. if (PyDict_SetItemString(d, "__builtins__",
  613. PyEval_GetBuiltins()) != 0)
  614. goto error;
  615. }
  616. /* Remember the filename as the __file__ attribute */
  617. v = NULL;
  618. if (pathname != NULL) {
  619. v = PyString_FromString(pathname);
  620. if (v == NULL)
  621. PyErr_Clear();
  622. }
  623. if (v == NULL) {
  624. v = ((PyCodeObject *)co)->co_filename;
  625. Py_INCREF(v);
  626. }
  627. if (PyDict_SetItemString(d, "__file__", v) != 0)
  628. PyErr_Clear(); /* Not important enough to report */
  629. Py_DECREF(v);
  630. v = PyEval_EvalCode((PyCodeObject *)co, d, d);
  631. if (v == NULL)
  632. goto error;
  633. Py_DECREF(v);
  634. if ((m = PyDict_GetItemString(modules, name)) == NULL) {
  635. PyErr_Format(PyExc_ImportError,
  636. "Loaded module %.200s not found in sys.modules",
  637. name);
  638. return NULL;
  639. }
  640. Py_INCREF(m);
  641. return m;
  642. error:
  643. remove_module(name);
  644. return NULL;
  645. }
  646. /* Given a pathname for a Python source file, fill a buffer with the
  647. pathname for the corresponding compiled file. Return the pathname
  648. for the compiled file, or NULL if there's no space in the buffer.
  649. Doesn't set an exception. */
  650. static char *
  651. make_compiled_pathname(char *pathname, char *buf, size_t buflen)
  652. {
  653. size_t len = strlen(pathname);
  654. if (len+2 > buflen)
  655. return NULL;
  656. #ifdef MS_WINDOWS
  657. /* Treat .pyw as if it were .py. The case of ".pyw" must match
  658. that used in _PyImport_StandardFiletab. */
  659. if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
  660. --len; /* pretend 'w' isn't there */
  661. #endif
  662. memcpy(buf, pathname, len);
  663. buf[len] = Py_OptimizeFlag ? 'o' : 'c';
  664. buf[len+1] = '\0';
  665. return buf;
  666. }
  667. /* Given a pathname for a Python source file, its time of last
  668. modification, and a pathname for a compiled file, check whether the
  669. compiled file represents the same version of the source. If so,
  670. return a FILE pointer for the compiled file, positioned just after
  671. the header; if not, return NULL.
  672. Doesn't set an exception. */
  673. static FILE *
  674. check_compiled_module(char *pathname, time_t mtime, char *cpathname)
  675. {
  676. FILE *fp;
  677. long magic;
  678. long pyc_mtime;
  679. fp = fopen(cpathname, "rb");
  680. if (fp == NULL)
  681. return NULL;
  682. magic = PyMarshal_ReadLongFromFile(fp);
  683. if (magic != pyc_magic) {
  684. if (Py_VerboseFlag)
  685. PySys_WriteStderr("# %s has bad magic\n", cpathname);
  686. fclose(fp);
  687. return NULL;
  688. }
  689. pyc_mtime = PyMarshal_ReadLongFromFile(fp);
  690. if (pyc_mtime != mtime) {
  691. if (Py_VerboseFlag)
  692. PySys_WriteStderr("# %s has bad mtime\n", cpathname);
  693. fclose(fp);
  694. return NULL;
  695. }
  696. if (Py_VerboseFlag)
  697. PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
  698. return fp;
  699. }
  700. /* Read a code object from a file and check it for validity */
  701. static PyCodeObject *
  702. read_compiled_module(char *cpathname, FILE *fp)
  703. {
  704. PyObject *co;
  705. co = PyMarshal_ReadLastObjectFromFile(fp);
  706. if (co == NULL)
  707. return NULL;
  708. if (!PyCode_Check(co)) {
  709. PyErr_Format(PyExc_ImportError,
  710. "Non-code object in %.200s", cpathname);
  711. Py_DECREF(co);
  712. return NULL;
  713. }
  714. return (PyCodeObject *)co;
  715. }
  716. /* Load a module from a compiled file, execute it, and return its
  717. module object WITH INCREMENTED REFERENCE COUNT */
  718. static PyObject *
  719. load_compiled_module(char *name, char *cpathname, FILE *fp)
  720. {
  721. long magic;
  722. PyCodeObject *co;
  723. PyObject *m;
  724. magic = PyMarshal_ReadLongFromFile(fp);
  725. if (magic != pyc_magic) {
  726. PyErr_Format(PyExc_ImportError,
  727. "Bad magic number in %.200s", cpathname);
  728. return NULL;
  729. }
  730. (void) PyMarshal_ReadLongFromFile(fp);
  731. co = read_compiled_module(cpathname, fp);
  732. if (co == NULL)
  733. return NULL;
  734. if (Py_VerboseFlag)
  735. PySys_WriteStderr("import %s # precompiled from %s\n",
  736. name, cpathname);
  737. m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
  738. Py_DECREF(co);
  739. return m;
  740. }
  741. /* Parse a source file and return the corresponding code object */
  742. static PyCodeObject *
  743. parse_source_module(const char *pathname, FILE *fp)
  744. {
  745. PyCodeObject *co = NULL;
  746. mod_ty mod;
  747. PyCompilerFlags flags;
  748. PyArena *arena = PyArena_New();
  749. if (arena == NULL)
  750. return NULL;
  751. flags.cf_flags = 0;
  752. mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags,
  753. NULL, arena);
  754. if (mod) {
  755. co = PyAST_Compile(mod, pathname, NULL, arena);
  756. }
  757. PyArena_Free(arena);
  758. return co;
  759. }
  760. /* Helper to open a bytecode file for writing in exclusive mode */
  761. static FILE *
  762. open_exclusive(char *filename, mode_t mode)
  763. {
  764. #if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
  765. /* Use O_EXCL to avoid a race condition when another process tries to
  766. write the same file. When that happens, our open() call fails,
  767. which is just fine (since it's only a cache).
  768. XXX If the file exists and is writable but the directory is not
  769. writable, the file will never be written. Oh well.
  770. */
  771. int fd;
  772. (void) unlink(filename);
  773. fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
  774. #ifdef O_BINARY
  775. |O_BINARY /* necessary for Windows */
  776. #endif
  777. #ifdef __VMS
  778. , mode, "ctxt=bin", "shr=nil"
  779. #else
  780. , mode
  781. #endif
  782. );
  783. if (fd < 0)
  784. return NULL;
  785. return fdopen(fd, "wb");
  786. #else
  787. /* Best we can do -- on Windows this can't happen anyway */
  788. return fopen(filename, "wb");
  789. #endif
  790. }
  791. /* Write a compiled module to a file, placing the time of last
  792. modification of its source into the header.
  793. Errors are ignored, if a write error occurs an attempt is made to
  794. remove the file. */
  795. static void
  796. write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
  797. {
  798. FILE *fp;
  799. time_t mtime = srcstat->st_mtime;
  800. #ifdef MS_WINDOWS /* since Windows uses different permissions */
  801. mode_t mode = srcstat->st_mode & ~S_IEXEC;
  802. #else
  803. mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
  804. #endif
  805. fp = open_exclusive(cpathname, mode);
  806. if (fp == NULL) {
  807. if (Py_VerboseFlag)
  808. PySys_WriteStderr(
  809. "# can't create %s\n", cpathname);
  810. return;
  811. }
  812. PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
  813. /* First write a 0 for mtime */
  814. PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
  815. PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
  816. if (fflush(fp) != 0 || ferror(fp)) {
  817. if (Py_VerboseFlag)
  818. PySys_WriteStderr("# can't write %s\n", cpathname);
  819. /* Don't keep partial file */
  820. fclose(fp);
  821. (void) unlink(cpathname);
  822. return;
  823. }
  824. /* Now write the true mtime (as a 32-bit field) */
  825. fseek(fp, 4L, 0);
  826. assert(mtime <= 0xFFFFFFFF);
  827. PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
  828. fflush(fp);
  829. fclose(fp);
  830. if (Py_VerboseFlag)
  831. PySys_WriteStderr("# wrote %s\n", cpathname);
  832. }
  833. static void
  834. update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
  835. {
  836. PyObject *constants, *tmp;
  837. Py_ssize_t i, n;
  838. if (!_PyString_Eq(co->co_filename, oldname))
  839. return;
  840. tmp = co->co_filename;
  841. co->co_filename = newname;
  842. Py_INCREF(co->co_filename);
  843. Py_DECREF(tmp);
  844. constants = co->co_consts;
  845. n = PyTuple_GET_SIZE(constants);
  846. for (i = 0; i < n; i++) {
  847. tmp = PyTuple_GET_ITEM(constants, i);
  848. if (PyCode_Check(tmp))
  849. update_code_filenames((PyCodeObject *)tmp,
  850. oldname, newname);
  851. }
  852. }
  853. static int
  854. update_compiled_module(PyCodeObject *co, char *pathname)
  855. {
  856. PyObject *oldname, *newname;
  857. if (strcmp(PyString_AsString(co->co_filename), pathname) == 0)
  858. return 0;
  859. newname = PyString_FromString(pathname);
  860. if (newname == NULL)
  861. return -1;
  862. oldname = co->co_filename;
  863. Py_INCREF(oldname);
  864. update_code_filenames(co, oldname, newname);
  865. Py_DECREF(oldname);
  866. Py_DECREF(newname);
  867. return 1;
  868. }
  869. /* Load a source module from a given file and return its module
  870. object WITH INCREMENTED REFERENCE COUNT. If there's a matching
  871. byte-compiled file, use that instead. */
  872. static PyObject *
  873. load_source_module(char *name, char *pathname, FILE *fp)
  874. {
  875. struct stat st;
  876. FILE *fpc;
  877. char *buf;
  878. char *cpathname;
  879. PyCodeObject *co = NULL;
  880. PyObject *m;
  881. if (fstat(fileno(fp), &st) != 0) {
  882. PyErr_Format(PyExc_RuntimeError,
  883. "unable to get file status from '%s'",
  884. pathname);
  885. return NULL;
  886. }
  887. if (sizeof st.st_mtime > 4) {
  888. /* Python's .pyc timestamp handling presumes that the timestamp fits
  889. in 4 bytes. Since the code only does an equality comparison,
  890. ordering is not important and we can safely ignore the higher bits
  891. (collisions are extremely unlikely).
  892. */
  893. st.st_mtime &= 0xFFFFFFFF;
  894. }
  895. buf = PyMem_MALLOC(MAXPATHLEN+1);
  896. if (buf == NULL) {
  897. return PyErr_NoMemory();
  898. }
  899. cpathname = make_compiled_pathname(pathname, buf,
  900. (size_t)MAXPATHLEN + 1);
  901. if (cpathname != NULL &&
  902. (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
  903. co = read_compiled_module(cpathname, fpc);
  904. fclose(fpc);
  905. if (co == NULL)
  906. goto error_exit;
  907. if (update_compiled_module(co, pathname) < 0)
  908. goto error_exit;
  909. if (Py_VerboseFlag)
  910. PySys_WriteStderr("import %s # precompiled from %s\n",
  911. name, cpathname);
  912. pathname = cpathname;
  913. }
  914. else {
  915. co = parse_source_module(pathname, fp);
  916. if (co == NULL)
  917. goto error_exit;
  918. if (Py_VerboseFlag)
  919. PySys_WriteStderr("import %s # from %s\n",
  920. name, pathname);
  921. if (cpathname) {
  922. PyObject *ro = PySys_GetObject("dont_write_bytecode");
  923. if (ro == NULL || !PyObject_IsTrue(ro))
  924. write_compiled_module(co, cpathname, &st);
  925. }
  926. }
  927. m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
  928. Py_DECREF(co);
  929. PyMem_FREE(buf);
  930. return m;
  931. error_exit:
  932. Py_XDECREF(co);
  933. PyMem_FREE(buf);
  934. return NULL;
  935. }
  936. /* Forward */
  937. static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
  938. static struct filedescr *find_module(char *, char *, PyObject *,
  939. char *, size_t, FILE **, PyObject **);
  940. static struct _frozen *find_frozen(char *name);
  941. /* Load a package and return its module object WITH INCREMENTED
  942. REFERENCE COUNT */
  943. static PyObject *
  944. load_package(char *name, char *pathname)
  945. {
  946. PyObject *m, *d;
  947. PyObject *file = NULL;
  948. PyObject *path = NULL;
  949. int err;
  950. char *buf = NULL;
  951. FILE *fp = NULL;
  952. struct filedescr *fdp;
  953. m = PyImport_AddModule(name);
  954. if (m == NULL)
  955. return NULL;
  956. if (Py_VerboseFlag)
  957. PySys_WriteStderr("import %s # directory %s\n",
  958. name, pathname);
  959. d = PyModule_GetDict(m);
  960. file = PyString_FromString(pathname);
  961. if (file == NULL)
  962. goto error;
  963. path = Py_BuildValue("[O]", file);
  964. if (path == NULL)
  965. goto error;
  966. err = PyDict_SetItemString(d, "__file__", file);
  967. if (err == 0)
  968. err = PyDict_SetItemString(d, "__path__", path);
  969. if (err != 0)
  970. goto error;
  971. buf = PyMem_MALLOC(MAXPATHLEN+1);
  972. if (buf == NULL) {
  973. PyErr_NoMemory();
  974. goto error;
  975. }
  976. buf[0] = '\0';
  977. fdp = find_module(name, "__init__", path, buf, MAXPATHLEN+1, &fp, NULL);
  978. if (fdp == NULL) {
  979. if (PyErr_ExceptionMatches(PyExc_ImportError)) {
  980. PyErr_Clear();
  981. Py_INCREF(m);
  982. }
  983. else
  984. m = NULL;
  985. goto cleanup;
  986. }
  987. m = load_module(name, fp, buf, fdp->type, NULL);
  988. if (fp != NULL)
  989. fclose(fp);
  990. goto cleanup;
  991. error:
  992. m = NULL;
  993. cleanup:
  994. if (buf)
  995. PyMem_FREE(buf);
  996. Py_XDECREF(path);
  997. Py_XDECREF(file);
  998. return m;
  999. }
  1000. /* Helper to test for built-in module */
  1001. static int
  1002. is_builtin(char *name)
  1003. {
  1004. int i;
  1005. for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
  1006. if (strcmp(name, PyImport_Inittab[i].name) == 0) {
  1007. if (PyImport_Inittab[i].initfunc == NULL)
  1008. return -1;
  1009. else
  1010. return 1;
  1011. }
  1012. }
  1013. return 0;
  1014. }
  1015. /* Return an importer object for a sys.path/pkg.__path__ item 'p',
  1016. possibly by fetching it from the path_importer_cache dict. If it
  1017. wasn't yet cached, traverse path_hooks until a hook is found
  1018. that can handle the path item. Return None if no hook could;
  1019. this tells our caller it should fall back to the builtin
  1020. import mechanism. Cache the result in path_importer_cache.
  1021. Returns a borrowed reference. */
  1022. static PyObject *
  1023. get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
  1024. PyObject *p)
  1025. {
  1026. PyObject *importer;
  1027. Py_ssize_t j, nhooks;
  1028. /* These conditions are the caller's responsibility: */
  1029. assert(PyList_Check(path_hooks));
  1030. assert(PyDict_Check(path_importer_cache));
  1031. nhooks = PyList_Size(path_hooks);
  1032. if (nhooks < 0)
  1033. return NULL; /* Shouldn't happen */
  1034. importer = PyDict_GetItem(path_importer_cache, p);
  1035. if (importer != NULL)
  1036. return importer;
  1037. /* set path_importer_cache[p] to None to avoid recursion */
  1038. if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
  1039. return NULL;
  1040. for (j = 0; j < nhooks; j++) {
  1041. PyObject *hook = PyList_GetItem(path_hooks, j);
  1042. if (hook == NULL)
  1043. return NULL;
  1044. importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
  1045. if (importer != NULL)
  1046. break;
  1047. if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
  1048. return NULL;
  1049. }
  1050. PyErr_Clear();
  1051. }
  1052. if (importer == NULL) {
  1053. importer = PyObject_CallFunctionObjArgs(
  1054. (PyObject *)&PyNullImporter_Type, p, NULL
  1055. );
  1056. if (importer == NULL) {
  1057. if (PyErr_ExceptionMatches(PyExc_ImportError)) {
  1058. PyErr_Clear();
  1059. return Py_None;
  1060. }
  1061. }
  1062. }
  1063. if (importer != NULL) {
  1064. int err = PyDict_SetItem(path_importer_cache, p, importer);
  1065. Py_DECREF(importer);
  1066. if (err != 0)
  1067. return NULL;
  1068. }
  1069. return importer;
  1070. }
  1071. PyAPI_FUNC(PyObject *)
  1072. PyImport_GetImporter(PyObject *path) {
  1073. PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
  1074. if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
  1075. if ((path_hooks = PySys_GetObject("path_hooks"))) {
  1076. importer = get_path_importer(path_importer_cache,
  1077. path_hooks, path);
  1078. }
  1079. }
  1080. Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
  1081. return importer;
  1082. }
  1083. /* Search the path (default sys.path) for a module. Return the
  1084. corresponding filedescr struct, and (via return arguments) the
  1085. pathname and an open file. Return NULL if the module is not found. */
  1086. #ifdef MS_COREDLL
  1087. extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
  1088. char *, Py_ssize_t);
  1089. #endif
  1090. static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
  1091. static int find_init_module(char *); /* Forward */
  1092. static struct filedescr importhookdescr = {"", "", IMP_HOOK};
  1093. static struct filedescr *
  1094. find_module(char *fullname, char *subname, PyObject *path, char *buf,
  1095. size_t buflen, FILE **p_fp, PyObject **p_loader)
  1096. {
  1097. Py_ssize_t i, npath;
  1098. size_t len, namelen;
  1099. struct filedescr *fdp = NULL;
  1100. char *filemode;
  1101. FILE *fp = NULL;
  1102. PyObject *path_hooks, *path_importer_cache;
  1103. static struct filedescr fd_frozen = {"", "", PY_FROZEN};
  1104. static struct filedescr fd_builtin = {"", "", C_BUILTIN};
  1105. static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
  1106. char *name;
  1107. #if defined(PYOS_OS2)
  1108. size_t saved_len;
  1109. size_t saved_namelen;
  1110. char *saved_buf = NULL;
  1111. #endif
  1112. if (p_loader != NULL)
  1113. *p_loader = NULL;
  1114. if (strlen(subname) > MAXPATHLEN) {
  1115. PyErr_SetString(PyExc_OverflowError,
  1116. "module name is too long");
  1117. return NULL;
  1118. }
  1119. name = PyMem_MALLOC(MAXPATHLEN+1);
  1120. if (name == NULL) {
  1121. PyErr_NoMemory();
  1122. return NULL;
  1123. }
  1124. strcpy(name, subname);
  1125. /* sys.meta_path import hook */
  1126. if (p_loader != NULL) {
  1127. PyObject *meta_path;
  1128. meta_path = PySys_GetObject("meta_path");
  1129. if (meta_path == NULL || !PyList_Check(meta_path)) {
  1130. PyErr_SetString(PyExc_RuntimeError,
  1131. "sys.meta_path must be a list of "
  1132. "import hooks");
  1133. goto error_exit;
  1134. }
  1135. Py_INCREF(meta_path); /* zap guard */
  1136. npath = PyList_Size(meta_path);
  1137. for (i = 0; i < npath; i++) {
  1138. PyObject *loader;
  1139. PyObject *hook = PyList_GetItem(meta_path, i);
  1140. loader = PyObject_CallMethod(hook, "find_module",
  1141. "sO", fullname,
  1142. path != NULL ?
  1143. path : Py_None);
  1144. if (loader == NULL) {
  1145. Py_DECREF(meta_path);
  1146. goto error_exit; /* true error */
  1147. }
  1148. if (loader != Py_None) {
  1149. /* a loader was found */
  1150. *p_loader = loader;
  1151. Py_DECREF(meta_path);
  1152. PyMem_FREE(name);
  1153. return &importhookdescr;
  1154. }
  1155. Py_DECREF(loader);
  1156. }
  1157. Py_DECREF(meta_path);
  1158. }
  1159. if (path != NULL && PyString_Check(path)) {
  1160. /* The only type of submodule allowed inside a "frozen"
  1161. package are other frozen modules or packages. */
  1162. if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
  1163. PyErr_SetString(PyExc_ImportError,
  1164. "full frozen module name too long");
  1165. goto error_exit;
  1166. }
  1167. strcpy(buf, PyString_AsString(path));
  1168. strcat(buf, ".");
  1169. strcat(buf, name);
  1170. strcpy(name, buf);
  1171. if (find_frozen(name) != NULL) {
  1172. strcpy(buf, name);
  1173. PyMem_FREE(name);
  1174. return &fd_frozen;
  1175. }
  1176. PyErr_Format(PyExc_ImportError,
  1177. "No frozen submodule named %.200s", name);
  1178. goto error_exit;
  1179. }
  1180. if (path == NULL) {
  1181. if (is_builtin(name)) {
  1182. strcpy(buf, name);
  1183. PyMem_FREE(name);
  1184. return &fd_builtin;
  1185. }
  1186. if ((find_frozen(name)) != NULL) {
  1187. strcpy(buf, name);
  1188. PyMem_FREE(name);
  1189. return &fd_frozen;
  1190. }
  1191. #ifdef MS_COREDLL
  1192. fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
  1193. if (fp != NULL) {
  1194. *p_fp = fp;
  1195. PyMem_FREE(name);
  1196. return fdp;
  1197. }
  1198. #endif
  1199. path = PySys_GetObject("path");
  1200. }
  1201. if (path == NULL || !PyList_Check(path)) {
  1202. PyErr_SetString(PyExc_RuntimeError,
  1203. "sys.path must be a list of directory names");
  1204. goto error_exit;
  1205. }
  1206. path_hooks = PySys_GetObject("path_hooks");
  1207. if (path_hooks == NULL || !PyList_Check(path_hooks)) {
  1208. PyErr_SetString(PyExc_RuntimeError,
  1209. "sys.path_hooks must be a list of "
  1210. "import hooks");
  1211. goto error_exit;
  1212. }
  1213. path_importer_cache = PySys_GetObject("path_importer_cache");
  1214. if (path_importer_cache == NULL ||
  1215. !PyDict_Check(path_importer_cache)) {
  1216. PyErr_SetString(PyExc_RuntimeError,
  1217. "sys.path_importer_cache must be a dict");
  1218. goto error_exit;
  1219. }
  1220. npath = PyList_Size(path);
  1221. namelen = strlen(name);
  1222. for (i = 0; i < npath; i++) {
  1223. PyObject *copy = NULL;
  1224. PyObject *v = PyList_GetItem(path, i);
  1225. if (!v)
  1226. goto error_exit;
  1227. #ifdef Py_USING_UNICODE
  1228. if (PyUnicode_Check(v)) {
  1229. copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
  1230. PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
  1231. if (copy == NULL)
  1232. goto error_exit;
  1233. v = copy;
  1234. }
  1235. else
  1236. #endif
  1237. if (!PyString_Check(v))
  1238. continue;
  1239. len = PyString_GET_SIZE(v);
  1240. if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
  1241. Py_XDECREF(copy);
  1242. continue; /* Too long */
  1243. }
  1244. strcpy(buf, PyString_AS_STRING(v));
  1245. if (strlen(buf) != len) {
  1246. Py_XDECREF(copy);
  1247. continue; /* v contains '\0' */
  1248. }
  1249. /* sys.path_hooks import hook */
  1250. if (p_loader != NULL) {
  1251. PyObject *importer;
  1252. importer = get_path_importer(path_importer_cache,
  1253. path_hooks, v);
  1254. if (importer == NULL) {
  1255. Py_XDECREF(copy);
  1256. goto error_exit;
  1257. }
  1258. /* Note: importer is a borrowed reference */
  1259. if (importer != Py_None) {
  1260. PyObject *loader;
  1261. loader = PyObject_CallMethod(importer,
  1262. "find_module",
  1263. "s", fullname);
  1264. Py_XDECREF(copy);
  1265. if (loader == NULL)
  1266. goto error_exit; /* error */
  1267. if (loader != Py_None) {
  1268. /* a loader was found */
  1269. *p_loader = loader;
  1270. PyMem_FREE(name);
  1271. return &importhookdescr;
  1272. }
  1273. Py_DECREF(loader);
  1274. continue;
  1275. }
  1276. }
  1277. /* no hook was found, use builtin import */
  1278. if (len > 0 && buf[len-1] != SEP
  1279. #ifdef ALTSEP
  1280. && buf[len-1] != ALTSEP
  1281. #endif
  1282. )
  1283. buf[len++] = SEP;
  1284. strcpy(buf+len, name);
  1285. len += namelen;
  1286. /* Check for package import (buf holds a directory name,
  1287. and there's an __init__ module in that directory */
  1288. if (isdir(buf) && /* it's an existing directory */
  1289. case_ok(buf, len, namelen, name)) { /* case matches */
  1290. if (find_init_module(buf)) { /* and has __init__.py */
  1291. Py_XDECREF(copy);
  1292. PyMem_FREE(name);
  1293. return &fd_package;
  1294. }
  1295. else {
  1296. char warnstr[MAXPATHLEN+80];
  1297. sprintf(warnstr, "Not importing directory "
  1298. "'%.*s': missing __init__.py",
  1299. MAXPATHLEN, buf);
  1300. if (PyErr_Warn(PyExc_ImportWarning,
  1301. warnstr)) {
  1302. Py_XDECREF(copy);
  1303. goto error_exit;
  1304. }
  1305. }
  1306. }
  1307. #if defined(PYOS_OS2)
  1308. /* take a snapshot of the module spec for restoration
  1309. * after the 8 character DLL hackery
  1310. */
  1311. saved_buf = strdup(buf);
  1312. saved_len = len;
  1313. saved_namelen = namelen;
  1314. #endif /* PYOS_OS2 */
  1315. for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
  1316. #if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
  1317. /* OS/2 limits DLLs to 8 character names (w/o
  1318. extension)
  1319. * so if the name is longer than that and its a
  1320. * dynamically loaded module we're going to try,
  1321. * truncate the name before trying
  1322. */
  1323. if (strlen(subname) > 8) {
  1324. /* is this an attempt to load a C extension? */
  1325. const struct filedescr *scan;
  1326. scan = _PyImport_DynLoadFiletab;
  1327. while (scan->suffix != NULL) {
  1328. if (!strcmp(scan->suffix, fdp->suffix))
  1329. break;
  1330. else
  1331. scan++;
  1332. }
  1333. if (scan->suffix != NULL) {
  1334. /* yes, so truncate the name */
  1335. namelen = 8;
  1336. len -= strlen(subname) - namelen;
  1337. buf[len] = '\0';
  1338. }
  1339. }
  1340. #endif /* PYOS_OS2 */
  1341. strcpy(buf+len, fdp->suffix);
  1342. if (Py_VerboseFlag > 1)
  1343. PySys_WriteStderr("# trying %s\n", buf);
  1344. filemode = fdp->mode;
  1345. if (filemode[0] == 'U')
  1346. filemode = "r" PY_STDIOTEXTMODE;
  1347. fp = fopen(buf, filemode);
  1348. if (fp != NULL) {
  1349. if (case_ok(buf, len, namelen, name))
  1350. break;
  1351. else { /* continue search */
  1352. fclose(fp);
  1353. fp = NULL;
  1354. }
  1355. }
  1356. #if defined(PYOS_OS2)
  1357. /* restore the saved snapshot */
  1358. strcpy(buf, saved_buf);
  1359. len = saved_len;
  1360. namelen = saved_namelen;
  1361. #endif
  1362. }
  1363. #if defined(PYOS_OS2)
  1364. /* don't need/want the module name snapshot anymore */
  1365. if (saved_buf)
  1366. {
  1367. free(saved_buf);
  1368. saved_buf = NULL;
  1369. }
  1370. #endif
  1371. Py_XDECREF(copy);
  1372. if (fp != NULL)
  1373. break;
  1374. }
  1375. if (fp == NULL) {
  1376. PyErr_Format(PyExc_ImportError,
  1377. "No module named %.200s", name);
  1378. goto error_exit;
  1379. }
  1380. *p_fp = fp;
  1381. PyMem_FREE(name);
  1382. return fdp;
  1383. error_exit:
  1384. PyMem_FREE(name);
  1385. return NULL;
  1386. }
  1387. /* Helpers for main.c
  1388. * Find the source file corresponding to a named module
  1389. */
  1390. struct filedescr *
  1391. _PyImport_FindModule(const char *name, PyObject *path, char *buf,
  1392. size_t buflen, FILE **p_fp, PyObject **p_loader)
  1393. {
  1394. return find_module((char *) name, (char *) name, path,
  1395. buf, buflen, p_fp, p_loader);
  1396. }
  1397. PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
  1398. {
  1399. return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
  1400. }
  1401. /* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
  1402. * The arguments here are tricky, best shown by example:
  1403. * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
  1404. * ^ ^ ^ ^
  1405. * |--------------------- buf ---------------------|
  1406. * |------------------- len ------------------|
  1407. * |------ name -------|
  1408. * |----- namelen -----|
  1409. * buf is the full path, but len only counts up to (& exclusive of) the
  1410. * extension. name is the module name, also exclusive of extension.
  1411. *
  1412. * We've already done a successful stat() or fopen() on buf, so know that
  1413. * there's some match, possibly case-insensitive.
  1414. *
  1415. * case_ok() is to return 1 if there's a case-sensitive match for
  1416. * name, else 0. case_ok() is also to return 1 if envar PYTHONCASEOK
  1417. * exists.
  1418. *
  1419. * case_ok() is used to implement case-sensitive import semantics even
  1420. * on platforms with case-insensitive filesystems. It's trivial to implement
  1421. * for case-sensitive filesystems. It's pretty much a cross-platform
  1422. * nightmare for systems with case-insensitive filesystems.
  1423. */
  1424. /* First we may need a pile of platform-specific header files; the sequence
  1425. * of #if's here should match the sequence in the body of case_ok().
  1426. */
  1427. #if defined(MS_WINDOWS)
  1428. #include <windows.h>
  1429. #elif defined(DJGPP)
  1430. #include <dir.h>
  1431. #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
  1432. #include <sys/types.h>
  1433. #include <dirent.h>
  1434. #elif defined(PYOS_OS2)
  1435. #define INCL_DOS
  1436. #define INCL_DOSERRORS
  1437. #define INCL_NOPMAPI
  1438. #include <os2.h>
  1439. #elif defined(RISCOS)
  1440. #include "oslib/osfscontrol.h"
  1441. #endif
  1442. static int
  1443. case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
  1444. {
  1445. /* Pick a platform-specific implementation; the sequence of #if's here should
  1446. * match the sequence just above.
  1447. */
  1448. /* MS_WINDOWS */
  1449. #if defined(MS_WINDOWS)
  1450. WIN32_FIND_DATA data;
  1451. HANDLE h;
  1452. if (Py_GETENV("PYTHONCASEOK") != NULL)
  1453. return 1;
  1454. h = FindFirstFile(buf, &data);
  1455. if (h == INVALID_HANDLE_VALUE) {
  1456. PyErr_Format(PyExc_NameError,
  1457. "Can't find file for module %.100s\n(filename %.300s)",
  1458. name, buf);
  1459. return 0;
  1460. }
  1461. FindClose(h);
  1462. return strncmp(data.cFileName, name, namelen) == 0;
  1463. /* DJGPP */
  1464. #elif defined(DJGPP)
  1465. struct ffblk ffblk;
  1466. int done;
  1467. if (Py_GETENV("PYTHONCASEOK") != NULL)
  1468. return 1;
  1469. done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
  1470. if (done) {
  1471. PyErr_Format(PyExc_NameError,
  1472. "Can't find file for module %.100s\n(filename %.300s)",
  1473. name, buf);
  1474. return 0;
  1475. }
  1476. return strncmp(ffblk.ff_name, name, namelen) == 0;
  1477. /* new-fangled macintosh (macosx) or Cygwin */
  1478. #elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
  1479. DIR *dirp;
  1480. struct dirent *dp;
  1481. char dirname[MAXPATHLEN + 1];
  1482. const int dirlen = len - namelen - 1; /* don't want trailing SEP */
  1483. if (Py_GETENV("PYTHONCASEOK") != NULL)
  1484. return 1;
  1485. /* Copy the dir component into dirname; substitute "." if empty */
  1486. if (dirlen <= 0) {
  1487. dirname[0] = '.';
  1488. dirname[1] = '\0';
  1489. }
  1490. else {
  1491. assert(dirlen <= MAXPATHLEN);
  1492. memcpy(dirname, buf, dirlen);
  1493. dirname[dirlen] = '\0';
  1494. }
  1495. /* Open the directory and search the entries for an exact match. */
  1496. dirp = opendir(dirname);
  1497. if (dirp) {
  1498. char *nameWithExt = buf + len - namelen;
  1499. while ((dp = readdir(dirp)) != NULL) {
  1500. const int thislen =
  1501. #ifdef _DIRENT_HAVE_D_NAMELEN
  1502. dp->d_namlen;
  1503. #else
  1504. strlen(dp->d_name);
  1505. #endif
  1506. if (thislen >= namelen &&
  1507. strcmp(dp->d_name, nameWithExt) == 0) {
  1508. (void)closedir(dirp);
  1509. return 1; /* Found */
  1510. }
  1511. }
  1512. (void)closedir(dirp);
  1513. }
  1514. return 0 ; /* Not found */
  1515. /* RISC OS */
  1516. #elif defined(RISCOS)
  1517. char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
  1518. char buf2[MAXPATHLEN+2];
  1519. char *nameWithExt = buf+len-namelen;
  1520. int canonlen;
  1521. os_error *e;
  1522. if (Py_GETENV("PYTHONCASEOK") != NULL)
  1523. return 1;
  1524. /* workaround:
  1525. append wildcard, otherwise case of filename wouldn't be touched */
  1526. strcpy(buf2, buf);
  1527. strcat(buf2, "*");
  1528. e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
  1529. canonlen = MAXPATHLEN+1-canonlen;
  1530. if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
  1531. return 0;
  1532. if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
  1533. return 1; /* match */
  1534. return 0;
  1535. /* OS/2 */
  1536. #elif defined(PYOS_OS2)
  1537. HDIR hdir = 1;
  1538. ULONG srchcnt = 1;
  1539. FILEFINDBUF3 ffbuf;
  1540. APIRET rc;
  1541. if (Py_GETENV("PYTHONCASEOK") != NULL)
  1542. return 1;
  1543. rc = DosFindFirst(buf,
  1544. &hdir,
  1545. FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
  1546. &ffbuf, sizeof(ffbuf),
  1547. &srchcnt,
  1548. FIL_STANDARD);
  1549. if (rc != NO_ERROR)
  1550. return 0;
  1551. return strncmp(ffbuf.achName, name, namelen) == 0;
  1552. /* assuming it's a case-sensitive filesystem, so there's nothing to do! */
  1553. #else
  1554. return 1;
  1555. #endif
  1556. }
  1557. #ifdef HAVE_STAT
  1558. /* Helper to look for __init__.py or __init__.py[co] in potential package */
  1559. static int
  1560. find_init_module(char *buf)
  1561. {
  1562. const size_t save_len = strlen(buf);
  1563. size_t i = save_len;
  1564. char *pname; /* pointer to start of __init__ */
  1565. struct stat statbuf;
  1566. /* For calling case_ok(buf, len, namelen, name):
  1567. * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
  1568. * ^ ^ ^ ^
  1569. * |--------------------- buf ---------------------|
  1570. * |------------------- len ------------------|
  1571. * |------ name -------|
  1572. * |----- namelen -----|
  1573. */
  1574. if (save_len + 13 >= MAXPATHLEN)
  1575. return 0;
  1576. buf[i++] = SEP;
  1577. pname = buf + i;
  1578. strcpy(pname, "__init__.py");
  1579. if (stat(buf, &statbuf) == 0) {
  1580. if (case_ok(buf,
  1581. save_len + 9, /* len("/__init__") */
  1582. 8, /* len("__init__") */
  1583. pname)) {
  1584. buf[save_len] = '\0';
  1585. return 1;
  1586. }
  1587. }
  1588. i += strlen(pname);
  1589. strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
  1590. if (stat(buf, &statbuf) == 0) {
  1591. if (case_ok(buf,
  1592. save_len + 9, /* len("/__init__") */
  1593. 8, /* len("__init__") */
  1594. pname)) {
  1595. buf[save_len] = '\0';
  1596. return 1;
  1597. }
  1598. }
  1599. buf[save_len] = '\0';
  1600. return 0;
  1601. }
  1602. #else
  1603. #ifdef RISCOS
  1604. static int
  1605. find_init_module(buf)
  1606. char *buf;
  1607. {
  1608. int save_len = strlen(buf);
  1609. int i = save_len;
  1610. if (save_len + 13 >= MAXPATHLEN)
  1611. return 0;
  1612. buf[i++] = SEP;
  1613. strcpy(buf+i, "__init__/py");
  1614. if (isfile(buf)) {
  1615. buf[save_len] = '\0';
  1616. return 1;
  1617. }
  1618. if (Py_OptimizeFlag)
  1619. strcpy(buf+i, "o");
  1620. else
  1621. strcpy(buf+i, "c");
  1622. if (isfile(buf)) {
  1623. buf[save_len] = '\0';
  1624. return 1;
  1625. }
  1626. buf[save_len] = '\0';
  1627. return 0;
  1628. }
  1629. #endif /*RISCOS*/
  1630. #endif /* HAVE_STAT */
  1631. static int init_builtin(char *); /* Forward */
  1632. /* Load an external module using the default search path and return
  1633. its module object WITH INCREMENTED REFERENCE COUNT */
  1634. static PyObject *
  1635. load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
  1636. {
  1637. PyObject *modules;
  1638. PyObject *m;
  1639. int err;
  1640. /* First check that there's an open file (if we need one) */
  1641. switch (type) {
  1642. case PY_SOURCE:
  1643. case PY_COMPILED:
  1644. if (fp == NULL) {
  1645. PyErr_Format(PyExc_ValueError,
  1646. "file object required for import (type code %d)",
  1647. type);
  1648. return NULL;
  1649. }
  1650. }
  1651. switch (type) {
  1652. case PY_SOURCE:
  1653. m = load_source_module(name, pathname, fp);
  1654. break;
  1655. case PY_COMPILED:
  1656. m = load_compiled_module(name, pathname, fp);
  1657. break;
  1658. #ifdef HAVE_DYNAMIC_LOADING
  1659. case C_EXTENSION:
  1660. m = _PyImport_LoadDynamicModule(name, pathname, fp);
  1661. break;
  1662. #endif
  1663. case PKG_DIRECTORY:
  1664. m = load_package(name, pathname);
  1665. break;
  1666. case C_BUILTIN:
  1667. case PY_FROZEN:
  1668. if (pathname != NULL && pathname[0] != '\0')
  1669. name = pathname;
  1670. if (type == C_BUILTIN)
  1671. err = init_builtin(name);
  1672. else
  1673. err = PyImport_ImportFrozenModule(name);
  1674. if (err < 0)
  1675. return NULL;
  1676. if (err == 0) {
  1677. PyErr_Format(PyExc_ImportError,
  1678. "Purported %s module %.200s not found",
  1679. type == C_BUILTIN ?
  1680. "builtin" : "frozen",
  1681. name);
  1682. return NULL;
  1683. }
  1684. modules = PyImport_GetModuleDict();
  1685. m = PyDict_GetItemString(modules, name);
  1686. if (m == NULL) {
  1687. PyErr_Format(
  1688. PyExc_ImportError,
  1689. "%s module %.200s not properly initialized",
  1690. type == C_BUILTIN ?
  1691. "builtin" : "frozen",
  1692. name);
  1693. return NULL;
  1694. }
  1695. Py_INCREF(m);
  1696. break;
  1697. case IMP_HOOK: {
  1698. if (loader == NULL) {
  1699. PyErr_SetString(PyExc_ImportError,
  1700. "import hook without loader");
  1701. return NULL;
  1702. }
  1703. m = PyObject_CallMethod(loader, "load_module", "s", name);
  1704. break;
  1705. }
  1706. default:
  1707. PyErr_Format(PyExc_ImportError,
  1708. "Don't know how to import %.200s (type code %d)",
  1709. name, type);
  1710. m = NULL;
  1711. }
  1712. return m;
  1713. }
  1714. /* Initialize a built-in module.
  1715. Return 1 for success, 0 if the module is not found, and -1 with
  1716. an exception set if the initialization failed. */
  1717. static int
  1718. init_builtin(char *name)
  1719. {
  1720. struct _inittab *p;
  1721. if (_PyImport_FindExtension(name, name) != NULL)
  1722. return 1;
  1723. for (p = PyImport_Inittab; p->name != NULL; p++) {
  1724. if (strcmp(name, p->name) == 0) {
  1725. if (p->initfunc == NULL) {
  1726. PyErr_Format(PyExc_ImportError,
  1727. "Cannot re-init internal module %.200s",
  1728. name);
  1729. return -1;
  1730. }
  1731. if (Py_VerboseFlag)
  1732. PySys_WriteStderr("import %s # builtin\n", name);
  1733. (*p->initfunc)();
  1734. if (PyErr_Occurred())
  1735. return -1;
  1736. if (_PyImport_FixupExtension(name, name) == NULL)
  1737. return -1;
  1738. return 1;
  1739. }
  1740. }
  1741. return 0;
  1742. }
  1743. /* Frozen modules */
  1744. static struct _frozen *
  1745. find_frozen(char *name)
  1746. {
  1747. struct _frozen *p;
  1748. for (p = PyImport_FrozenModules; ; p++) {
  1749. if (p->name == NULL)
  1750. return NULL;
  1751. if (strcmp(p->name, name) == 0)
  1752. break;
  1753. }
  1754. return p;
  1755. }
  1756. static PyObject *
  1757. get_frozen_object(char *name)
  1758. {
  1759. struct _frozen *p = find_frozen(name);
  1760. int size;
  1761. if (p == NULL) {
  1762. PyErr_Format(PyExc_ImportError,
  1763. "No such frozen object named %.200s",
  1764. name);
  1765. return NULL;
  1766. }
  1767. if (p->code == NULL) {
  1768. PyErr_Format(PyExc_ImportError,
  1769. "Excluded frozen object named %.200s",
  1770. name);
  1771. return NULL;
  1772. }
  1773. size = p->size;
  1774. if (size < 0)
  1775. size = -size;
  1776. return PyMarshal_ReadObjectFromString((char *)p->code, size);
  1777. }
  1778. /* Initialize a frozen module.
  1779. Return 1 for succes, 0 if the module is not found, and -1 with
  1780. an exception set if the initialization failed.
  1781. This function is also used from frozenmain.c */
  1782. int
  1783. PyImport_ImportFrozenModule(char *name)
  1784. {
  1785. struct _frozen *p = find_frozen(name);
  1786. PyObject *co;
  1787. PyObject *m;
  1788. int ispackage;
  1789. int size;
  1790. if (p == NULL)
  1791. return 0;
  1792. if (p->code == NULL) {
  1793. PyErr_Format(PyExc_ImportError,
  1794. "Excluded frozen object named %.200s",
  1795. name);
  1796. return -1;
  1797. }
  1798. size = p->size;
  1799. ispackage = (size < 0);
  1800. if (ispackage)
  1801. size = -size;
  1802. if (Py_VerboseFlag)
  1803. PySys_WriteStderr("import %s # frozen%s\n",
  1804. name, ispackage ? " package" : "");
  1805. co = PyMarshal_ReadObjectFromString((char *)p->code, size);
  1806. if (co == NULL)
  1807. return -1;
  1808. if (!PyCode_Check(co)) {
  1809. PyErr_Format(PyExc_TypeError,
  1810. "frozen object %.200s is not a code object",
  1811. name);
  1812. goto err_return;
  1813. }
  1814. if (ispackage) {
  1815. /* Set __path__ to the package name */
  1816. PyObject *d, *s;
  1817. int err;
  1818. m = PyImport_AddModule(name);
  1819. if (m == NULL)
  1820. goto err_return;
  1821. d = PyModule_GetDict(m);
  1822. s = PyString_InternFromString(name);
  1823. if (s == NULL)
  1824. goto err_return;
  1825. err = PyDict_SetItemString(d, "__path__", s);
  1826. Py_DECREF(s);
  1827. if (err != 0)
  1828. goto err_return;
  1829. }
  1830. m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
  1831. if (m == NULL)
  1832. goto err_return;
  1833. Py_DECREF(co);
  1834. Py_DECREF(m);
  1835. return 1;
  1836. err_return:
  1837. Py_DECREF(co);
  1838. return -1;
  1839. }
  1840. /* Import a module, either built-in, frozen, or external, and return
  1841. its module object WITH INCREMENTED REFERENCE COUNT */
  1842. PyObject *
  1843. PyImport_ImportModule(const char *name)
  1844. {
  1845. PyObject *pname;
  1846. PyObject *result;
  1847. pname = PyString_FromString(name);
  1848. if (pname == NULL)
  1849. return NULL;
  1850. result = PyImport_Import(pname);
  1851. Py_DECREF(pname);
  1852. return result;
  1853. }
  1854. /* Import a module without blocking
  1855. *
  1856. * At first it tries to fetch the module from sys.modules. If the module was
  1857. * never loaded before it loads it with PyImport_ImportModule() unless another
  1858. * thread holds the import lock. In the latter case the function raises an
  1859. * ImportError instead of blocking.
  1860. *
  1861. * Returns the module object with incremented ref count.
  1862. */
  1863. PyObject *
  1864. PyImport_ImportModuleNoBlock(const char *name)
  1865. {
  1866. PyObject *result;
  1867. PyObject *modules;
  1868. #ifdef WITH_THREAD
  1869. long me;
  1870. #endif
  1871. /* Try to get the module from sys.modules[name] */
  1872. modules = PyImport_GetModuleDict();
  1873. if (modules == NULL)
  1874. return NULL;
  1875. result = PyDict_GetItemString(modules, name);
  1876. if (result != NULL) {
  1877. Py_INCREF(result);
  1878. return result;
  1879. }
  1880. else {
  1881. PyErr_Clear();
  1882. }
  1883. #ifdef WITH_THREAD
  1884. /* check the import lock
  1885. * me might be -1 but I ignore the error here, the lock function
  1886. * takes care of the problem */
  1887. me = PyThread_get_thread_ident();
  1888. if (import_lock_thread == -1 || import_lock_thread == me) {
  1889. /* no thread or me is holding the lock */
  1890. return PyImport_ImportModule(name);
  1891. }
  1892. else {
  1893. PyErr_Format(PyExc_ImportError,
  1894. "Failed to import %.200s because the import lock"
  1895. "is held by another thread.",
  1896. name);
  1897. return NULL;
  1898. }
  1899. #else
  1900. return PyImport_ImportModule(name);
  1901. #endif
  1902. }
  1903. /* Forward declarations for helper routines */
  1904. static PyObject *get_parent(PyObject *globals, char *buf,
  1905. Py_ssize_t *p_buflen, int level);
  1906. static PyObject *load_next(PyObject *mod, PyObject *altmod,
  1907. char **p_name, char *buf, Py_ssize_t *p_buflen);
  1908. static int mark_miss(char *name);
  1909. static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
  1910. char *buf, Py_ssize_t buflen, int recursive);
  1911. static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
  1912. /* The Magnum Opus of dotted-name import :-) */
  1913. static PyObject *
  1914. import_module_level(char *name, PyObject *globals, PyObject *locals,
  1915. PyObject *fromlist, int level)
  1916. {
  1917. char *buf;
  1918. Py_ssize_t buflen = 0;
  1919. PyObject *parent, *head, *next, *tail;
  1920. if (strchr(name, '/') != NULL
  1921. #ifdef MS_WINDOWS
  1922. || strchr(name, '\\') != NULL
  1923. #endif
  1924. ) {
  1925. PyErr_SetString(PyExc_ImportError,
  1926. "Import by filename is not supported.");
  1927. return NULL;
  1928. }
  1929. buf = PyMem_MALLOC(MAXPATHLEN+1);
  1930. if (buf == NULL) {
  1931. return PyErr_NoMemory();
  1932. }
  1933. parent = get_parent(globals, buf, &buflen, level);
  1934. if (parent == NULL)
  1935. goto error_exit;
  1936. head = load_next(parent, level < 0 ? Py_None : parent, &name, buf,
  1937. &buflen);
  1938. if (head == NULL)
  1939. goto error_exit;
  1940. tail = head;
  1941. Py_INCREF(tail);
  1942. while (name) {
  1943. next = load_next(tail, tail, &name, buf, &buflen);
  1944. Py_DECREF(tail);
  1945. if (next == NULL) {
  1946. Py_DECREF(head);
  1947. goto error_exit;
  1948. }
  1949. tail = next;
  1950. }
  1951. if (tail == Py_None) {
  1952. /* If tail is Py_None, both get_parent and load_next found
  1953. an empty module name: someone called __import__("") or
  1954. doctored faulty bytecode */
  1955. Py_DECREF(tail);
  1956. Py_DECREF(head);
  1957. PyErr_SetString(PyExc_ValueError,
  1958. "Empty module name");
  1959. goto error_exit;
  1960. }
  1961. if (fromlist != NULL) {
  1962. if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
  1963. fromlist = NULL;
  1964. }
  1965. if (fromlist == NULL) {
  1966. Py_DECREF(tail);
  1967. PyMem_FREE(buf);
  1968. return head;
  1969. }
  1970. Py_DECREF(head);
  1971. if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
  1972. Py_DECREF(tail);
  1973. goto error_exit;
  1974. }
  1975. PyMem_FREE(buf);
  1976. return tail;
  1977. error_exit:
  1978. PyMem_FREE(buf);
  1979. return NULL;
  1980. }
  1981. PyObject *
  1982. PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
  1983. PyObject *fromlist, int level)
  1984. {
  1985. PyObject *result;
  1986. _PyImport_AcquireLock();
  1987. result = import_module_level(name, globals, locals, fromlist, level);
  1988. if (_PyImport_ReleaseLock() < 0) {
  1989. Py_XDECREF(result);
  1990. PyErr_SetString(PyExc_RuntimeError,
  1991. "not holding the import lock");
  1992. return NULL;
  1993. }
  1994. return result;
  1995. }
  1996. /* Return the package that an import is being performed in. If globals comes
  1997. from the module foo.bar.bat (not itself a package), this returns the
  1998. sys.modules entry for foo.bar. If globals is from a package's __init__.py,
  1999. the package's entry in sys.modules is returned, as a borrowed reference.
  2000. The *name* of the returned package is returned in buf, with the length of
  2001. the name in *p_buflen.
  2002. If globals doesn't come from a package or a module in a package, or a
  2003. corresponding entry is not found in sys.modules, Py_None is returned.
  2004. */
  2005. static PyObject *
  2006. get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
  2007. {
  2008. static PyObject *namestr = NULL;
  2009. static PyObject *pathstr = NULL;
  2010. static PyObject *pkgstr = NULL;
  2011. PyObject *pkgname, *modname, *modpath, *modules, *parent;
  2012. int orig_level = level;
  2013. if (globals == NULL || !PyDict_Check(globals) || !level)
  2014. return Py_None;
  2015. if (namestr == NULL) {
  2016. namestr = PyString_InternFromString("__name__");
  2017. if (namestr == NULL)
  2018. return NULL;
  2019. }
  2020. if (pathstr == NULL) {
  2021. pathstr = PyString_InternFromString("__path__");
  2022. if (pathstr == NULL)
  2023. return NULL;
  2024. }
  2025. if (pkgstr == NULL) {
  2026. pkgstr = PyString_InternFromString("__package__");
  2027. if (pkgstr == NULL)
  2028. return NULL;
  2029. }
  2030. *buf = '\0';
  2031. *p_buflen = 0;
  2032. pkgname = PyDict_GetItem(globals, pkgstr);
  2033. if ((pkgname != NULL) && (pkgname != Py_None)) {
  2034. /* __package__ is set, so use it */
  2035. Py_ssize_t len;
  2036. if (!PyString_Check(pkgname)) {
  2037. PyErr_SetString(PyExc_ValueError,
  2038. "__package__ set to non-string");
  2039. return NULL;
  2040. }
  2041. len = PyString_GET_SIZE(pkgname);
  2042. if (len == 0) {
  2043. if (level > 0) {
  2044. PyErr_SetString(PyExc_ValueError,
  2045. "Attempted relative import in non-package");
  2046. return NULL;
  2047. }
  2048. return Py_None;
  2049. }
  2050. if (len > MAXPATHLEN) {
  2051. PyErr_SetString(PyExc_ValueError,
  2052. "Package name too long");
  2053. return NULL;
  2054. }
  2055. strcpy(buf, PyString_AS_STRING(pkgname));
  2056. } else {
  2057. /* __package__ not set, so figure it out and set it */
  2058. modname = PyDict_GetItem(globals, namestr);
  2059. if (modname == NULL || !PyString_Check(modname))
  2060. return Py_None;
  2061. modpath = PyDict_GetItem(globals, pathstr);
  2062. if (modpath != NULL) {
  2063. /* __path__ is set, so modname is already the package name */
  2064. Py_ssize_t len = PyString_GET_SIZE(modname);
  2065. int error;
  2066. if (len > MAXPATHLEN) {
  2067. PyErr_SetString(PyExc_ValueError,
  2068. "Module name too long");
  2069. return NULL;
  2070. }
  2071. strcpy(buf, PyString_AS_STRING(modname));
  2072. error = PyDict_SetItem(globals, pkgstr, modname);
  2073. if (error) {
  2074. PyErr_SetString(PyExc_ValueError,
  2075. "Could not set __package__");
  2076. return NULL;
  2077. }
  2078. } else {
  2079. /* Normal module, so work out the package name if any */
  2080. char *start = PyString_AS_STRING(modname);
  2081. char *lastdot = strrchr(start, '.');
  2082. size_t len;
  2083. int error;
  2084. if (lastdot == NULL && level > 0) {
  2085. PyErr_SetString(PyExc_ValueError,
  2086. "Attempted relative import in non-package");
  2087. return NULL;
  2088. }
  2089. if (lastdot == NULL) {
  2090. error = PyDict_SetItem(globals, pkgstr, Py_None);
  2091. if (error) {
  2092. PyErr_SetString(PyExc_ValueError,
  2093. "Could not set __package__");
  2094. return NULL;
  2095. }
  2096. return Py_None;
  2097. }
  2098. len = lastdot - start;
  2099. if (len >= MAXPATHLEN) {
  2100. PyErr_SetString(PyExc_ValueError,
  2101. "Module name too long");
  2102. return NULL;
  2103. }
  2104. strncpy(buf, start, len);
  2105. buf[len] = '\0';
  2106. pkgname = PyString_FromString(buf);
  2107. if (pkgname == NULL) {
  2108. return NULL;
  2109. }
  2110. error = PyDict_SetItem(globals, pkgstr, pkgname);
  2111. Py_DECREF(pkgname);
  2112. if (error) {
  2113. PyErr_SetString(PyExc_ValueError,
  2114. "Could not set __package__");
  2115. return NULL;
  2116. }
  2117. }
  2118. }
  2119. while (--level > 0) {
  2120. char *dot = strrchr(buf, '.');
  2121. if (dot == NULL) {
  2122. PyErr_SetString(PyExc_ValueError,
  2123. "Attempted relative import beyond "
  2124. "toplevel package");
  2125. return NULL;
  2126. }
  2127. *dot = '\0';
  2128. }
  2129. *p_buflen = strlen(buf);
  2130. modules = PyImport_GetModuleDict();
  2131. parent = PyDict_GetItemString(modules, buf);
  2132. if (parent == NULL) {
  2133. if (orig_level < 1) {
  2134. PyObject *err_msg = PyString_FromFormat(
  2135. "Parent module '%.200s' not found "
  2136. "while handling absolute import", buf);
  2137. if (err_msg == NULL) {
  2138. return NULL;
  2139. }
  2140. if (!PyErr_WarnEx(PyExc_RuntimeWarning,
  2141. PyString_AsString(err_msg), 1)) {
  2142. *buf = '\0';
  2143. *p_buflen = 0;
  2144. parent = Py_None;
  2145. }
  2146. Py_DECREF(err_msg);
  2147. } else {
  2148. PyErr_Format(PyExc_SystemError,
  2149. "Parent module '%.200s' not loaded, "
  2150. "cannot perform relative import", buf);
  2151. }
  2152. }
  2153. return parent;
  2154. /* We expect, but can't guarantee, if parent != None, that:
  2155. - parent.__name__ == buf
  2156. - parent.__dict__ is globals
  2157. If this is violated... Who cares? */
  2158. }
  2159. /* altmod is either None or same as mod */
  2160. static PyObject *
  2161. load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
  2162. Py_ssize_t *p_buflen)
  2163. {
  2164. char *name = *p_name;
  2165. char *dot = strchr(name, '.');
  2166. size_t len;
  2167. char *p;
  2168. PyObject *result;
  2169. if (strlen(name) == 0) {
  2170. /* completely empty module name should only happen in
  2171. 'from . import' (or '__import__("")')*/
  2172. Py_INCREF(mod);
  2173. *p_name = NULL;
  2174. return mod;
  2175. }
  2176. if (dot == NULL) {
  2177. *p_name = NULL;
  2178. len = strlen(name);
  2179. }
  2180. else {
  2181. *p_name = dot+1;
  2182. len = dot-name;
  2183. }
  2184. if (len == 0) {
  2185. PyErr_SetString(PyExc_ValueError,
  2186. "Empty module name");
  2187. return NULL;
  2188. }
  2189. p = buf + *p_buflen;
  2190. if (p != buf)
  2191. *p++ = '.';
  2192. if (p+len-buf >= MAXPATHLEN) {
  2193. PyErr_SetString(PyExc_ValueError,
  2194. "Module name too long");
  2195. return NULL;
  2196. }
  2197. strncpy(p, name, len);
  2198. p[len] = '\0';
  2199. *p_buflen = p+len-buf;
  2200. result = import_submodule(mod, p, buf);
  2201. if (result == Py_None && altmod != mod) {
  2202. Py_DECREF(result);
  2203. /* Here, altmod must be None and mod must not be None */
  2204. result = import_submodule(altmod, p, p);
  2205. if (result != NULL && result != Py_None) {
  2206. if (mark_miss(buf) != 0) {
  2207. Py_DECREF(result);
  2208. return NULL;
  2209. }
  2210. strncpy(buf, name, len);
  2211. buf[len] = '\0';
  2212. *p_buflen = len;
  2213. }
  2214. }
  2215. if (result == NULL)
  2216. return NULL;
  2217. if (result == Py_None) {
  2218. Py_DECREF(result);
  2219. PyErr_Format(PyExc_ImportError,
  2220. "No module named %.200s", name);
  2221. return NULL;
  2222. }
  2223. return result;
  2224. }
  2225. static int
  2226. mark_miss(char *name)
  2227. {
  2228. PyObject *modules = PyImport_GetModuleDict();
  2229. return PyDict_SetItemString(modules, name, Py_None);
  2230. }
  2231. static int
  2232. ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
  2233. int recursive)
  2234. {
  2235. int i;
  2236. if (!PyObject_HasAttrString(mod, "__path__"))
  2237. return 1;
  2238. for (i = 0; ; i++) {
  2239. PyObject *item = PySequence_GetItem(fromlist, i);
  2240. int hasit;
  2241. if (item == NULL) {
  2242. if (PyErr_ExceptionMatches(PyExc_IndexError)) {
  2243. PyErr_Clear();
  2244. return 1;
  2245. }
  2246. return 0;
  2247. }
  2248. if (!PyString_Check(item)) {
  2249. PyErr_SetString(PyExc_TypeError,
  2250. "Item in ``from list'' not a string");
  2251. Py_DECREF(item);
  2252. return 0;
  2253. }
  2254. if (PyString_AS_STRING(item)[0] == '*') {
  2255. PyObject *all;
  2256. Py_DECREF(item);
  2257. /* See if the package defines __all__ */
  2258. if (recursive)
  2259. continue; /* Avoid endless recursion */
  2260. all = PyObject_GetAttrString(mod, "__all__");
  2261. if (all == NULL)
  2262. PyErr_Clear();
  2263. else {
  2264. int ret = ensure_fromlist(mod, all, buf, buflen, 1);
  2265. Py_DECREF(all);
  2266. if (!ret)
  2267. return 0;
  2268. }
  2269. continue;
  2270. }
  2271. hasit = PyObject_HasAttr(mod, item);
  2272. if (!hasit) {
  2273. char *subname = PyString_AS_STRING(item);
  2274. PyObject *submod;
  2275. char *p;
  2276. if (buflen + strlen(subname) >= MAXPATHLEN) {
  2277. PyErr_SetString(PyExc_ValueError,
  2278. "Module name too long");
  2279. Py_DECREF(item);
  2280. return 0;
  2281. }
  2282. p = buf + buflen;
  2283. *p++ = '.';
  2284. strcpy(p, subname);
  2285. submod = import_submodule(mod, subname, buf);
  2286. Py_XDECREF(submod);
  2287. if (submod == NULL) {
  2288. Py_DECREF(item);
  2289. return 0;
  2290. }
  2291. }
  2292. Py_DECREF(item);
  2293. }
  2294. /* NOTREACHED */
  2295. }
  2296. static int
  2297. add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
  2298. PyObject *modules)
  2299. {
  2300. if (mod == Py_None)
  2301. return 1;
  2302. /* Irrespective of the success of this load, make a
  2303. reference to it in the parent package module. A copy gets
  2304. saved in the modules dictionary under the full name, so get a
  2305. reference from there, if need be. (The exception is when the
  2306. load failed with a SyntaxError -- then there's no trace in
  2307. sys.modules. In that case, of course, do nothing extra.) */
  2308. if (submod == NULL) {
  2309. submod = PyDict_GetItemString(modules, fullname);
  2310. if (submod == NULL)
  2311. return 1;
  2312. }
  2313. if (PyModule_Check(mod)) {
  2314. /* We can't use setattr here since it can give a
  2315. * spurious warning if the submodule name shadows a
  2316. * builtin name */
  2317. PyObject *dict = PyModule_GetDict(mod);
  2318. if (!dict)
  2319. return 0;
  2320. if (PyDict_SetItemString(dict, subname, submod) < 0)
  2321. return 0;
  2322. }
  2323. else {
  2324. if (PyObject_SetAttrString(mod, subname, submod) < 0)
  2325. return 0;
  2326. }
  2327. return 1;
  2328. }
  2329. static PyObject *
  2330. import_submodule(PyObject *mod, char *subname, char *fullname)
  2331. {
  2332. PyObject *modules = PyImport_GetModuleDict();
  2333. PyObject *m = NULL;
  2334. /* Require:
  2335. if mod == None: subname == fullname
  2336. else: mod.__name__ + "." + subname == fullname
  2337. */
  2338. if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
  2339. Py_INCREF(m);
  2340. }
  2341. else {
  2342. PyObject *path, *loader = NULL;
  2343. char *buf;
  2344. struct filedescr *fdp;
  2345. FILE *fp = NULL;
  2346. if (mod == Py_None)
  2347. path = NULL;
  2348. else {
  2349. path = PyObject_GetAttrString(mod, "__path__");
  2350. if (path == NULL) {
  2351. PyErr_Clear();
  2352. Py_INCREF(Py_None);
  2353. return Py_None;
  2354. }
  2355. }
  2356. buf = PyMem_MALLOC(MAXPATHLEN+1);
  2357. if (buf == NULL) {
  2358. return PyErr_NoMemory();
  2359. }
  2360. buf[0] = '\0';
  2361. fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
  2362. &fp, &loader);
  2363. Py_XDECREF(path);
  2364. if (fdp == NULL) {
  2365. PyMem_FREE(buf);
  2366. if (!PyErr_ExceptionMatches(PyExc_ImportError))
  2367. return NULL;
  2368. PyErr_Clear();
  2369. Py_INCREF(Py_None);
  2370. return Py_None;
  2371. }
  2372. m = load_module(fullname, fp, buf, fdp->type, loader);
  2373. Py_XDECREF(loader);
  2374. if (fp)
  2375. fclose(fp);
  2376. if (!add_submodule(mod, m, fullname, subname, modules)) {
  2377. Py_XDECREF(m);
  2378. m = NULL;
  2379. }
  2380. PyMem_FREE(buf);
  2381. }
  2382. return m;
  2383. }
  2384. /* Re-import a module of any kind and return its module object, WITH
  2385. INCREMENTED REFERENCE COUNT */
  2386. PyObject *
  2387. PyImport_ReloadModule(PyObject *m)
  2388. {
  2389. PyInterpreterState *interp = PyThreadState_Get()->interp;
  2390. PyObject *modules_reloading = interp->modules_reloading;
  2391. PyObject *modules = PyImport_GetModuleDict();
  2392. PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
  2393. char *name, *subname;
  2394. char *buf;
  2395. struct filedescr *fdp;
  2396. FILE *fp = NULL;
  2397. PyObject *newm;
  2398. if (modules_reloading == NULL) {
  2399. Py_FatalError("PyImport_ReloadModule: "
  2400. "no modules_reloading dictionary!");
  2401. return NULL;
  2402. }
  2403. if (m == NULL || !PyModule_Check(m)) {
  2404. PyErr_SetString(PyExc_TypeError,
  2405. "reload() argument must be module");
  2406. return NULL;
  2407. }
  2408. name = PyModule_GetName(m);
  2409. if (name == NULL)
  2410. return NULL;
  2411. if (m != PyDict_GetItemString(modules, name)) {
  2412. PyErr_Format(PyExc_ImportError,
  2413. "reload(): module %.200s not in sys.modules",
  2414. name);
  2415. return NULL;
  2416. }
  2417. existing_m = PyDict_GetItemString(modules_reloading, name);
  2418. if (existing_m != NULL) {
  2419. /* Due to a recursive reload, this module is already
  2420. being reloaded. */
  2421. Py_INCREF(existing_m);
  2422. return existing_m;
  2423. }
  2424. if (PyDict_SetItemString(modules_reloading, name, m) < 0)
  2425. return NULL;
  2426. subname = strrchr(name, '.');
  2427. if (subname == NULL)
  2428. subname = name;
  2429. else {
  2430. PyObject *parentname, *parent;
  2431. parentname = PyString_FromStringAndSize(name, (subname-name));
  2432. if (parentname == NULL) {
  2433. imp_modules_reloading_clear();
  2434. return NULL;
  2435. }
  2436. parent = PyDict_GetItem(modules, parentname);
  2437. if (parent == NULL) {
  2438. PyErr_Format(PyExc_ImportError,
  2439. "reload(): parent %.200s not in sys.modules",
  2440. PyString_AS_STRING(parentname));
  2441. Py_DECREF(parentname);
  2442. imp_modules_reloading_clear();
  2443. return NULL;
  2444. }
  2445. Py_DECREF(parentname);
  2446. subname++;
  2447. path = PyObject_GetAttrString(parent, "__path__");
  2448. if (path == NULL)
  2449. PyErr_Clear();
  2450. }
  2451. buf = PyMem_MALLOC(MAXPATHLEN+1);
  2452. if (buf == NULL) {
  2453. Py_XDECREF(path);
  2454. return PyErr_NoMemory();
  2455. }
  2456. buf[0] = '\0';
  2457. fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
  2458. Py_XDECREF(path);
  2459. if (fdp == NULL) {
  2460. Py_XDECREF(loader);
  2461. imp_modules_reloading_clear();
  2462. PyMem_FREE(buf);
  2463. return NULL;
  2464. }
  2465. newm = load_module(name, fp, buf, fdp->type, loader);
  2466. Py_XDECREF(loader);
  2467. if (fp)
  2468. fclose(fp);
  2469. if (newm == NULL) {
  2470. /* load_module probably removed name from modules because of
  2471. * the error. Put back the original module object. We're
  2472. * going to return NULL in this case regardless of whether
  2473. * replacing name succeeds, so the return value is ignored.
  2474. */
  2475. PyDict_SetItemString(modules, name, m);
  2476. }
  2477. imp_modules_reloading_clear();
  2478. PyMem_FREE(buf);
  2479. return newm;
  2480. }
  2481. /* Higher-level import emulator which emulates the "import" statement
  2482. more accurately -- it invokes the __import__() function from the
  2483. builtins of the current globals. This means that the import is
  2484. done using whatever import hooks are installed in the current
  2485. environment, e.g. by "rexec".
  2486. A dummy list ["__doc__"] is passed as the 4th argument so that
  2487. e.g. PyImport_Import(PyString_FromString("win32com.client.gencache"))
  2488. will return <module "gencache"> instead of <module "win32com">. */
  2489. PyObject *
  2490. PyImport_Import(PyObject *module_name)
  2491. {
  2492. static PyObject *silly_list = NULL;
  2493. static PyObject *builtins_str = NULL;
  2494. static PyObject *import_str = NULL;
  2495. PyObject *globals = NULL;
  2496. PyObject *import = NULL;
  2497. PyObject *builtins = NULL;
  2498. PyObject *r = NULL;
  2499. /* Initialize constant string objects */
  2500. if (silly_list == NULL) {
  2501. import_str = PyString_InternFromString("__import__");
  2502. if (import_str == NULL)
  2503. return NULL;
  2504. builtins_str = PyString_InternFromString("__builtins__");
  2505. if (builtins_str == NULL)
  2506. return NULL;
  2507. silly_list = Py_BuildValue("[s]", "__doc__");
  2508. if (silly_list == NULL)
  2509. return NULL;
  2510. }
  2511. /* Get the builtins from current globals */
  2512. globals = PyEval_GetGlobals();
  2513. if (globals != NULL) {
  2514. Py_INCREF(globals);
  2515. builtins = PyObject_GetItem(globals, builtins_str);
  2516. if (builtins == NULL)
  2517. goto err;
  2518. }
  2519. else {
  2520. /* No globals -- use standard builtins, and fake globals */
  2521. builtins = PyImport_ImportModuleLevel("__builtin__",
  2522. NULL, NULL, NULL, 0);
  2523. if (builtins == NULL)
  2524. return NULL;
  2525. globals = Py_BuildValue("{OO}", builtins_str, builtins);
  2526. if (globals == NULL)
  2527. goto err;
  2528. }
  2529. /* Get the __import__ function from the builtins */
  2530. if (PyDict_Check(builtins)) {
  2531. import = PyObject_GetItem(builtins, import_str);
  2532. if (import == NULL)
  2533. PyErr_SetObject(PyExc_KeyError, import_str);
  2534. }
  2535. else
  2536. import = PyObject_GetAttr(builtins, import_str);
  2537. if (import == NULL)
  2538. goto err;
  2539. /* Call the __import__ function with the proper argument list
  2540. * Always use absolute import here. */
  2541. r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
  2542. globals, silly_list, 0, NULL);
  2543. err:
  2544. Py_XDECREF(globals);
  2545. Py_XDECREF(builtins);
  2546. Py_XDECREF(import);
  2547. return r;
  2548. }
  2549. /* Module 'imp' provides Python access to the primitives used for
  2550. importing modules.
  2551. */
  2552. static PyObject *
  2553. imp_get_magic(PyObject *self, PyObject *noargs)
  2554. {
  2555. char buf[4];
  2556. buf[0] = (char) ((pyc_magic >> 0) & 0xff);
  2557. buf[1] = (char) ((pyc_magic >> 8) & 0xff);
  2558. buf[2] = (char) ((pyc_magic >> 16) & 0xff);
  2559. buf[3] = (char) ((pyc_magic >> 24) & 0xff);
  2560. return PyString_FromStringAndSize(buf, 4);
  2561. }
  2562. static PyObject *
  2563. imp_get_suffixes(PyObject *self, PyObject *noargs)
  2564. {
  2565. PyObject *list;
  2566. struct filedescr *fdp;
  2567. list = PyList_New(0);
  2568. if (list == NULL)
  2569. return NULL;
  2570. for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
  2571. PyObject *item = Py_BuildValue("ssi",
  2572. fdp->suffix, fdp->mode, fdp->type);
  2573. if (item == NULL) {
  2574. Py_DECREF(list);
  2575. return NULL;
  2576. }
  2577. if (PyList_Append(list, item) < 0) {
  2578. Py_DECREF(list);
  2579. Py_DECREF(item);
  2580. return NULL;
  2581. }
  2582. Py_DECREF(item);
  2583. }
  2584. return list;
  2585. }
  2586. static PyObject *
  2587. call_find_module(char *name, PyObject *path)
  2588. {
  2589. extern int fclose(FILE *);
  2590. PyObject *fob, *ret;
  2591. struct filedescr *fdp;
  2592. char *pathname;
  2593. FILE *fp = NULL;
  2594. pathname = PyMem_MALLOC(MAXPATHLEN+1);
  2595. if (pathname == NULL) {
  2596. return PyErr_NoMemory();
  2597. }
  2598. pathname[0] = '\0';
  2599. if (path == Py_None)
  2600. path = NULL;
  2601. fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
  2602. if (fdp == NULL) {
  2603. PyMem_FREE(pathname);
  2604. return NULL;
  2605. }
  2606. if (fp != NULL) {
  2607. fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
  2608. if (fob == NULL) {
  2609. PyMem_FREE(pathname);
  2610. return NULL;
  2611. }
  2612. }
  2613. else {
  2614. fob = Py_None;
  2615. Py_INCREF(fob);
  2616. }
  2617. ret = Py_BuildValue("Os(ssi)",
  2618. fob, pathname, fdp->suffix, fdp->mode, fdp->type);
  2619. Py_DECREF(fob);
  2620. PyMem_FREE(pathname);
  2621. return ret;
  2622. }
  2623. static PyObject *
  2624. imp_find_module(PyObject *self, PyObject *args)
  2625. {
  2626. char *name;
  2627. PyObject *path = NULL;
  2628. if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
  2629. return NULL;
  2630. return call_find_module(name, path);
  2631. }
  2632. static PyObject *
  2633. imp_init_builtin(PyObject *self, PyObject *args)
  2634. {
  2635. char *name;
  2636. int ret;
  2637. PyObject *m;
  2638. if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
  2639. return NULL;
  2640. ret = init_builtin(name);
  2641. if (ret < 0)
  2642. return NULL;
  2643. if (ret == 0) {
  2644. Py_INCREF(Py_None);
  2645. return Py_None;
  2646. }
  2647. m = PyImport_AddModule(name);
  2648. Py_XINCREF(m);
  2649. return m;
  2650. }
  2651. static PyObject *
  2652. imp_init_frozen(PyObject *self, PyObject *args)
  2653. {
  2654. char *name;
  2655. int ret;
  2656. PyObject *m;
  2657. if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
  2658. return NULL;
  2659. ret = PyImport_ImportFrozenModule(name);
  2660. if (ret < 0)
  2661. return NULL;
  2662. if (ret == 0) {
  2663. Py_INCREF(Py_None);
  2664. return Py_None;
  2665. }
  2666. m = PyImport_AddModule(name);
  2667. Py_XINCREF(m);
  2668. return m;
  2669. }
  2670. static PyObject *
  2671. imp_get_frozen_object(PyObject *self, PyObject *args)
  2672. {
  2673. char *name;
  2674. if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
  2675. return NULL;
  2676. return get_frozen_object(name);
  2677. }
  2678. static PyObject *
  2679. imp_is_builtin(PyObject *self, PyObject *args)
  2680. {
  2681. char *name;
  2682. if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
  2683. return NULL;
  2684. return PyInt_FromLong(is_builtin(name));
  2685. }
  2686. static PyObject *
  2687. imp_is_frozen(PyObject *self, PyObject *args)
  2688. {
  2689. char *name;
  2690. struct _frozen *p;
  2691. if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
  2692. return NULL;
  2693. p = find_frozen(name);
  2694. return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
  2695. }
  2696. static FILE *
  2697. get_file(char *pathname, PyObject *fob, char *mode)
  2698. {
  2699. FILE *fp;
  2700. if (fob == NULL) {
  2701. if (mode[0] == 'U')
  2702. mode = "r" PY_STDIOTEXTMODE;
  2703. fp = fopen(pathname, mode);
  2704. if (fp == NULL)
  2705. PyErr_SetFromErrno(PyExc_IOError);
  2706. }
  2707. else {
  2708. fp = PyFile_AsFile(fob);
  2709. if (fp == NULL)
  2710. PyErr_SetString(PyExc_ValueError,
  2711. "bad/closed file object");
  2712. }
  2713. return fp;
  2714. }
  2715. static PyObject *
  2716. imp_load_compiled(PyObject *self, PyObject *args)
  2717. {
  2718. char *name;
  2719. char *pathname;
  2720. PyObject *fob = NULL;
  2721. PyObject *m;
  2722. FILE *fp;
  2723. if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
  2724. &PyFile_Type, &fob))
  2725. return NULL;
  2726. fp = get_file(pathname, fob, "rb");
  2727. if (fp == NULL)
  2728. return NULL;
  2729. m = load_compiled_module(name, pathname, fp);
  2730. if (fob == NULL)
  2731. fclose(fp);
  2732. return m;
  2733. }
  2734. #ifdef HAVE_DYNAMIC_LOADING
  2735. static PyObject *
  2736. imp_load_dynamic(PyObject *self, PyObject *args)
  2737. {
  2738. char *name;
  2739. char *pathname;
  2740. PyObject *fob = NULL;
  2741. PyObject *m;
  2742. FILE *fp = NULL;
  2743. if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
  2744. &PyFile_Type, &fob))
  2745. return NULL;
  2746. if (fob) {
  2747. fp = get_file(pathname, fob, "r");
  2748. if (fp == NULL)
  2749. return NULL;
  2750. }
  2751. m = _PyImport_LoadDynamicModule(name, pathname, fp);
  2752. return m;
  2753. }
  2754. #endif /* HAVE_DYNAMIC_LOADING */
  2755. static PyObject *
  2756. imp_load_source(PyObject *self, PyObject *args)
  2757. {
  2758. char *name;
  2759. char *pathname;
  2760. PyObject *fob = NULL;
  2761. PyObject *m;
  2762. FILE *fp;
  2763. if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
  2764. &PyFile_Type, &fob))
  2765. return NULL;
  2766. fp = get_file(pathname, fob, "r");
  2767. if (fp == NULL)
  2768. return NULL;
  2769. m = load_source_module(name, pathname, fp);
  2770. if (fob == NULL)
  2771. fclose(fp);
  2772. return m;
  2773. }
  2774. static PyObject *
  2775. imp_load_module(PyObject *self, PyObject *args)
  2776. {
  2777. char *name;
  2778. PyObject *fob;
  2779. char *pathname;
  2780. char *suffix; /* Unused */
  2781. char *mode;
  2782. int type;
  2783. FILE *fp;
  2784. if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
  2785. &name, &fob, &pathname,
  2786. &suffix, &mode, &type))
  2787. return NULL;
  2788. if (*mode) {
  2789. /* Mode must start with 'r' or 'U' and must not contain '+'.
  2790. Implicit in this test is the assumption that the mode
  2791. may contain other modifiers like 'b' or 't'. */
  2792. if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
  2793. PyErr_Format(PyExc_ValueError,
  2794. "invalid file open mode %.200s", mode);
  2795. return NULL;
  2796. }
  2797. }
  2798. if (fob == Py_None)
  2799. fp = NULL;
  2800. else {
  2801. if (!PyFile_Check(fob)) {
  2802. PyErr_SetString(PyExc_ValueError,
  2803. "load_module arg#2 should be a file or None");
  2804. return NULL;
  2805. }
  2806. fp = get_file(pathname, fob, mode);
  2807. if (fp == NULL)
  2808. return NULL;
  2809. }
  2810. return load_module(name, fp, pathname, type, NULL);
  2811. }
  2812. static PyObject *
  2813. imp_load_package(PyObject *self, PyObject *args)
  2814. {
  2815. char *name;
  2816. char *pathname;
  2817. if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
  2818. return NULL;
  2819. return load_package(name, pathname);
  2820. }
  2821. static PyObject *
  2822. imp_new_module(PyObject *self, PyObject *args)
  2823. {
  2824. char *name;
  2825. if (!PyArg_ParseTuple(args, "s:new_module", &name))
  2826. return NULL;
  2827. return PyModule_New(name);
  2828. }
  2829. static PyObject *
  2830. imp_reload(PyObject *self, PyObject *v)
  2831. {
  2832. return PyImport_ReloadModule(v);
  2833. }
  2834. /* Doc strings */
  2835. PyDoc_STRVAR(doc_imp,
  2836. "This module provides the components needed to build your own\n\
  2837. __import__ function. Undocumented functions are obsolete.");
  2838. PyDoc_STRVAR(doc_reload,
  2839. "reload(module) -> module\n\
  2840. \n\
  2841. Reload the module. The module must have been successfully imported before.");
  2842. PyDoc_STRVAR(doc_find_module,
  2843. "find_module(name, [path]) -> (file, filename, (suffix, mode, type))\n\
  2844. Search for a module. If path is omitted or None, search for a\n\
  2845. built-in, frozen or special module and continue search in sys.path.\n\
  2846. The module name cannot contain '.'; to search for a submodule of a\n\
  2847. package, pass the submodule name and the package's __path__.");
  2848. PyDoc_STRVAR(doc_load_module,
  2849. "load_module(name, file, filename, (suffix, mode, type)) -> module\n\
  2850. Load a module, given information returned by find_module().\n\
  2851. The module name must include the full package name, if any.");
  2852. PyDoc_STRVAR(doc_get_magic,
  2853. "get_magic() -> string\n\
  2854. Return the magic number for .pyc or .pyo files.");
  2855. PyDoc_STRVAR(doc_get_suffixes,
  2856. "get_suffixes() -> [(suffix, mode, type), ...]\n\
  2857. Return a list of (suffix, mode, type) tuples describing the files\n\
  2858. that find_module() looks for.");
  2859. PyDoc_STRVAR(doc_new_module,
  2860. "new_module(name) -> module\n\
  2861. Create a new module. Do not enter it in sys.modules.\n\
  2862. The module name must include the full package name, if any.");
  2863. PyDoc_STRVAR(doc_lock_held,
  2864. "lock_held() -> boolean\n\
  2865. Return True if the import lock is currently held, else False.\n\
  2866. On platforms without threads, return False.");
  2867. PyDoc_STRVAR(doc_acquire_lock,
  2868. "acquire_lock() -> None\n\
  2869. Acquires the interpreter's import lock for the current thread.\n\
  2870. This lock should be used by import hooks to ensure thread-safety\n\
  2871. when importing modules.\n\
  2872. On platforms without threads, this function does nothing.");
  2873. PyDoc_STRVAR(doc_release_lock,
  2874. "release_lock() -> None\n\
  2875. Release the interpreter's import lock.\n\
  2876. On platforms without threads, this function does nothing.");
  2877. static PyMethodDef imp_methods[] = {
  2878. {"reload", imp_reload, METH_O, doc_reload},
  2879. {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
  2880. {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
  2881. {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
  2882. {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
  2883. {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
  2884. {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
  2885. {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
  2886. {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
  2887. /* The rest are obsolete */
  2888. {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
  2889. {"init_builtin", imp_init_builtin, METH_VARARGS},
  2890. {"init_frozen", imp_init_frozen, METH_VARARGS},
  2891. {"is_builtin", imp_is_builtin, METH_VARARGS},
  2892. {"is_frozen", imp_is_frozen, METH_VARARGS},
  2893. {"load_compiled", imp_load_compiled, METH_VARARGS},
  2894. #ifdef HAVE_DYNAMIC_LOADING
  2895. {"load_dynamic", imp_load_dynamic, METH_VARARGS},
  2896. #endif
  2897. {"load_package", imp_load_package, METH_VARARGS},
  2898. {"load_source", imp_load_source, METH_VARARGS},
  2899. {NULL, NULL} /* sentinel */
  2900. };
  2901. static int
  2902. setint(PyObject *d, char *name, int value)
  2903. {
  2904. PyObject *v;
  2905. int err;
  2906. v = PyInt_FromLong((long)value);
  2907. err = PyDict_SetItemString(d, name, v);
  2908. Py_XDECREF(v);
  2909. return err;
  2910. }
  2911. typedef struct {
  2912. PyObject_HEAD
  2913. } NullImporter;
  2914. static int
  2915. NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
  2916. {
  2917. char *path;
  2918. Py_ssize_t pathlen;
  2919. if (!_PyArg_NoKeywords("NullImporter()", kwds))
  2920. return -1;
  2921. if (!PyArg_ParseTuple(args, "s:NullImporter",
  2922. &path))
  2923. return -1;
  2924. pathlen = strlen(path);
  2925. if (pathlen == 0) {
  2926. PyErr_SetString(PyExc_ImportError, "empty pathname");
  2927. return -1;
  2928. } else {
  2929. if(isdir(path)) {
  2930. PyErr_SetString(PyExc_ImportError,
  2931. "existing directory");
  2932. return -1;
  2933. }
  2934. }
  2935. return 0;
  2936. }
  2937. static PyObject *
  2938. NullImporter_find_module(NullImporter *self, PyObject *args)
  2939. {
  2940. Py_RETURN_NONE;
  2941. }
  2942. static PyMethodDef NullImporter_methods[] = {
  2943. {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
  2944. "Always return None"
  2945. },
  2946. {NULL} /* Sentinel */
  2947. };
  2948. PyTypeObject PyNullImporter_Type = {
  2949. PyVarObject_HEAD_INIT(NULL, 0)
  2950. "imp.NullImporter", /*tp_name*/
  2951. sizeof(NullImporter), /*tp_basicsize*/
  2952. 0, /*tp_itemsize*/
  2953. 0, /*tp_dealloc*/
  2954. 0, /*tp_print*/
  2955. 0, /*tp_getattr*/
  2956. 0, /*tp_setattr*/
  2957. 0, /*tp_compare*/
  2958. 0, /*tp_repr*/
  2959. 0, /*tp_as_number*/
  2960. 0, /*tp_as_sequence*/
  2961. 0, /*tp_as_mapping*/
  2962. 0, /*tp_hash */
  2963. 0, /*tp_call*/
  2964. 0, /*tp_str*/
  2965. 0, /*tp_getattro*/
  2966. 0, /*tp_setattro*/
  2967. 0, /*tp_as_buffer*/
  2968. Py_TPFLAGS_DEFAULT, /*tp_flags*/
  2969. "Null importer object", /* tp_doc */
  2970. 0, /* tp_traverse */
  2971. 0, /* tp_clear */
  2972. 0, /* tp_richcompare */
  2973. 0, /* tp_weaklistoffset */
  2974. 0, /* tp_iter */
  2975. 0, /* tp_iternext */
  2976. NullImporter_methods, /* tp_methods */
  2977. 0, /* tp_members */
  2978. 0, /* tp_getset */
  2979. 0, /* tp_base */
  2980. 0, /* tp_dict */
  2981. 0, /* tp_descr_get */
  2982. 0, /* tp_descr_set */
  2983. 0, /* tp_dictoffset */
  2984. (initproc)NullImporter_init, /* tp_init */
  2985. 0, /* tp_alloc */
  2986. PyType_GenericNew /* tp_new */
  2987. };
  2988. PyMODINIT_FUNC
  2989. initimp(void)
  2990. {
  2991. PyObject *m, *d;
  2992. if (PyType_Ready(&PyNullImporter_Type) < 0)
  2993. goto failure;
  2994. m = Py_InitModule4("imp", imp_methods, doc_imp,
  2995. NULL, PYTHON_API_VERSION);
  2996. if (m == NULL)
  2997. goto failure;
  2998. d = PyModule_GetDict(m);
  2999. if (d == NULL)
  3000. goto failure;
  3001. if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
  3002. if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
  3003. if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
  3004. if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
  3005. if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
  3006. if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
  3007. if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
  3008. if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
  3009. if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
  3010. if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
  3011. Py_INCREF(&PyNullImporter_Type);
  3012. PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
  3013. failure:
  3014. ;
  3015. }
  3016. /* API for embedding applications that want to add their own entries
  3017. to the table of built-in modules. This should normally be called
  3018. *before* Py_Initialize(). When the table resize fails, -1 is
  3019. returned and the existing table is unchanged.
  3020. After a similar function by Just van Rossum. */
  3021. int
  3022. PyImport_ExtendInittab(struct _inittab *newtab)
  3023. {
  3024. static struct _inittab *our_copy = NULL;
  3025. struct _inittab *p;
  3026. int i, n;
  3027. /* Count the number of entries in both tables */
  3028. for (n = 0; newtab[n].name != NULL; n++)
  3029. ;
  3030. if (n == 0)
  3031. return 0; /* Nothing to do */
  3032. for (i = 0; PyImport_Inittab[i].name != NULL; i++)
  3033. ;
  3034. /* Allocate new memory for the combined table */
  3035. p = our_copy;
  3036. PyMem_RESIZE(p, struct _inittab, i+n+1);
  3037. if (p == NULL)
  3038. return -1;
  3039. /* Copy the tables into the new memory */
  3040. if (our_copy != PyImport_Inittab)
  3041. memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
  3042. PyImport_Inittab = our_copy = p;
  3043. memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
  3044. return 0;
  3045. }
  3046. /* Shorthand to add a single entry given a name and a function */
  3047. int
  3048. PyImport_AppendInittab(const char *name, void (*initfunc)(void))
  3049. {
  3050. struct _inittab newtab[2];
  3051. memset(newtab, '\0', sizeof newtab);
  3052. newtab[0].name = (char *)name;
  3053. newtab[0].initfunc = initfunc;
  3054. return PyImport_ExtendInittab(newtab);
  3055. }
  3056. #ifdef __cplusplus
  3057. }
  3058. #endif