importdl.c 7.15 KB
Newer Older
1 2 3

/* Support for dynamic loading of extension modules */

4
#include "Python.h"
5

6 7 8 9
/* ./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.
10
*/
11
#ifdef HAVE_DYNAMIC_LOADING
12

13 14
#include "importdl.h"

15
#ifdef MS_WINDOWS
16 17 18 19
extern dl_funcptr _PyImport_FindSharedFuncptrWindows(const char *prefix,
                                                     const char *shortname,
                                                     PyObject *pathname,
                                                     FILE *fp);
20
#else
21 22 23
extern dl_funcptr _PyImport_FindSharedFuncptr(const char *prefix,
                                              const char *shortname,
                                              const char *pathname, FILE *fp);
24
#endif
25

26 27
static const char * const ascii_only_prefix = "PyInit";
static const char * const nonascii_prefix = "PyInitU";
28 29 30 31 32 33 34 35 36 37 38

/* Get the variable part of a module's export symbol name.
 * Returns a bytes instance. For non-ASCII-named modules, the name is
 * encoded as per PEP 489.
 * The hook_prefix pointer is set to either ascii_only_prefix or
 * nonascii_prefix, as appropriate.
 */
static PyObject *
get_encoded_name(PyObject *name, const char **hook_prefix) {
    PyObject *tmp;
    PyObject *encoded = NULL;
39 40 41
    PyObject *modname = NULL;
    Py_ssize_t name_len, lastdot;
    _Py_IDENTIFIER(replace);
42 43 44 45 46 47 48

    /* Get the short name (substring after last dot) */
    name_len = PyUnicode_GetLength(name);
    lastdot = PyUnicode_FindChar(name, '.', 0, name_len, -1);
    if (lastdot < -1) {
        return NULL;
    } else if (lastdot >= 0) {
49
        tmp = PyUnicode_Substring(name, lastdot + 1, name_len);
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
        if (tmp == NULL)
            return NULL;
        name = tmp;
        /* "name" now holds a new reference to the substring */
    } else {
        Py_INCREF(name);
    }

    /* Encode to ASCII or Punycode, as needed */
    encoded = PyUnicode_AsEncodedString(name, "ascii", NULL);
    if (encoded != NULL) {
        *hook_prefix = ascii_only_prefix;
    } else {
        if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
            PyErr_Clear();
            encoded = PyUnicode_AsEncodedString(name, "punycode", NULL);
            if (encoded == NULL) {
                goto error;
            }
            *hook_prefix = nonascii_prefix;
        } else {
            goto error;
        }
    }

75 76 77 78
    /* Replace '-' by '_' */
    modname = _PyObject_CallMethodId(encoded, &PyId_replace, "cc", '-', '_');
    if (modname == NULL)
        goto error;
79 80

    Py_DECREF(name);
81 82
    Py_DECREF(encoded);
    return modname;
83 84 85 86 87 88
error:
    Py_DECREF(name);
    Py_XDECREF(encoded);
    return NULL;
}

89
PyObject *
90
_PyImport_LoadDynamicModuleWithSpec(PyObject *spec, FILE *fp)
91
{
92
#ifndef MS_WINDOWS
93
    PyObject *pathbytes = NULL;
94
#endif
95 96
    PyObject *name_unicode = NULL, *name = NULL, *path = NULL, *m = NULL;
    const char *name_buf, *hook_prefix;
97
    const char *oldcontext;
98 99 100 101 102 103
    dl_funcptr exportfunc;
    PyModuleDef *def;
    PyObject *(*p0)(void);

    name_unicode = PyObject_GetAttrString(spec, "name");
    if (name_unicode == NULL) {
104
        return NULL;
105
    }
106 107 108 109 110
    if (!PyUnicode_Check(name_unicode)) {
        PyErr_SetString(PyExc_TypeError,
                        "spec.name must be a string");
        goto error;
    }
111

112 113
    name = get_encoded_name(name_unicode, &hook_prefix);
    if (name == NULL) {
114
        goto error;
115
    }
116 117 118 119 120
    name_buf = PyBytes_AS_STRING(name);

    path = PyObject_GetAttrString(spec, "origin");
    if (path == NULL)
        goto error;
121

122
#ifdef MS_WINDOWS
123 124
    exportfunc = _PyImport_FindSharedFuncptrWindows(hook_prefix, name_buf,
                                                    path, fp);
125
#else
126 127
    pathbytes = PyUnicode_EncodeFSDefault(path);
    if (pathbytes == NULL)
128
        goto error;
129 130 131
    exportfunc = _PyImport_FindSharedFuncptr(hook_prefix, name_buf,
                                             PyBytes_AS_STRING(pathbytes),
                                             fp);
132
    Py_DECREF(pathbytes);
133
#endif
134 135 136 137 138 139 140 141 142 143 144 145 146

    if (exportfunc == NULL) {
        if (!PyErr_Occurred()) {
            PyObject *msg;
            msg = PyUnicode_FromFormat(
                "dynamic module does not define "
                "module export function (%s_%s)",
                hook_prefix, name_buf);
            if (msg == NULL)
                goto error;
            PyErr_SetImportError(msg, name_unicode, path);
            Py_DECREF(msg);
        }
147
        goto error;
148
    }
149 150 151 152

    p0 = (PyObject *(*)(void))exportfunc;

    /* Package context is needed for single-phase init */
153
    oldcontext = _Py_PackageContext;
154
    _Py_PackageContext = PyUnicode_AsUTF8(name_unicode);
155 156 157 158
    if (_Py_PackageContext == NULL) {
        _Py_PackageContext = oldcontext;
        goto error;
    }
159
    m = p0();
160
    _Py_PackageContext = oldcontext;
161

162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
    if (m == NULL) {
        if (!PyErr_Occurred()) {
            PyErr_Format(
                PyExc_SystemError,
                "initialization of %s failed without raising an exception",
                name_buf);
        }
        goto error;
    } else if (PyErr_Occurred()) {
        PyErr_Clear();
        PyErr_Format(
            PyExc_SystemError,
            "initialization of %s raised unreported exception",
            name_buf);
        m = NULL;
        goto error;
    }
    if (Py_TYPE(m) == NULL) {
        /* This can happen when a PyModuleDef is returned without calling
         * PyModuleDef_Init on it
         */
183
        PyErr_Format(PyExc_SystemError,
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
                     "init function of %s returned uninitialized object",
                     name_buf);
        m = NULL; /* prevent segfault in DECREF */
        goto error;
    }
    if (PyObject_TypeCheck(m, &PyModuleDef_Type)) {
        Py_DECREF(name_unicode);
        Py_DECREF(name);
        Py_DECREF(path);
        return PyModule_FromDefAndSpec((PyModuleDef*)m, spec);
    }

    /* Fall back to single-phase init mechanism */

    if (hook_prefix == nonascii_prefix) {
        /* don't allow legacy init for non-ASCII module names */
        PyErr_Format(
            PyExc_SystemError,
            "initialization of * did not return PyModuleDef",
            name_buf);
204
        goto error;
205
    }
206

207 208
    /* Remember pointer to module init function. */
    def = PyModule_GetDef(m);
209 210 211
    if (def == NULL) {
        PyErr_Format(PyExc_SystemError,
                     "initialization of %s did not return an extension "
212
                     "module", name_buf);
213
        goto error;
214
    }
215
    def->m_base.m_init = p0;
216

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

223 224
    PyObject *modules = PyImport_GetModuleDict();
    if (_PyImport_FixupExtensionObject(m, name_unicode, path, modules) < 0)
225
        goto error;
226 227 228 229 230

    Py_DECREF(name_unicode);
    Py_DECREF(name);
    Py_DECREF(path);

231
    return m;
232 233

error:
234 235 236
    Py_DECREF(name_unicode);
    Py_XDECREF(name);
    Py_XDECREF(path);
237 238
    Py_XDECREF(m);
    return NULL;
239
}
240 241

#endif /* HAVE_DYNAMIC_LOADING */