Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/importdl.c
Line
Count
Source
1
2
/* Support for dynamic loading of extension modules */
3
4
#include "Python.h"
5
#include "pycore_call.h"          // _PyObject_CallMethod()
6
#include "pycore_import.h"        // _PyImport_SwapPackageContext()
7
#include "pycore_importdl.h"
8
#include "pycore_moduleobject.h"  // _PyModule_GetDefOrNull()
9
#include "pycore_pyerrors.h"      // _PyErr_FormatFromCause()
10
#include "pycore_runtime.h"       // _Py_ID()
11
#include "pycore_global_objects.h"  // _Py_SINGLETON()
12
#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
13
14
15
/***********************************/
16
/* module info to use when loading */
17
/***********************************/
18
19
static const struct hook_prefixes ascii_only_prefixes = {
20
    "PyInit", "PyModExport"};
21
static const struct hook_prefixes nonascii_prefixes = {
22
    "PyInitU", "PyModExportU"};
23
24
/* Get the variable part of a module's export symbol name.
25
 * Returns a bytes instance. For non-ASCII-named modules, the name is
26
 * encoded as per PEP 489.
27
 * The hook_prefix pointer is set to either ascii_only_prefix or
28
 * nonascii_prefix, as appropriate.
29
 */
30
static PyObject *
31
972
get_encoded_name(PyObject *name, const struct hook_prefixes **hook_prefixes) {
32
972
    PyObject *tmp;
33
972
    Py_ssize_t name_len, lastdot;
34
35
    /* Get the short name (substring after last dot) */
36
972
    name_len = PyUnicode_GetLength(name);
37
972
    if (name_len < 0) {
38
0
        return NULL;
39
0
    }
40
972
    lastdot = PyUnicode_FindChar(name, '.', 0, name_len, -1);
41
972
    if (lastdot < -1) {
42
0
        return NULL;
43
972
    } else if (lastdot >= 0) {
44
4
        tmp = PyUnicode_Substring(name, lastdot + 1, name_len);
45
4
        if (tmp == NULL)
46
0
            return NULL;
47
4
        name = tmp;
48
        /* "name" now holds a new reference to the substring */
49
968
    } else {
50
968
        Py_INCREF(name);
51
968
    }
52
53
    /* Encode to ASCII or Punycode, as needed */
54
972
    PyObject *encoded;
55
972
    if (PyUnicode_IS_ASCII(name)) {
56
972
        *hook_prefixes = &ascii_only_prefixes;
57
972
        encoded = PyUnicode_AsASCIIString(name);
58
972
    } else {
59
0
        *hook_prefixes = &nonascii_prefixes;
60
0
        encoded = PyUnicode_AsEncodedString(name, "punycode", NULL);
61
0
    }
62
972
    if (encoded == NULL) {
63
0
        goto error;
64
0
    }
65
66
    /* Call encoded.replace('-', '_') */
67
972
    PyObject *modname = PyObject_VectorcallMethod(
68
972
        &_Py_ID(replace),
69
972
        (PyObject*[3]) {
70
972
            encoded,
71
972
            (PyObject *)&_Py_SINGLETON(bytes_characters)['-'],
72
972
            (PyObject *)&_Py_SINGLETON(bytes_characters)['_'],
73
972
        },
74
972
        3 | PY_VECTORCALL_ARGUMENTS_OFFSET,
75
972
        NULL);
76
972
    Py_CLEAR(encoded);
77
78
972
    if (modname == NULL) {
79
0
        goto error;
80
0
    }
81
82
972
    Py_DECREF(name);
83
972
    return modname;
84
0
error:
85
0
    Py_DECREF(name);
86
0
    return NULL;
87
972
}
88
89
void
90
_Py_ext_module_loader_info_clear(struct _Py_ext_module_loader_info *info)
91
972
{
92
972
    Py_CLEAR(info->filename);
93
972
#ifndef MS_WINDOWS
94
972
    Py_CLEAR(info->filename_encoded);
95
972
#endif
96
972
    Py_CLEAR(info->name);
97
972
    Py_CLEAR(info->name_encoded);
98
972
}
99
100
int
101
_Py_ext_module_loader_info_init(struct _Py_ext_module_loader_info *p_info,
102
                                PyObject *name,
103
                                PyObject *spec,
104
                                _Py_ext_module_origin origin)
105
972
{
106
972
    struct _Py_ext_module_loader_info info = {
107
972
        .origin=origin,
108
972
    };
109
110
972
    if (name == NULL) {
111
935
        assert(spec != NULL);
112
935
        info.name = PyObject_GetAttr(spec, &_Py_ID(name));
113
935
        if (info.name == NULL) {
114
0
            goto error;
115
0
        }
116
935
    }
117
37
    else {
118
37
        info.name = Py_NewRef(name);
119
37
    }
120
121
972
    if (!PyUnicode_Check(info.name)) {
122
0
        PyErr_Format(PyExc_TypeError,
123
0
                     "module name must be a string, not %T",
124
0
                     info.name);
125
0
        goto error;
126
0
    }
127
128
972
    if (PyUnicode_GetLength(info.name) == 0) {
129
0
        PyErr_Format(PyExc_ValueError, "module name must not be empty");
130
0
        goto error;
131
0
    }
132
133
972
    info.name_encoded = get_encoded_name(info.name, &info.hook_prefixes);
134
972
    if (info.name_encoded == NULL) {
135
0
        goto error;
136
0
    }
137
138
972
    info.newcontext = _PyUnicode_AsUTF8NoNUL(info.name);
139
972
    if (info.newcontext == NULL) {
140
0
        goto error;
141
0
    }
142
143
972
    if (origin == _Py_ext_module_origin_DYNAMIC) {
144
219
        assert(spec != NULL);
145
219
        info.filename = PyObject_GetAttr(spec, &_Py_ID(origin));
146
219
        if (info.filename == NULL) {
147
0
            goto error;
148
0
        }
149
150
219
        if (!PyUnicode_Check(info.filename)) {
151
0
            PyErr_SetString(PyExc_TypeError,
152
0
                            "module filename must be a string");
153
0
            goto error;
154
0
        }
155
219
        if (PyUnicode_FindChar(info.filename, 0, 0,
156
219
                               PyUnicode_GET_LENGTH(info.filename), 1) != -1) {
157
0
            PyErr_SetString(PyExc_ValueError, "embedded null character");
158
0
            goto error;
159
0
        }
160
161
219
#ifndef MS_WINDOWS
162
219
        info.filename_encoded = PyUnicode_EncodeFSDefault(info.filename);
163
219
        if (info.filename_encoded == NULL) {
164
0
            goto error;
165
0
        }
166
219
#endif
167
168
219
        info.path = info.filename;
169
219
    }
170
753
    else {
171
753
        info.filename = NULL;
172
753
        info.path = info.name;
173
753
    }
174
175
972
    *p_info = info;
176
972
    return 0;
177
178
0
error:
179
0
    _Py_ext_module_loader_info_clear(&info);
180
0
    return -1;
181
972
}
182
183
184
/********************************/
185
/* module init function results */
186
/********************************/
187
188
void
189
_Py_ext_module_loader_result_clear(struct _Py_ext_module_loader_result *res)
190
968
{
191
    /* Instead, the caller should have called
192
     * _Py_ext_module_loader_result_apply_error(). */
193
968
    assert(res->err == NULL);
194
968
    *res = (struct _Py_ext_module_loader_result){0};
195
968
}
196
197
static void
198
_Py_ext_module_loader_result_set_error(
199
                            struct _Py_ext_module_loader_result *res,
200
                            enum _Py_ext_module_loader_result_error_kind kind)
201
0
{
202
#ifndef NDEBUG
203
    switch (kind) {
204
    case _Py_ext_module_loader_result_EXCEPTION: _Py_FALLTHROUGH;
205
    case _Py_ext_module_loader_result_ERR_UNREPORTED_EXC:
206
        assert(PyErr_Occurred());
207
        break;
208
    case _Py_ext_module_loader_result_ERR_MISSING: _Py_FALLTHROUGH;
209
    case _Py_ext_module_loader_result_ERR_UNINITIALIZED: _Py_FALLTHROUGH;
210
    case _Py_ext_module_loader_result_ERR_NONASCII_NOT_MULTIPHASE: _Py_FALLTHROUGH;
211
    case _Py_ext_module_loader_result_ERR_NOT_MODULE: _Py_FALLTHROUGH;
212
    case _Py_ext_module_loader_result_ERR_MISSING_DEF:
213
        assert(!PyErr_Occurred());
214
        break;
215
    default:
216
        /* We added a new error kind but forgot to add it to this switch. */
217
        assert(0);
218
    }
219
#endif
220
221
0
    assert(res->err == NULL && res->_err.exc == NULL);
222
0
    res->err = &res->_err;
223
0
    *res->err = (struct _Py_ext_module_loader_result_error){
224
0
        .kind=kind,
225
0
        .exc=PyErr_GetRaisedException(),
226
0
    };
227
228
    /* For some kinds, we also set/check res->kind. */
229
0
    switch (kind) {
230
0
    case _Py_ext_module_loader_result_ERR_UNINITIALIZED:
231
0
        assert(res->kind == _Py_ext_module_kind_UNKNOWN);
232
0
        res->kind = _Py_ext_module_kind_INVALID;
233
0
        break;
234
    /* None of the rest affect the result kind. */
235
0
    case _Py_ext_module_loader_result_EXCEPTION: _Py_FALLTHROUGH;
236
0
    case _Py_ext_module_loader_result_ERR_MISSING: _Py_FALLTHROUGH;
237
0
    case _Py_ext_module_loader_result_ERR_UNREPORTED_EXC: _Py_FALLTHROUGH;
238
0
    case _Py_ext_module_loader_result_ERR_NONASCII_NOT_MULTIPHASE: _Py_FALLTHROUGH;
239
0
    case _Py_ext_module_loader_result_ERR_NOT_MODULE: _Py_FALLTHROUGH;
240
0
    case _Py_ext_module_loader_result_ERR_MISSING_DEF:
241
0
        break;
242
0
    default:
243
        /* We added a new error kind but forgot to add it to this switch. */
244
0
        assert(0);
245
0
    }
246
0
}
247
248
void
249
_Py_ext_module_loader_result_apply_error(
250
                            struct _Py_ext_module_loader_result *res,
251
                            const char *name)
252
0
{
253
0
    assert(!PyErr_Occurred());
254
0
    assert(res->err != NULL && res->err == &res->_err);
255
0
    struct _Py_ext_module_loader_result_error err = *res->err;
256
0
    res->err = NULL;
257
258
    /* We're otherwise done with the result at this point. */
259
0
    _Py_ext_module_loader_result_clear(res);
260
261
#ifndef NDEBUG
262
    switch (err.kind) {
263
    case _Py_ext_module_loader_result_EXCEPTION: _Py_FALLTHROUGH;
264
    case _Py_ext_module_loader_result_ERR_UNREPORTED_EXC:
265
        assert(err.exc != NULL);
266
        break;
267
    case _Py_ext_module_loader_result_ERR_MISSING: _Py_FALLTHROUGH;
268
    case _Py_ext_module_loader_result_ERR_UNINITIALIZED: _Py_FALLTHROUGH;
269
    case _Py_ext_module_loader_result_ERR_NONASCII_NOT_MULTIPHASE: _Py_FALLTHROUGH;
270
    case _Py_ext_module_loader_result_ERR_NOT_MODULE: _Py_FALLTHROUGH;
271
    case _Py_ext_module_loader_result_ERR_MISSING_DEF:
272
        assert(err.exc == NULL);
273
        break;
274
    default:
275
        /* We added a new error kind but forgot to add it to this switch. */
276
        assert(0);
277
    }
278
#endif
279
280
0
    const char *msg = NULL;
281
0
    switch (err.kind) {
282
0
    case _Py_ext_module_loader_result_EXCEPTION:
283
0
        break;
284
0
    case _Py_ext_module_loader_result_ERR_MISSING:
285
0
        msg = "initialization of %s failed without raising an exception";
286
0
        break;
287
0
    case _Py_ext_module_loader_result_ERR_UNREPORTED_EXC:
288
0
        msg = "initialization of %s raised unreported exception";
289
0
        break;
290
0
    case _Py_ext_module_loader_result_ERR_UNINITIALIZED:
291
0
        msg = "init function of %s returned uninitialized object";
292
0
        break;
293
0
    case _Py_ext_module_loader_result_ERR_NONASCII_NOT_MULTIPHASE:
294
0
        msg = "initialization of %s did not return PyModuleDef";
295
0
        break;
296
0
    case _Py_ext_module_loader_result_ERR_NOT_MODULE:
297
0
        msg = "initialization of %s did not return an extension module";
298
0
        break;
299
0
    case _Py_ext_module_loader_result_ERR_MISSING_DEF:
300
0
        msg = "initialization of %s did not return a valid extension module";
301
0
        break;
302
0
    default:
303
        /* We added a new error kind but forgot to add it to this switch. */
304
0
        assert(0);
305
0
        PyErr_Format(PyExc_SystemError,
306
0
                     "loading %s failed due to init function", name);
307
0
        return;
308
0
    }
309
310
0
    if (err.exc != NULL) {
311
0
        PyErr_SetRaisedException(err.exc);
312
0
        err.exc = NULL;  /* PyErr_SetRaisedException() stole our reference. */
313
0
        if (msg != NULL) {
314
0
            _PyErr_FormatFromCause(PyExc_SystemError, msg, name);
315
0
        }
316
0
    }
317
0
    else {
318
0
        assert(msg != NULL);
319
0
        PyErr_Format(PyExc_SystemError, msg, name);
320
0
    }
321
0
}
322
323
324
/********************************************/
325
/* getting/running the module init function */
326
/********************************************/
327
328
#ifdef HAVE_DYNAMIC_LOADING
329
static dl_funcptr
330
findfuncptr(const char *prefix, const char *name_buf,
331
            struct _Py_ext_module_loader_info *info,
332
            FILE *fp)
333
434
{
334
#ifdef MS_WINDOWS
335
    return _PyImport_FindSharedFuncptrWindows(
336
            prefix, name_buf, info->filename, fp);
337
#else
338
434
    const char *path_buf = PyBytes_AS_STRING(info->filename_encoded);
339
434
    return _PyImport_FindSharedFuncptr(
340
434
            prefix, name_buf, path_buf, fp);
341
434
#endif
342
434
}
343
344
int
345
_PyImport_GetModuleExportHooks(
346
    struct _Py_ext_module_loader_info *info,
347
    FILE *fp,
348
    PyModInitFunction *modinit,
349
    PyModExportFunction *modexport)
350
219
{
351
219
    *modinit = NULL;
352
219
    *modexport = NULL;
353
354
219
    const char *name_buf = PyBytes_AS_STRING(info->name_encoded);
355
219
    dl_funcptr exportfunc;
356
357
219
    exportfunc = findfuncptr(
358
219
        info->hook_prefixes->export_prefix,
359
219
        name_buf, info, fp);
360
219
    if (exportfunc) {
361
4
        *modexport = (PyModExportFunction)exportfunc;
362
4
        return 2;
363
4
    }
364
215
    if (PyErr_Occurred()) {
365
0
        return -1;
366
0
    }
367
368
215
    exportfunc = findfuncptr(
369
215
        info->hook_prefixes->init_prefix,
370
215
        name_buf, info, fp);
371
215
    if (exportfunc) {
372
215
        *modinit = (PyModInitFunction)exportfunc;
373
215
        return 1;
374
215
    }
375
376
0
    if (!PyErr_Occurred()) {
377
0
        PyObject *msg;
378
0
        msg = PyUnicode_FromFormat(
379
0
            "dynamic module does not define "
380
0
            "module export function (%s_%s or %s_%s)",
381
0
            info->hook_prefixes->export_prefix, name_buf,
382
0
            info->hook_prefixes->init_prefix, name_buf);
383
0
        if (msg != NULL) {
384
0
            PyErr_SetImportError(msg, info->name, info->filename);
385
0
            Py_DECREF(msg);
386
0
        }
387
0
    }
388
0
    return -1;
389
215
}
390
#endif /* HAVE_DYNAMIC_LOADING */
391
392
int
393
_PyImport_RunModInitFunc(PyModInitFunction p0,
394
                         struct _Py_ext_module_loader_info *info,
395
                         struct _Py_ext_module_loader_result *p_res)
396
968
{
397
968
    struct _Py_ext_module_loader_result res = {
398
968
        .kind=_Py_ext_module_kind_UNKNOWN,
399
968
    };
400
401
    /* Call the module init function. */
402
403
    /* Package context is needed for single-phase init */
404
968
    const char *oldcontext = _PyImport_SwapPackageContext(info->newcontext);
405
968
    PyObject *m = p0();
406
968
    _PyImport_SwapPackageContext(oldcontext);
407
408
    /* Validate the result (and populate "res". */
409
410
968
    if (m == NULL) {
411
        /* The init func for multi-phase init modules is expected
412
         * to return a PyModuleDef after calling PyModuleDef_Init().
413
         * That function never raises an exception nor returns NULL,
414
         * so at this point it must be a single-phase init modules. */
415
0
        res.kind = _Py_ext_module_kind_SINGLEPHASE;
416
0
        if (PyErr_Occurred()) {
417
0
            _Py_ext_module_loader_result_set_error(
418
0
                        &res, _Py_ext_module_loader_result_EXCEPTION);
419
0
        }
420
0
        else {
421
0
            _Py_ext_module_loader_result_set_error(
422
0
                        &res, _Py_ext_module_loader_result_ERR_MISSING);
423
0
        }
424
0
        goto error;
425
968
    } else if (PyErr_Occurred()) {
426
        /* Likewise, we infer that this is a single-phase init module. */
427
0
        res.kind = _Py_ext_module_kind_SINGLEPHASE;
428
0
        _Py_ext_module_loader_result_set_error(
429
0
                &res, _Py_ext_module_loader_result_ERR_UNREPORTED_EXC);
430
        /* We would probably be correct to decref m here,
431
         * but we weren't doing so before,
432
         * so we stick with doing nothing. */
433
0
        m = NULL;
434
0
        goto error;
435
0
    }
436
437
968
    if (Py_IS_TYPE(m, NULL)) {
438
        /* This can happen when a PyModuleDef is returned without calling
439
         * PyModuleDef_Init on it
440
         */
441
0
        _Py_ext_module_loader_result_set_error(
442
0
                &res, _Py_ext_module_loader_result_ERR_UNINITIALIZED);
443
        /* Likewise, decref'ing here makes sense.  However, the original
444
         * code has a note about "prevent segfault in DECREF",
445
         * so we play it safe and leave it alone. */
446
0
        m = NULL; /* prevent segfault in DECREF */
447
0
        goto error;
448
0
    }
449
450
968
    if (PyObject_TypeCheck(m, &PyModuleDef_Type)) {
451
        /* multi-phase init */
452
968
        res.kind = _Py_ext_module_kind_MULTIPHASE;
453
968
        res.def = (PyModuleDef *)m;
454
        /* Run PyModule_FromDefAndSpec() to finish loading the module. */
455
968
    }
456
0
    else if (info->hook_prefixes == &nonascii_prefixes) {
457
        /* Non-ASCII is only supported for multi-phase init. */
458
0
        res.kind = _Py_ext_module_kind_MULTIPHASE;
459
        /* Don't allow legacy init for non-ASCII module names. */
460
0
        _Py_ext_module_loader_result_set_error(
461
0
                &res, _Py_ext_module_loader_result_ERR_NONASCII_NOT_MULTIPHASE);
462
0
        goto error;
463
0
    }
464
0
    else {
465
        /* single-phase init (legacy) */
466
0
        res.kind = _Py_ext_module_kind_SINGLEPHASE;
467
0
        res.module = m;
468
469
0
        if (!PyModule_Check(m)) {
470
0
            _Py_ext_module_loader_result_set_error(
471
0
                    &res, _Py_ext_module_loader_result_ERR_NOT_MODULE);
472
0
            goto error;
473
0
        }
474
475
0
        res.def = _PyModule_GetDefOrNull(m);
476
0
        if (res.def == NULL) {
477
0
            PyErr_Clear();
478
0
            _Py_ext_module_loader_result_set_error(
479
0
                    &res, _Py_ext_module_loader_result_ERR_MISSING_DEF);
480
0
            goto error;
481
0
        }
482
0
    }
483
484
968
    assert(!PyErr_Occurred());
485
968
    assert(res.err == NULL);
486
968
    *p_res = res;
487
968
    return 0;
488
489
0
error:
490
0
    assert(!PyErr_Occurred());
491
0
    assert(res.err != NULL);
492
0
    Py_CLEAR(res.module);
493
    res.def = NULL;
494
0
    *p_res = res;
495
0
    p_res->err = &p_res->_err;
496
0
    return -1;
497
968
}