cpython_sandbox / Python / importdl.c

/* Support for dynamic loading of extension modules */

#include "Python.h"

/* ./configure sets HAVE_DYNAMIC_LOADING if dynamic loading of modules is
   supported on this platform. configure will then compile and link in one
   of the dynload_*.c files, as appropriate. We will call a function in
   those modules to get a function pointer to the module's init function.
*/
#ifdef HAVE_DYNAMIC_LOADING

#include "importdl.h"

#ifdef MS_WINDOWS
extern dl_funcptr _PyImport_GetDynLoadWindows(const char *shortname,
                                              PyObject *pathname, FILE *fp);
#else
extern dl_funcptr _PyImport_GetDynLoadFunc(const char *shortname,
                                           const char *pathname, FILE *fp);
extern dl_funcptr _PyImport_GetImportExecFunc(const char *shortname,
                                              PyObject *path, FILE *fp,
                                              dl_funcptr *create_func);
#endif


/* Extension module names must be encodable to ASCII because dynamic
 * modules must have initialization functions including the name written
 * in C, and the C language doesn't accept non-ASCII identifiers.
 *
 * Extension module names also all share a single flat namespace, since
 * the initialization function names are based only on the final part of
 * the module name, without the name of the containing package.
 */
static PyObject *
_split_extension_module_name(PyObject *name,
                             char **shortname,
                             char **packagecontext)
{
    PyObject *nameascii;
    char *namestr, *lastdot;

    nameascii = PyUnicode_AsEncodedString(name, "ascii", NULL);
    if (nameascii == NULL)
        return NULL;

    namestr = PyBytes_AS_STRING(nameascii);
    if (namestr == NULL) {
        Py_DECREF(nameascii);
        return NULL;
    }

    lastdot = strrchr(namestr, '.');
    if (lastdot == NULL) {
        *packagecontext = NULL;
        *shortname = namestr;
    }
    else {
        *packagecontext = namestr;
        *shortname = lastdot+1;
    }

    return nameascii;
}

static PyObject *
_PyImport_CreateAndExecExtensionModule(PyObject *name,
                                       PyObject *path,
                                       FILE *fp)
{
    /* Alternative extension loading mechanism that creates the module
     * *first*, and then allows the extension module to initialize it
     *
     * Initial prototype is implemented in dynload_shlib only
     */
    dl_funcptr raw_exec_module, raw_create_module;
    int (*exec_module)(PyObject *);
    PyObject* m = NULL, *modules = NULL;
    PyObject *nameascii = NULL;
    char *shortname, *packagecontext;

    nameascii = _split_extension_module_name(name, &shortname,
                                             &packagecontext);
    if (nameascii == NULL)
        return NULL;

    raw_exec_module = _PyImport_GetImportExecFunc(shortname, path, fp,
                                                  &raw_create_module);
    if (raw_exec_module == NULL) {
        /* Not necessarily an error: fall back to the legacy API */
        Py_DECREF(nameascii);
        return NULL;
    }

    /* No support for create_module as yet, since that part depends on
     * the availability of PEP 451 ModuleSpec objects to pass into the
     * create_module call
     */
    if (raw_create_module != NULL) {
        PyObject *msg = PyUnicode_FromFormat("custom module creation hook "
                                             "(PyImportCreate_%s) not yet "
                                             "supported",
                                             shortname);
        if (msg == NULL)
            goto error;
        PyErr_SetImportError(msg, name, path);
        Py_DECREF(msg);
        goto error;
    } else {
        /* Create the module object */
        m = PyModule_NewObject(name);
        if (m == NULL) {
            goto error;
        }
    }

    /* Set standard attributes */
    if (PyObject_SetAttrString(m, "__file__", path) != 0) {
        goto error;
    }

    /* Add the module to sys.modules */
    modules = PyImport_GetModuleDict(); /* Borrowed ref */
    if (modules == NULL) {
        goto error;
    }
    if (PyDict_SetItem(modules, name, m) != 0) {
        goto error;
    }

    /* Initialize the module */
    exec_module = (int(*)(PyObject *))raw_exec_module;
    if ((*exec_module)(m) != 0) {
        goto error;
    }


    Py_DECREF(nameascii);
    return m;

error:
    Py_DECREF(nameascii);
    Py_XDECREF(m);
    return NULL;
}

PyObject *
_PyImport_LoadDynamicModule(PyObject *name, PyObject *path, FILE *fp)
{
    PyObject *m = NULL;
#ifndef MS_WINDOWS
    PyObject *pathbytes;
#endif
    PyObject *nameascii;
    char *shortname, *packagecontext, *oldcontext;
    dl_funcptr p0;
    PyObject* (*p)(void);
    struct PyModuleDef *def;

    m = _PyImport_FindExtensionObject(name, path);
    if (m != NULL) {
        Py_INCREF(m);
        return m;
    }

    /* Look for PyImportExec before falling back to legacy initialization */
    m = _PyImport_CreateAndExecExtensionModule(name, path, fp);
    if (m != NULL) {
        return m;
    }
    /* Continue to legacy import only if the new hooks weren't even tried */
    if (PyErr_Occurred())
        return NULL;

    nameascii = _split_extension_module_name(name, &shortname,
                                             &packagecontext);
    if (nameascii == NULL)
        return NULL;

#ifdef MS_WINDOWS
    p0 = _PyImport_GetDynLoadWindows(shortname, path, fp);
#else
    pathbytes = PyUnicode_EncodeFSDefault(path);
    if (pathbytes == NULL)
        goto error;
    p0 = _PyImport_GetDynLoadFunc(shortname,
                                  PyBytes_AS_STRING(pathbytes), fp);
    Py_DECREF(pathbytes);
#endif
    p = (PyObject*(*)(void))p0;
    if (PyErr_Occurred())
        goto error;
    if (p == NULL) {
        PyObject *msg = PyUnicode_FromFormat("extension module does not "
                                             "define an init (PyInit_%s) or "
                                             "exec function "
                                             "(PyImportExec_%s)",
                                             shortname, shortname);
        if (msg == NULL)
            goto error;
        PyErr_SetImportError(msg, name, path);
        Py_DECREF(msg);
        goto error;
    }
    oldcontext = _Py_PackageContext;
    _Py_PackageContext = packagecontext;
    m = (*p)();
    _Py_PackageContext = oldcontext;
    if (m == NULL)
        goto error;

    if (PyErr_Occurred()) {
        PyErr_Format(PyExc_SystemError,
                     "initialization of %s raised unreported exception",
                     shortname);
        goto error;
    }

    /* Remember pointer to module init function. */
    def = PyModule_GetDef(m);
    if (def == NULL) {
        PyErr_Format(PyExc_SystemError,
                     "initialization of %s did not return an extension "
                     "module", shortname);
        goto error;
    }
    def->m_base.m_init = p;

    /* Remember the filename as the __file__ attribute */
    if (PyModule_AddObject(m, "__file__", path) < 0)
        PyErr_Clear(); /* Not important enough to report */
    else
        Py_INCREF(path);

    if (_PyImport_FixupExtensionObject(m, name, path) < 0)
        goto error;
    Py_DECREF(nameascii);
    return m;

error:
    Py_DECREF(nameascii);
    Py_XDECREF(m);
    return NULL;
}

#endif /* HAVE_DYNAMIC_LOADING */
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.