Coverage Report

Created: 2025-11-24 06:11

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/import.c
Line
Count
Source
1
/* Module definition and import implementation */
2
3
#include "Python.h"
4
#include "pycore_audit.h"         // _PySys_Audit()
5
#include "pycore_ceval.h"
6
#include "pycore_critical_section.h"  // Py_BEGIN_CRITICAL_SECTION()
7
#include "pycore_hashtable.h"     // _Py_hashtable_new_full()
8
#include "pycore_import.h"        // _PyImport_BootstrapImp()
9
#include "pycore_initconfig.h"    // _PyStatus_OK()
10
#include "pycore_interp.h"        // struct _import_runtime_state
11
#include "pycore_magic_number.h"  // PYC_MAGIC_NUMBER_TOKEN
12
#include "pycore_moduleobject.h"  // _PyModule_GetDef()
13
#include "pycore_namespace.h"     // _PyNamespace_Type
14
#include "pycore_object.h"        // _Py_SetImmortal()
15
#include "pycore_pyerrors.h"      // _PyErr_SetString()
16
#include "pycore_pyhash.h"        // _Py_KeyedHash()
17
#include "pycore_pylifecycle.h"
18
#include "pycore_pymem.h"         // _PyMem_DefaultRawFree()
19
#include "pycore_pystate.h"       // _PyInterpreterState_GET()
20
#include "pycore_sysmodule.h"     // _PySys_ClearAttrString()
21
#include "pycore_time.h"          // _PyTime_AsMicroseconds()
22
#include "pycore_unicodeobject.h" // _PyUnicode_AsUTF8NoNUL()
23
#include "pycore_weakref.h"       // _PyWeakref_GET_REF()
24
25
#include "marshal.h"              // PyMarshal_ReadObjectFromString()
26
#include "pycore_importdl.h"      // _PyImport_DynLoadFiletab
27
#include "pydtrace.h"             // PyDTrace_IMPORT_FIND_LOAD_START_ENABLED()
28
#include <stdbool.h>              // bool
29
30
#ifdef HAVE_FCNTL_H
31
#include <fcntl.h>
32
#endif
33
34
35
/*[clinic input]
36
module _imp
37
[clinic start generated code]*/
38
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9c332475d8686284]*/
39
40
#include "clinic/import.c.h"
41
42
43
#ifndef NDEBUG
44
static bool
45
is_interpreter_isolated(PyInterpreterState *interp)
46
{
47
    return !_Py_IsMainInterpreter(interp)
48
        && !(interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC)
49
        && interp->ceval.own_gil;
50
}
51
#endif
52
53
54
/*******************************/
55
/* process-global import state */
56
/*******************************/
57
58
/* This table is defined in config.c: */
59
extern struct _inittab _PyImport_Inittab[];
60
61
// This is not used after Py_Initialize() is called.
62
// (See _PyRuntimeState.imports.inittab.)
63
struct _inittab *PyImport_Inittab = _PyImport_Inittab;
64
// When we dynamically allocate a larger table for PyImport_ExtendInittab(),
65
// we track the pointer here so we can deallocate it during finalization.
66
static struct _inittab *inittab_copy = NULL;
67
68
69
/*******************************/
70
/* runtime-global import state */
71
/*******************************/
72
73
15.0k
#define INITTAB _PyRuntime.imports.inittab
74
795
#define LAST_MODULE_INDEX _PyRuntime.imports.last_module_index
75
1.73k
#define EXTENSIONS _PyRuntime.imports.extensions
76
77
#define PKGCONTEXT (_PyRuntime.imports.pkgcontext)
78
79
80
/*******************************/
81
/* interpreter import state */
82
/*******************************/
83
84
#define MODULES(interp) \
85
2.98M
    (interp)->imports.modules
86
#define MODULES_BY_INDEX(interp) \
87
308
    (interp)->imports.modules_by_index
88
#define IMPORTLIB(interp) \
89
17.7k
    (interp)->imports.importlib
90
#define OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) \
91
0
    (interp)->imports.override_multi_interp_extensions_check
92
#define OVERRIDE_FROZEN_MODULES(interp) \
93
14.0k
    (interp)->imports.override_frozen_modules
94
#ifdef HAVE_DLOPEN
95
#  define DLOPENFLAGS(interp) \
96
248
        (interp)->imports.dlopenflags
97
#endif
98
#define IMPORT_FUNC(interp) \
99
1.63M
    (interp)->imports.import_func
100
101
#define IMPORT_LOCK(interp) \
102
212k
    (interp)->imports.lock
103
104
#define FIND_AND_LOAD(interp) \
105
14.3k
    (interp)->imports.find_and_load
106
107
#define _IMPORT_TIME_HEADER(interp)                                           \
108
0
    do {                                                                      \
109
0
        if (FIND_AND_LOAD((interp)).header) {                                 \
110
0
            fputs("import time: self [us] | cumulative | imported package\n", \
111
0
                  stderr);                                                    \
112
0
            FIND_AND_LOAD((interp)).header = 0;                               \
113
0
        }                                                                     \
114
0
    } while (0)
115
116
117
/*******************/
118
/* the import lock */
119
/*******************/
120
121
/* Locking primitives to prevent parallel imports of the same module
122
   in different threads to return with a partially loaded module.
123
   These calls are serialized by the global interpreter lock. */
124
125
void
126
_PyImport_AcquireLock(PyInterpreterState *interp)
127
70.7k
{
128
70.7k
    _PyRecursiveMutex_Lock(&IMPORT_LOCK(interp));
129
70.7k
}
130
131
void
132
_PyImport_ReleaseLock(PyInterpreterState *interp)
133
70.7k
{
134
70.7k
    _PyRecursiveMutex_Unlock(&IMPORT_LOCK(interp));
135
70.7k
}
136
137
void
138
_PyImport_ReInitLock(PyInterpreterState *interp)
139
0
{
140
    // gh-126688: Thread id may change after fork() on some operating systems.
141
0
    IMPORT_LOCK(interp).thread = PyThread_get_thread_ident_ex();
142
0
}
143
144
145
/***************/
146
/* sys.modules */
147
/***************/
148
149
PyObject *
150
_PyImport_InitModules(PyInterpreterState *interp)
151
28
{
152
28
    assert(MODULES(interp) == NULL);
153
28
    MODULES(interp) = PyDict_New();
154
28
    if (MODULES(interp) == NULL) {
155
0
        return NULL;
156
0
    }
157
28
    return MODULES(interp);
158
28
}
159
160
PyObject *
161
_PyImport_GetModules(PyInterpreterState *interp)
162
504k
{
163
504k
    return MODULES(interp);
164
504k
}
165
166
PyObject *
167
_PyImport_GetModulesRef(PyInterpreterState *interp)
168
0
{
169
0
    _PyImport_AcquireLock(interp);
170
0
    PyObject *modules = MODULES(interp);
171
0
    if (modules == NULL) {
172
        /* The interpreter hasn't been initialized yet. */
173
0
        modules = Py_None;
174
0
    }
175
0
    Py_INCREF(modules);
176
0
    _PyImport_ReleaseLock(interp);
177
0
    return modules;
178
0
}
179
180
void
181
_PyImport_ClearModules(PyInterpreterState *interp)
182
0
{
183
0
    Py_SETREF(MODULES(interp), NULL);
184
0
}
185
186
static inline PyObject *
187
get_modules_dict(PyThreadState *tstate, bool fatal)
188
2.47M
{
189
    /* Technically, it would make sense to incref the dict,
190
     * since sys.modules could be swapped out and decref'ed to 0
191
     * before the caller is done using it.  However, that is highly
192
     * unlikely, especially since we can rely on a global lock
193
     * (i.e. the GIL) for thread-safety. */
194
2.47M
    PyObject *modules = MODULES(tstate->interp);
195
2.47M
    if (modules == NULL) {
196
0
        if (fatal) {
197
0
            Py_FatalError("interpreter has no modules dictionary");
198
0
        }
199
0
        _PyErr_SetString(tstate, PyExc_RuntimeError,
200
0
                         "unable to get sys.modules");
201
0
        return NULL;
202
0
    }
203
2.47M
    return modules;
204
2.47M
}
205
206
PyObject *
207
PyImport_GetModuleDict(void)
208
0
{
209
0
    PyThreadState *tstate = _PyThreadState_GET();
210
0
    return get_modules_dict(tstate, true);
211
0
}
212
213
int
214
_PyImport_SetModule(PyObject *name, PyObject *m)
215
4
{
216
4
    PyThreadState *tstate = _PyThreadState_GET();
217
4
    PyObject *modules = get_modules_dict(tstate, true);
218
4
    return PyObject_SetItem(modules, name, m);
219
4
}
220
221
int
222
_PyImport_SetModuleString(const char *name, PyObject *m)
223
38
{
224
38
    PyThreadState *tstate = _PyThreadState_GET();
225
38
    PyObject *modules = get_modules_dict(tstate, true);
226
38
    return PyMapping_SetItemString(modules, name, m);
227
38
}
228
229
static PyObject *
230
import_get_module(PyThreadState *tstate, PyObject *name)
231
2.47M
{
232
2.47M
    PyObject *modules = get_modules_dict(tstate, false);
233
2.47M
    if (modules == NULL) {
234
0
        return NULL;
235
0
    }
236
237
2.47M
    PyObject *m;
238
2.47M
    Py_INCREF(modules);
239
2.47M
    (void)PyMapping_GetOptionalItem(modules, name, &m);
240
2.47M
    Py_DECREF(modules);
241
2.47M
    return m;
242
2.47M
}
243
244
static int
245
import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
246
2.28M
{
247
2.28M
    PyObject *spec;
248
249
    /* Optimization: only call _bootstrap._lock_unlock_module() if
250
       __spec__._initializing is true.
251
       NOTE: because of this, initializing must be set *before*
252
       stuffing the new module in sys.modules.
253
    */
254
2.28M
    int rc = PyObject_GetOptionalAttr(mod, &_Py_ID(__spec__), &spec);
255
2.28M
    if (rc > 0) {
256
2.28M
        rc = _PyModuleSpec_IsInitializing(spec);
257
2.28M
        Py_DECREF(spec);
258
2.28M
    }
259
2.28M
    if (rc == 0) {
260
2.28M
        goto done;
261
2.28M
    }
262
436
    else if (rc < 0) {
263
0
        return rc;
264
0
    }
265
266
    /* Wait until module is done importing. */
267
436
    PyObject *value = PyObject_CallMethodOneArg(
268
436
        IMPORTLIB(interp), &_Py_ID(_lock_unlock_module), name);
269
436
    if (value == NULL) {
270
0
        return -1;
271
0
    }
272
436
    Py_DECREF(value);
273
274
2.28M
done:
275
    /* When -X importtime=2, print an import time entry even if an
276
       imported module has already been loaded.
277
     */
278
2.28M
    if (_PyInterpreterState_GetConfig(interp)->import_time == 2) {
279
0
        _IMPORT_TIME_HEADER(interp);
280
0
#define import_level FIND_AND_LOAD(interp).import_level
281
0
        fprintf(stderr, "import time: cached    | cached     | %*s\n",
282
0
                import_level*2, PyUnicode_AsUTF8(name));
283
0
#undef import_level
284
0
    }
285
286
2.28M
    return 0;
287
436
}
288
289
static void remove_importlib_frames(PyThreadState *tstate);
290
291
PyObject *
292
PyImport_GetModule(PyObject *name)
293
504k
{
294
504k
    PyThreadState *tstate = _PyThreadState_GET();
295
504k
    PyObject *mod;
296
297
504k
    mod = import_get_module(tstate, name);
298
504k
    if (mod != NULL && mod != Py_None) {
299
504k
        if (import_ensure_initialized(tstate->interp, mod, name) < 0) {
300
0
            Py_DECREF(mod);
301
0
            remove_importlib_frames(tstate);
302
0
            return NULL;
303
0
        }
304
504k
    }
305
504k
    return mod;
306
504k
}
307
308
/* Get the module object corresponding to a module name.
309
   First check the modules dictionary if there's one there,
310
   if not, create a new one and insert it in the modules dictionary. */
311
312
static PyObject *
313
import_add_module_lock_held(PyObject *modules, PyObject *name)
314
140
{
315
140
    PyObject *m;
316
140
    if (PyMapping_GetOptionalItem(modules, name, &m) < 0) {
317
0
        return NULL;
318
0
    }
319
140
    if (m != NULL && PyModule_Check(m)) {
320
84
        return m;
321
84
    }
322
56
    Py_XDECREF(m);
323
56
    m = PyModule_NewObject(name);
324
56
    if (m == NULL)
325
0
        return NULL;
326
56
    if (PyObject_SetItem(modules, name, m) != 0) {
327
0
        Py_DECREF(m);
328
0
        return NULL;
329
0
    }
330
331
56
    return m;
332
56
}
333
334
static PyObject *
335
import_add_module(PyThreadState *tstate, PyObject *name)
336
140
{
337
140
    PyObject *modules = get_modules_dict(tstate, false);
338
140
    if (modules == NULL) {
339
0
        return NULL;
340
0
    }
341
342
140
    PyObject *m;
343
140
    Py_BEGIN_CRITICAL_SECTION(modules);
344
140
    m = import_add_module_lock_held(modules, name);
345
140
    Py_END_CRITICAL_SECTION();
346
140
    return m;
347
140
}
348
349
PyObject *
350
PyImport_AddModuleRef(const char *name)
351
84
{
352
84
    PyObject *name_obj = PyUnicode_FromString(name);
353
84
    if (name_obj == NULL) {
354
0
        return NULL;
355
0
    }
356
84
    PyThreadState *tstate = _PyThreadState_GET();
357
84
    PyObject *module = import_add_module(tstate, name_obj);
358
84
    Py_DECREF(name_obj);
359
84
    return module;
360
84
}
361
362
363
PyObject *
364
PyImport_AddModuleObject(PyObject *name)
365
28
{
366
28
    PyThreadState *tstate = _PyThreadState_GET();
367
28
    PyObject *mod = import_add_module(tstate, name);
368
28
    if (!mod) {
369
0
        return NULL;
370
0
    }
371
372
    // gh-86160: PyImport_AddModuleObject() returns a borrowed reference.
373
    // Create a weak reference to produce a borrowed reference, since it can
374
    // become NULL. sys.modules type can be different than dict and it is not
375
    // guaranteed that it keeps a strong reference to the module. It can be a
376
    // custom mapping with __getitem__() which returns a new object or removes
377
    // returned object, or __setitem__ which does nothing. There is so much
378
    // unknown.  With weakref we can be sure that we get either a reference to
379
    // live object or NULL.
380
    //
381
    // Use PyImport_AddModuleRef() to avoid these issues.
382
28
    PyObject *ref = PyWeakref_NewRef(mod, NULL);
383
28
    Py_DECREF(mod);
384
28
    if (ref == NULL) {
385
0
        return NULL;
386
0
    }
387
28
    mod = _PyWeakref_GET_REF(ref);
388
28
    Py_DECREF(ref);
389
28
    Py_XDECREF(mod);
390
391
28
    if (mod == NULL && !PyErr_Occurred()) {
392
0
        PyErr_SetString(PyExc_RuntimeError,
393
0
                        "sys.modules does not hold a strong reference "
394
0
                        "to the module");
395
0
    }
396
28
    return mod; /* borrowed reference */
397
28
}
398
399
400
PyObject *
401
PyImport_AddModule(const char *name)
402
0
{
403
0
    PyObject *nameobj = PyUnicode_FromString(name);
404
0
    if (nameobj == NULL) {
405
0
        return NULL;
406
0
    }
407
0
    PyObject *module = PyImport_AddModuleObject(nameobj);
408
0
    Py_DECREF(nameobj);
409
0
    return module;
410
0
}
411
412
413
/* Remove name from sys.modules, if it's there.
414
 * Can be called with an exception raised.
415
 * If fail to remove name a new exception will be chained with the old
416
 * exception, otherwise the old exception is preserved.
417
 */
418
static void
419
remove_module(PyThreadState *tstate, PyObject *name)
420
0
{
421
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
422
423
0
    PyObject *modules = get_modules_dict(tstate, true);
424
0
    if (PyDict_CheckExact(modules)) {
425
        // Error is reported to the caller
426
0
        (void)PyDict_Pop(modules, name, NULL);
427
0
    }
428
0
    else if (PyMapping_DelItem(modules, name) < 0) {
429
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
430
0
            _PyErr_Clear(tstate);
431
0
        }
432
0
    }
433
434
0
    _PyErr_ChainExceptions1(exc);
435
0
}
436
437
438
/************************************/
439
/* per-interpreter modules-by-index */
440
/************************************/
441
442
Py_ssize_t
443
_PyImport_GetNextModuleIndex(void)
444
795
{
445
795
    return _Py_atomic_add_ssize(&LAST_MODULE_INDEX, 1) + 1;
446
795
}
447
448
#ifndef NDEBUG
449
struct extensions_cache_value;
450
static struct extensions_cache_value * _find_cached_def(PyModuleDef *);
451
static Py_ssize_t _get_cached_module_index(struct extensions_cache_value *);
452
#endif
453
454
static Py_ssize_t
455
_get_module_index_from_def(PyModuleDef *def)
456
0
{
457
0
    Py_ssize_t index = def->m_base.m_index;
458
#ifndef NDEBUG
459
    struct extensions_cache_value *cached = _find_cached_def(def);
460
    assert(cached == NULL || index == _get_cached_module_index(cached));
461
#endif
462
0
    return index;
463
0
}
464
465
static void
466
_set_module_index(PyModuleDef *def, Py_ssize_t index)
467
56
{
468
56
    assert(index > 0);
469
56
    if (index == def->m_base.m_index) {
470
        /* There's nothing to do. */
471
56
    }
472
0
    else if (def->m_base.m_index == 0) {
473
        /* It should have been initialized by PyModuleDef_Init().
474
         * We assert here to catch this in dev, but keep going otherwise. */
475
0
        assert(def->m_base.m_index != 0);
476
0
        def->m_base.m_index = index;
477
0
    }
478
0
    else {
479
        /* It was already set for a different module.
480
         * We replace the old value. */
481
0
        assert(def->m_base.m_index > 0);
482
0
        def->m_base.m_index = index;
483
0
    }
484
56
}
485
486
static const char *
487
_modules_by_index_check(PyInterpreterState *interp, Py_ssize_t index)
488
0
{
489
0
    if (index <= 0) {
490
0
        return "invalid module index";
491
0
    }
492
0
    if (MODULES_BY_INDEX(interp) == NULL) {
493
0
        return "Interpreters module-list not accessible.";
494
0
    }
495
0
    if (index >= PyList_GET_SIZE(MODULES_BY_INDEX(interp))) {
496
0
        return "Module index out of bounds.";
497
0
    }
498
0
    return NULL;
499
0
}
500
501
static PyObject *
502
_modules_by_index_get(PyInterpreterState *interp, Py_ssize_t index)
503
0
{
504
0
    if (_modules_by_index_check(interp, index) != NULL) {
505
0
        return NULL;
506
0
    }
507
0
    PyObject *res = PyList_GET_ITEM(MODULES_BY_INDEX(interp), index);
508
0
    return res==Py_None ? NULL : res;
509
0
}
510
511
static int
512
_modules_by_index_set(PyInterpreterState *interp,
513
                      Py_ssize_t index, PyObject *module)
514
56
{
515
56
    assert(index > 0);
516
517
56
    if (MODULES_BY_INDEX(interp) == NULL) {
518
28
        MODULES_BY_INDEX(interp) = PyList_New(0);
519
28
        if (MODULES_BY_INDEX(interp) == NULL) {
520
0
            return -1;
521
0
        }
522
28
    }
523
524
196
    while (PyList_GET_SIZE(MODULES_BY_INDEX(interp)) <= index) {
525
140
        if (PyList_Append(MODULES_BY_INDEX(interp), Py_None) < 0) {
526
0
            return -1;
527
0
        }
528
140
    }
529
530
56
    return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(module));
531
56
}
532
533
static int
534
_modules_by_index_clear_one(PyInterpreterState *interp, Py_ssize_t index)
535
0
{
536
0
    const char *err = _modules_by_index_check(interp, index);
537
0
    if (err != NULL) {
538
0
        Py_FatalError(err);
539
0
        return -1;
540
0
    }
541
0
    return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(Py_None));
542
0
}
543
544
545
PyObject*
546
PyState_FindModule(PyModuleDef* module)
547
0
{
548
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
549
0
    if (module->m_slots) {
550
0
        return NULL;
551
0
    }
552
0
    Py_ssize_t index = _get_module_index_from_def(module);
553
0
    return _modules_by_index_get(interp, index);
554
0
}
555
556
/* _PyState_AddModule() has been completely removed from the C-API
557
   (and was removed from the limited API in 3.6).  However, we're
558
   playing it safe and keeping it around for any stable ABI extensions
559
   built against 3.2-3.5. */
560
int
561
_PyState_AddModule(PyThreadState *tstate, PyObject* module, PyModuleDef* def)
562
0
{
563
0
    if (!def) {
564
0
        assert(_PyErr_Occurred(tstate));
565
0
        return -1;
566
0
    }
567
0
    if (def->m_slots) {
568
0
        _PyErr_SetString(tstate,
569
0
                         PyExc_SystemError,
570
0
                         "PyState_AddModule called on module with slots");
571
0
        return -1;
572
0
    }
573
0
    assert(def->m_slots == NULL);
574
0
    Py_ssize_t index = _get_module_index_from_def(def);
575
0
    return _modules_by_index_set(tstate->interp, index, module);
576
0
}
577
578
int
579
PyState_AddModule(PyObject* module, PyModuleDef* def)
580
0
{
581
0
    if (!def) {
582
0
        Py_FatalError("module definition is NULL");
583
0
        return -1;
584
0
    }
585
586
0
    PyThreadState *tstate = _PyThreadState_GET();
587
0
    if (def->m_slots) {
588
0
        _PyErr_SetString(tstate,
589
0
                         PyExc_SystemError,
590
0
                         "PyState_AddModule called on module with slots");
591
0
        return -1;
592
0
    }
593
594
0
    PyInterpreterState *interp = tstate->interp;
595
0
    Py_ssize_t index = _get_module_index_from_def(def);
596
0
    if (MODULES_BY_INDEX(interp) &&
597
0
        index < PyList_GET_SIZE(MODULES_BY_INDEX(interp)) &&
598
0
        module == PyList_GET_ITEM(MODULES_BY_INDEX(interp), index))
599
0
    {
600
0
        _Py_FatalErrorFormat(__func__, "module %p already added", module);
601
0
        return -1;
602
0
    }
603
604
0
    assert(def->m_slots == NULL);
605
0
    return _modules_by_index_set(interp, index, module);
606
0
}
607
608
int
609
PyState_RemoveModule(PyModuleDef* def)
610
0
{
611
0
    PyThreadState *tstate = _PyThreadState_GET();
612
0
    if (def->m_slots) {
613
0
        _PyErr_SetString(tstate,
614
0
                         PyExc_SystemError,
615
0
                         "PyState_RemoveModule called on module with slots");
616
0
        return -1;
617
0
    }
618
0
    Py_ssize_t index = _get_module_index_from_def(def);
619
0
    return _modules_by_index_clear_one(tstate->interp, index);
620
0
}
621
622
623
// Used by finalize_modules()
624
void
625
_PyImport_ClearModulesByIndex(PyInterpreterState *interp)
626
0
{
627
0
    if (!MODULES_BY_INDEX(interp)) {
628
0
        return;
629
0
    }
630
631
0
    Py_ssize_t i;
632
0
    for (i = 0; i < PyList_GET_SIZE(MODULES_BY_INDEX(interp)); i++) {
633
0
        PyObject *m = PyList_GET_ITEM(MODULES_BY_INDEX(interp), i);
634
0
        if (PyModule_Check(m)) {
635
            /* cleanup the saved copy of module dicts */
636
0
            PyModuleDef *md = PyModule_GetDef(m);
637
0
            if (md) {
638
                // XXX Do this more carefully.  The dict might be owned
639
                // by another interpreter.
640
0
                Py_CLEAR(md->m_base.m_copy);
641
0
            }
642
0
        }
643
0
    }
644
645
    /* Setting modules_by_index to NULL could be dangerous, so we
646
       clear the list instead. */
647
0
    if (PyList_SetSlice(MODULES_BY_INDEX(interp),
648
0
                        0, PyList_GET_SIZE(MODULES_BY_INDEX(interp)),
649
0
                        NULL)) {
650
0
        PyErr_FormatUnraisable("Exception ignored while "
651
0
                               "clearing interpreters module list");
652
0
    }
653
0
}
654
655
656
/*********************/
657
/* extension modules */
658
/*********************/
659
660
/*
661
    It may help to have a big picture view of what happens
662
    when an extension is loaded.  This includes when it is imported
663
    for the first time.
664
665
    Here's a summary, using importlib._bootstrap._load() as a starting point.
666
667
    1.  importlib._bootstrap._load()
668
    2.    _load():  acquire import lock
669
    3.    _load() -> importlib._bootstrap._load_unlocked()
670
    4.      _load_unlocked() -> importlib._bootstrap.module_from_spec()
671
    5.        module_from_spec() -> ExtensionFileLoader.create_module()
672
    6.          create_module() -> _imp.create_dynamic()
673
                    (see below)
674
    7.        module_from_spec() -> importlib._bootstrap._init_module_attrs()
675
    8.      _load_unlocked():  sys.modules[name] = module
676
    9.      _load_unlocked() -> ExtensionFileLoader.exec_module()
677
    10.       exec_module() -> _imp.exec_dynamic()
678
                  (see below)
679
    11.   _load():  release import lock
680
681
682
    ...for single-phase init modules, where m_size == -1:
683
684
    (6). first time  (not found in _PyRuntime.imports.extensions):
685
       A. _imp_create_dynamic_impl() -> import_find_extension()
686
       B. _imp_create_dynamic_impl() -> _PyImport_GetModuleExportHooks()
687
       C.   _PyImport_GetModuleExportHooks():  load <module init func>
688
       D. _imp_create_dynamic_impl() -> import_run_extension()
689
       E.   import_run_extension() -> _PyImport_RunModInitFunc()
690
       F.     _PyImport_RunModInitFunc():  call <module init func>
691
       G.       <module init func> -> PyModule_Create() -> PyModule_Create2()
692
                                          -> PyModule_CreateInitialized()
693
       H.         PyModule_CreateInitialized() -> PyModule_New()
694
       I.         PyModule_CreateInitialized():  allocate mod->md_state
695
       J.         PyModule_CreateInitialized() -> PyModule_AddFunctions()
696
       K.         PyModule_CreateInitialized() -> PyModule_SetDocString()
697
       L.       PyModule_CreateInitialized():  set mod->md_def
698
       M.       <module init func>:  initialize the module, etc.
699
       N.   import_run_extension()
700
                -> _PyImport_CheckSubinterpIncompatibleExtensionAllowed()
701
       O.   import_run_extension():  set __file__
702
       P.   import_run_extension() -> update_global_state_for_extension()
703
       Q.     update_global_state_for_extension():
704
                      copy __dict__ into def->m_base.m_copy
705
       R.     update_global_state_for_extension():
706
                      add it to _PyRuntime.imports.extensions
707
       S.   import_run_extension() -> finish_singlephase_extension()
708
       T.     finish_singlephase_extension():
709
                      add it to interp->imports.modules_by_index
710
       U.     finish_singlephase_extension():  add it to sys.modules
711
712
       Step (Q) is skipped for core modules (sys/builtins).
713
714
    (6). subsequent times  (found in _PyRuntime.imports.extensions):
715
       A. _imp_create_dynamic_impl() -> import_find_extension()
716
       B.   import_find_extension() -> reload_singlephase_extension()
717
       C.     reload_singlephase_extension()
718
                  -> _PyImport_CheckSubinterpIncompatibleExtensionAllowed()
719
       D.     reload_singlephase_extension() -> import_add_module()
720
       E.       if name in sys.modules:  use that module
721
       F.       else:
722
                  1. import_add_module() -> PyModule_NewObject()
723
                  2. import_add_module():  set it on sys.modules
724
       G.     reload_singlephase_extension():  copy the "m_copy" dict into __dict__
725
       H.     reload_singlephase_extension():  add to modules_by_index
726
727
    (10). (every time):
728
       A. noop
729
730
731
    ...for single-phase init modules, where m_size >= 0:
732
733
    (6). not main interpreter and never loaded there - every time  (not found in _PyRuntime.imports.extensions):
734
       A-P. (same as for m_size == -1)
735
       Q.     _PyImport_RunModInitFunc():  set def->m_base.m_init
736
       R. (skipped)
737
       S-U. (same as for m_size == -1)
738
739
    (6). main interpreter - first time  (not found in _PyRuntime.imports.extensions):
740
       A-P. (same as for m_size == -1)
741
       Q.     _PyImport_RunModInitFunc():  set def->m_base.m_init
742
       R-U. (same as for m_size == -1)
743
744
    (6). subsequent times  (found in _PyRuntime.imports.extensions):
745
       A. _imp_create_dynamic_impl() -> import_find_extension()
746
       B.   import_find_extension() -> reload_singlephase_extension()
747
       C.     reload_singlephase_extension()
748
                  -> _PyImport_CheckSubinterpIncompatibleExtensionAllowed()
749
       D.     reload_singlephase_extension():  call def->m_base.m_init  (see above)
750
       E.     reload_singlephase_extension():  add the module to sys.modules
751
       F.     reload_singlephase_extension():  add to modules_by_index
752
753
    (10). every time:
754
       A. noop
755
756
757
    ...for multi-phase init modules from PyModInit_* (PyModuleDef):
758
759
    (6). every time:
760
       A. _imp_create_dynamic_impl() -> import_find_extension()  (not found)
761
       B. _imp_create_dynamic_impl() -> _PyImport_GetModuleExportHooks()
762
       C.   _PyImport_GetModuleExportHooks():  load <module init func>
763
       D. _imp_create_dynamic_impl() -> import_run_extension()
764
       E.   import_run_extension() -> _PyImport_RunModInitFunc()
765
       F.     _PyImport_RunModInitFunc():  call <module init func>
766
       G.   import_run_extension() -> PyModule_FromDefAndSpec()
767
768
       PyModule_FromDefAndSpec():
769
770
       H.      PyModule_FromDefAndSpec(): gather/check moduledef slots
771
       I.      if there's a Py_mod_create slot:
772
                 1. PyModule_FromDefAndSpec():  call its function
773
       J.      else:
774
                 1. PyModule_FromDefAndSpec() -> PyModule_NewObject()
775
       K:      PyModule_FromDefAndSpec():  set mod->md_def
776
       L.      PyModule_FromDefAndSpec() -> _add_methods_to_object()
777
       M.      PyModule_FromDefAndSpec() -> PyModule_SetDocString()
778
779
    (10). every time:
780
       A. _imp_exec_dynamic_impl() -> exec_builtin_or_dynamic()
781
       B.   if mod->md_state == NULL (including if m_size == 0):
782
            1. exec_builtin_or_dynamic() -> PyModule_Exec()
783
            2.   PyModule_Exec():  allocate mod->md_state
784
            3.   if there's a Py_mod_exec slot:
785
                 1. PyModule_Exec():  call its function
786
787
788
    ...for multi-phase init modules from PyModExport_* (slots array):
789
790
    (6). every time:
791
792
       A. _imp_create_dynamic_impl() -> import_find_extension()  (not found)
793
       B. _imp_create_dynamic_impl() -> _PyImport_GetModuleExportHooks()
794
       C.   _PyImport_GetModuleExportHooks():  load <module export func>
795
       D. _imp_create_dynamic_impl() -> import_run_modexport()
796
       E.     import_run_modexport():  call <module init func>
797
       F.   import_run_modexport() -> PyModule_FromSlotsAndSpec()
798
       G.     PyModule_FromSlotsAndSpec(): create temporary PyModuleDef-like
799
       H.       PyModule_FromSlotsAndSpec() -> PyModule_FromDefAndSpec()
800
801
       (PyModule_FromDefAndSpec behaves as for PyModInit_*, above)
802
803
    (10). every time: as for PyModInit_*, above
804
805
 */
806
807
808
/* Make sure name is fully qualified.
809
810
   This is a bit of a hack: when the shared library is loaded,
811
   the module name is "package.module", but the module calls
812
   PyModule_Create*() with just "module" for the name.  The shared
813
   library loader squirrels away the true name of the module in
814
   _PyRuntime.imports.pkgcontext, and PyModule_Create*() will
815
   substitute this (if the name actually matches).
816
*/
817
818
static _Py_thread_local const char *pkgcontext = NULL;
819
# undef PKGCONTEXT
820
2.84k
# define PKGCONTEXT pkgcontext
821
822
const char *
823
_PyImport_ResolveNameWithPackageContext(const char *name)
824
112
{
825
112
    if (PKGCONTEXT != NULL) {
826
0
        const char *p = strrchr(PKGCONTEXT, '.');
827
0
        if (p != NULL && strcmp(name, p+1) == 0) {
828
0
            name = PKGCONTEXT;
829
0
            PKGCONTEXT = NULL;
830
0
        }
831
0
    }
832
112
    return name;
833
112
}
834
835
const char *
836
_PyImport_SwapPackageContext(const char *newcontext)
837
1.36k
{
838
1.36k
    const char *oldcontext = PKGCONTEXT;
839
1.36k
    PKGCONTEXT = newcontext;
840
1.36k
    return oldcontext;
841
1.36k
}
842
843
#ifdef HAVE_DLOPEN
844
int
845
_PyImport_GetDLOpenFlags(PyInterpreterState *interp)
846
248
{
847
248
    return DLOPENFLAGS(interp);
848
248
}
849
850
void
851
_PyImport_SetDLOpenFlags(PyInterpreterState *interp, int new_val)
852
0
{
853
0
    DLOPENFLAGS(interp) = new_val;
854
0
}
855
#endif  // HAVE_DLOPEN
856
857
858
/* Common implementation for _imp.exec_dynamic and _imp.exec_builtin */
859
static int
860
683
exec_builtin_or_dynamic(PyObject *mod) {
861
683
    void *state;
862
863
683
    if (!PyModule_Check(mod)) {
864
0
        return 0;
865
0
    }
866
867
683
    state = PyModule_GetState(mod);
868
683
    if (state) {
869
        /* Already initialized; skip reload */
870
0
        return 0;
871
0
    }
872
873
683
    return PyModule_Exec(mod);
874
683
}
875
876
877
static int clear_singlephase_extension(PyInterpreterState *interp,
878
                                       PyObject *name, PyObject *filename);
879
880
// Currently, this is only used for testing.
881
// (See _testinternalcapi.clear_extension().)
882
// If adding another use, be careful about modules that import themselves
883
// recursively (see gh-123880).
884
int
885
_PyImport_ClearExtension(PyObject *name, PyObject *filename)
886
0
{
887
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
888
889
    /* Clearing a module's C globals is up to the module. */
890
0
    if (clear_singlephase_extension(interp, name, filename) < 0) {
891
0
        return -1;
892
0
    }
893
894
    // In the future we'll probably also make sure the extension's
895
    // file handle (and DL handle) is closed (requires saving it).
896
897
0
    return 0;
898
0
}
899
900
901
/*****************************/
902
/* single-phase init modules */
903
/*****************************/
904
905
/*
906
We support a number of kinds of single-phase init builtin/extension modules:
907
908
* "basic"
909
    * no module state (PyModuleDef.m_size == -1)
910
    * does not support repeated init (we use PyModuleDef.m_base.m_copy)
911
    * may have process-global state
912
    * the module's def is cached in _PyRuntime.imports.extensions,
913
      by (name, filename)
914
* "reinit"
915
    * no module state (PyModuleDef.m_size == 0)
916
    * supports repeated init (m_copy is never used)
917
    * should not have any process-global state
918
    * its def is never cached in _PyRuntime.imports.extensions
919
      (except, currently, under the main interpreter, for some reason)
920
* "with state"  (almost the same as reinit)
921
    * has module state (PyModuleDef.m_size > 0)
922
    * supports repeated init (m_copy is never used)
923
    * should not have any process-global state
924
    * its def is never cached in _PyRuntime.imports.extensions
925
      (except, currently, under the main interpreter, for some reason)
926
927
There are also variants within those classes:
928
929
* two or more modules share a PyModuleDef
930
    * a module's init func uses another module's PyModuleDef
931
    * a module's init func calls another's module's init func
932
    * a module's init "func" is actually a variable statically initialized
933
      to another module's init func
934
* two or modules share "methods"
935
    * a module's init func copies another module's PyModuleDef
936
      (with a different name)
937
* (basic-only) two or modules share process-global state
938
939
In the first case, where modules share a PyModuleDef, the following
940
notable weirdness happens:
941
942
* the module's __name__ matches the def, not the requested name
943
* the last module (with the same def) to be imported for the first time wins
944
    * returned by PyState_Find_Module() (via interp->modules_by_index)
945
    * (non-basic-only) its init func is used when re-loading any of them
946
      (via the def's m_init)
947
    * (basic-only) the copy of its __dict__ is used when re-loading any of them
948
      (via the def's m_copy)
949
950
However, the following happens as expected:
951
952
* a new module object (with its own __dict__) is created for each request
953
* the module's __spec__ has the requested name
954
* the loaded module is cached in sys.modules under the requested name
955
* the m_index field of the shared def is not changed,
956
  so at least PyState_FindModule() will always look in the same place
957
958
For "basic" modules there are other quirks:
959
960
* (whether sharing a def or not) when loaded the first time,
961
  m_copy is set before _init_module_attrs() is called
962
  in importlib._bootstrap.module_from_spec(),
963
  so when the module is re-loaded, the previous value
964
  for __wpec__ (and others) is reset, possibly unexpectedly.
965
966
Generally, when multiple interpreters are involved, some of the above
967
gets even messier.
968
*/
969
970
static inline void
971
extensions_lock_acquire(void)
972
795
{
973
795
    PyMutex_Lock(&_PyRuntime.imports.extensions.mutex);
974
795
}
975
976
static inline void
977
extensions_lock_release(void)
978
795
{
979
795
    PyMutex_Unlock(&_PyRuntime.imports.extensions.mutex);
980
795
}
981
982
983
/* Magic for extension modules (built-in as well as dynamically
984
   loaded).  To prevent initializing an extension module more than
985
   once, we keep a static dictionary 'extensions' keyed by the tuple
986
   (module name, module name)  (for built-in modules) or by
987
   (filename, module name) (for dynamically loaded modules), containing these
988
   modules.  A copy of the module's dictionary is stored by calling
989
   fix_up_extension() immediately after the module initialization
990
   function succeeds.  A copy can be retrieved from there by calling
991
   import_find_extension().
992
993
   Modules which do support multiple initialization set their m_size
994
   field to a non-negative number (indicating the size of the
995
   module-specific state). They are still recorded in the extensions
996
   dictionary, to avoid loading shared libraries twice.
997
*/
998
999
typedef struct cached_m_dict {
1000
    /* A shallow copy of the original module's __dict__. */
1001
    PyObject *copied;
1002
    /* The interpreter that owns the copy. */
1003
    int64_t interpid;
1004
} *cached_m_dict_t;
1005
1006
struct extensions_cache_value {
1007
    PyModuleDef *def;
1008
1009
    /* The function used to re-initialize the module.
1010
       This is only set for legacy (single-phase init) extension modules
1011
       and only used for those that support multiple initializations
1012
       (m_size >= 0).
1013
       It is set by update_global_state_for_extension(). */
1014
    PyModInitFunction m_init;
1015
1016
    /* The module's index into its interpreter's modules_by_index cache.
1017
       This is set for all extension modules but only used for legacy ones.
1018
       (See PyInterpreterState.modules_by_index for more info.) */
1019
    Py_ssize_t m_index;
1020
1021
    /* A copy of the module's __dict__ after the first time it was loaded.
1022
       This is only set/used for legacy modules that do not support
1023
       multiple initializations.
1024
       It is set exclusively by fixup_cached_def(). */
1025
    cached_m_dict_t m_dict;
1026
    struct cached_m_dict _m_dict;
1027
1028
    _Py_ext_module_origin origin;
1029
1030
#ifdef Py_GIL_DISABLED
1031
    /* The module's md_requires_gil member, for legacy modules that are
1032
     * reinitialized from m_dict rather than calling their initialization
1033
     * function again. */
1034
    bool md_requires_gil;
1035
#endif
1036
};
1037
1038
static struct extensions_cache_value *
1039
alloc_extensions_cache_value(void)
1040
56
{
1041
56
    struct extensions_cache_value *value
1042
56
            = PyMem_RawMalloc(sizeof(struct extensions_cache_value));
1043
56
    if (value == NULL) {
1044
0
        PyErr_NoMemory();
1045
0
        return NULL;
1046
0
    }
1047
56
    *value = (struct extensions_cache_value){0};
1048
56
    return value;
1049
56
}
1050
1051
static void
1052
free_extensions_cache_value(struct extensions_cache_value *value)
1053
0
{
1054
0
    PyMem_RawFree(value);
1055
0
}
1056
1057
static Py_ssize_t
1058
_get_cached_module_index(struct extensions_cache_value *cached)
1059
56
{
1060
56
    assert(cached->m_index > 0);
1061
56
    return cached->m_index;
1062
56
}
1063
1064
static void
1065
fixup_cached_def(struct extensions_cache_value *value)
1066
56
{
1067
    /* For the moment, the values in the def's m_base may belong
1068
     * to another module, and we're replacing them here.  This can
1069
     * cause problems later if the old module is reloaded.
1070
     *
1071
     * Also, we don't decref any old cached values first when we
1072
     * replace them here, in case we need to restore them in the
1073
     * near future.  Instead, the caller is responsible for wrapping
1074
     * this up by calling cleanup_old_cached_def() or
1075
     * restore_old_cached_def() if there was an error. */
1076
56
    PyModuleDef *def = value->def;
1077
56
    assert(def != NULL);
1078
1079
    /* We assume that all module defs are statically allocated
1080
       and will never be freed.  Otherwise, we would incref here. */
1081
56
    _Py_SetImmortalUntracked((PyObject *)def);
1082
1083
56
    def->m_base.m_init = value->m_init;
1084
1085
56
    assert(value->m_index > 0);
1086
56
    _set_module_index(def, value->m_index);
1087
1088
    /* Different modules can share the same def, so we can't just
1089
     * expect m_copy to be NULL. */
1090
56
    assert(def->m_base.m_copy == NULL
1091
56
           || def->m_base.m_init == NULL
1092
56
           || value->m_dict != NULL);
1093
56
    if (value->m_dict != NULL) {
1094
0
        assert(value->m_dict->copied != NULL);
1095
        /* As noted above, we don't first decref the old value, if any. */
1096
0
        def->m_base.m_copy = Py_NewRef(value->m_dict->copied);
1097
0
    }
1098
56
}
1099
1100
static void
1101
restore_old_cached_def(PyModuleDef *def, PyModuleDef_Base *oldbase)
1102
0
{
1103
0
    def->m_base = *oldbase;
1104
0
}
1105
1106
static void
1107
cleanup_old_cached_def(PyModuleDef_Base *oldbase)
1108
56
{
1109
56
    Py_XDECREF(oldbase->m_copy);
1110
56
}
1111
1112
static void
1113
del_cached_def(struct extensions_cache_value *value)
1114
0
{
1115
    /* If we hadn't made the stored defs immortal, we would decref here.
1116
       However, this decref would be problematic if the module def were
1117
       dynamically allocated, it were the last ref, and this function
1118
       were called with an interpreter other than the def's owner. */
1119
0
    assert(value->def == NULL || _Py_IsImmortal(value->def));
1120
1121
0
    Py_XDECREF(value->def->m_base.m_copy);
1122
0
    value->def->m_base.m_copy = NULL;
1123
0
}
1124
1125
static int
1126
init_cached_m_dict(struct extensions_cache_value *value, PyObject *m_dict)
1127
56
{
1128
56
    assert(value != NULL);
1129
    /* This should only have been called without an m_dict already set. */
1130
56
    assert(value->m_dict == NULL);
1131
56
    if (m_dict == NULL) {
1132
56
        return 0;
1133
56
    }
1134
56
    assert(PyDict_Check(m_dict));
1135
0
    assert(value->origin != _Py_ext_module_origin_CORE);
1136
1137
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1138
0
    assert(!is_interpreter_isolated(interp));
1139
1140
    /* XXX gh-88216: The copied dict is owned by the current
1141
     * interpreter.  That's a problem if the interpreter has
1142
     * its own obmalloc state or if the module is successfully
1143
     * imported into such an interpreter.  If the interpreter
1144
     * has its own GIL then there may be data races and
1145
     * PyImport_ClearModulesByIndex() can crash.  Normally,
1146
     * a single-phase init module cannot be imported in an
1147
     * isolated interpreter, but there are ways around that.
1148
     * Hence, heere be dragons!  Ideally we would instead do
1149
     * something like make a read-only, immortal copy of the
1150
     * dict using PyMem_RawMalloc() and store *that* in m_copy.
1151
     * Then we'd need to make sure to clear that when the
1152
     * runtime is finalized, rather than in
1153
     * PyImport_ClearModulesByIndex(). */
1154
0
    PyObject *copied = PyDict_Copy(m_dict);
1155
0
    if (copied == NULL) {
1156
        /* We expect this can only be "out of memory". */
1157
0
        return -1;
1158
0
    }
1159
    // XXX We may want to make the copy immortal.
1160
1161
0
    value->_m_dict = (struct cached_m_dict){
1162
0
        .copied=copied,
1163
0
        .interpid=PyInterpreterState_GetID(interp),
1164
0
    };
1165
1166
0
    value->m_dict = &value->_m_dict;
1167
0
    return 0;
1168
0
}
1169
1170
static void
1171
del_cached_m_dict(struct extensions_cache_value *value)
1172
0
{
1173
0
    if (value->m_dict != NULL) {
1174
0
        assert(value->m_dict == &value->_m_dict);
1175
0
        assert(value->m_dict->copied != NULL);
1176
        /* In the future we can take advantage of m_dict->interpid
1177
         * to decref the dict using the owning interpreter. */
1178
0
        Py_XDECREF(value->m_dict->copied);
1179
0
        value->m_dict = NULL;
1180
0
    }
1181
0
}
1182
1183
static PyObject * get_core_module_dict(
1184
        PyInterpreterState *interp, PyObject *name, PyObject *path);
1185
1186
static PyObject *
1187
get_cached_m_dict(struct extensions_cache_value *value,
1188
                  PyObject *name, PyObject *path)
1189
0
{
1190
0
    assert(value != NULL);
1191
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1192
    /* It might be a core module (e.g. sys & builtins),
1193
       for which we don't cache m_dict. */
1194
0
    if (value->origin == _Py_ext_module_origin_CORE) {
1195
0
        return get_core_module_dict(interp, name, path);
1196
0
    }
1197
0
    assert(value->def != NULL);
1198
    // XXX Switch to value->m_dict.
1199
0
    PyObject *m_dict = value->def->m_base.m_copy;
1200
0
    Py_XINCREF(m_dict);
1201
0
    return m_dict;
1202
0
}
1203
1204
static void
1205
del_extensions_cache_value(void *raw)
1206
0
{
1207
0
    struct extensions_cache_value *value = raw;
1208
0
    if (value != NULL) {
1209
0
        del_cached_m_dict(value);
1210
0
        del_cached_def(value);
1211
0
        free_extensions_cache_value(value);
1212
0
    }
1213
0
}
1214
1215
static void *
1216
hashtable_key_from_2_strings(PyObject *str1, PyObject *str2, const char sep)
1217
767
{
1218
767
    const char *str1_data = _PyUnicode_AsUTF8NoNUL(str1);
1219
767
    const char *str2_data = _PyUnicode_AsUTF8NoNUL(str2);
1220
767
    if (str1_data == NULL || str2_data == NULL) {
1221
0
        return NULL;
1222
0
    }
1223
767
    Py_ssize_t str1_len = strlen(str1_data);
1224
767
    Py_ssize_t str2_len = strlen(str2_data);
1225
1226
    /* Make sure sep and the NULL byte won't cause an overflow. */
1227
767
    assert(SIZE_MAX - str1_len - str2_len > 2);
1228
767
    size_t size = str1_len + 1 + str2_len + 1;
1229
1230
    // XXX Use a buffer if it's a temp value (every case but "set").
1231
767
    char *key = PyMem_RawMalloc(size);
1232
767
    if (key == NULL) {
1233
0
        PyErr_NoMemory();
1234
0
        return NULL;
1235
0
    }
1236
1237
767
    memcpy(key, str1_data, str1_len);
1238
767
    key[str1_len] = sep;
1239
767
    memcpy(key + str1_len + 1, str2_data, str2_len);
1240
767
    key[size - 1] = '\0';
1241
767
    assert(strlen(key) == size - 1);
1242
767
    return key;
1243
767
}
1244
1245
static Py_uhash_t
1246
hashtable_hash_str(const void *key)
1247
823
{
1248
823
    return Py_HashBuffer(key, strlen((const char *)key));
1249
823
}
1250
1251
static int
1252
hashtable_compare_str(const void *key1, const void *key2)
1253
0
{
1254
0
    return strcmp((const char *)key1, (const char *)key2) == 0;
1255
0
}
1256
1257
static void
1258
hashtable_destroy_str(void *ptr)
1259
711
{
1260
711
    PyMem_RawFree(ptr);
1261
711
}
1262
1263
#ifndef NDEBUG
1264
struct hashtable_next_match_def_data {
1265
    PyModuleDef *def;
1266
    struct extensions_cache_value *matched;
1267
};
1268
1269
static int
1270
hashtable_next_match_def(_Py_hashtable_t *ht,
1271
                         const void *key, const void *value, void *user_data)
1272
{
1273
    if (value == NULL) {
1274
        /* It was previously deleted. */
1275
        return 0;
1276
    }
1277
    struct hashtable_next_match_def_data *data
1278
            = (struct hashtable_next_match_def_data *)user_data;
1279
    struct extensions_cache_value *cur
1280
            = (struct extensions_cache_value *)value;
1281
    if (cur->def == data->def) {
1282
        data->matched = cur;
1283
        return 1;
1284
    }
1285
    return 0;
1286
}
1287
1288
static struct extensions_cache_value *
1289
_find_cached_def(PyModuleDef *def)
1290
{
1291
    struct hashtable_next_match_def_data data = {0};
1292
    (void)_Py_hashtable_foreach(
1293
            EXTENSIONS.hashtable, hashtable_next_match_def, &data);
1294
    return data.matched;
1295
}
1296
#endif
1297
1298
767
#define HTSEP ':'
1299
1300
static int
1301
_extensions_cache_init(void)
1302
28
{
1303
28
    _Py_hashtable_allocator_t alloc = {PyMem_RawMalloc, PyMem_RawFree};
1304
28
    EXTENSIONS.hashtable = _Py_hashtable_new_full(
1305
28
        hashtable_hash_str,
1306
28
        hashtable_compare_str,
1307
28
        hashtable_destroy_str,  // key
1308
28
        del_extensions_cache_value,  // value
1309
28
        &alloc
1310
28
    );
1311
28
    if (EXTENSIONS.hashtable == NULL) {
1312
0
        PyErr_NoMemory();
1313
0
        return -1;
1314
0
    }
1315
28
    return 0;
1316
28
}
1317
1318
static _Py_hashtable_entry_t *
1319
_extensions_cache_find_unlocked(PyObject *path, PyObject *name,
1320
                                void **p_key)
1321
795
{
1322
795
    if (EXTENSIONS.hashtable == NULL) {
1323
28
        return NULL;
1324
28
    }
1325
767
    void *key = hashtable_key_from_2_strings(path, name, HTSEP);
1326
767
    if (key == NULL) {
1327
0
        return NULL;
1328
0
    }
1329
767
    _Py_hashtable_entry_t *entry =
1330
767
            _Py_hashtable_get_entry(EXTENSIONS.hashtable, key);
1331
767
    if (p_key != NULL) {
1332
56
        *p_key = key;
1333
56
    }
1334
711
    else {
1335
711
        hashtable_destroy_str(key);
1336
711
    }
1337
767
    return entry;
1338
767
}
1339
1340
/* This can only fail with "out of memory". */
1341
static struct extensions_cache_value *
1342
_extensions_cache_get(PyObject *path, PyObject *name)
1343
739
{
1344
739
    struct extensions_cache_value *value = NULL;
1345
739
    extensions_lock_acquire();
1346
1347
739
    _Py_hashtable_entry_t *entry =
1348
739
            _extensions_cache_find_unlocked(path, name, NULL);
1349
739
    if (entry == NULL) {
1350
        /* It was never added. */
1351
739
        goto finally;
1352
739
    }
1353
0
    value = (struct extensions_cache_value *)entry->value;
1354
1355
739
finally:
1356
739
    extensions_lock_release();
1357
739
    return value;
1358
0
}
1359
1360
/* This can only fail with "out of memory". */
1361
static struct extensions_cache_value *
1362
_extensions_cache_set(PyObject *path, PyObject *name,
1363
                      PyModuleDef *def, PyModInitFunction m_init,
1364
                      Py_ssize_t m_index, PyObject *m_dict,
1365
                      _Py_ext_module_origin origin, bool requires_gil)
1366
56
{
1367
56
    struct extensions_cache_value *value = NULL;
1368
56
    void *key = NULL;
1369
56
    struct extensions_cache_value *newvalue = NULL;
1370
56
    PyModuleDef_Base olddefbase = def->m_base;
1371
1372
56
    assert(def != NULL);
1373
56
    assert(m_init == NULL || m_dict == NULL);
1374
    /* We expect the same symbol to be used and the shared object file
1375
     * to have remained loaded, so it must be the same pointer. */
1376
56
    assert(def->m_base.m_init == NULL || def->m_base.m_init == m_init);
1377
    /* For now we don't worry about comparing value->m_copy. */
1378
56
    assert(def->m_base.m_copy == NULL || m_dict != NULL);
1379
56
    assert((origin == _Py_ext_module_origin_DYNAMIC) == (name != path));
1380
56
    assert(origin != _Py_ext_module_origin_CORE || m_dict == NULL);
1381
1382
56
    extensions_lock_acquire();
1383
1384
56
    if (EXTENSIONS.hashtable == NULL) {
1385
28
        if (_extensions_cache_init() < 0) {
1386
0
            goto finally;
1387
0
        }
1388
28
    }
1389
1390
    /* Create a cached value to populate for the module. */
1391
56
    _Py_hashtable_entry_t *entry =
1392
56
            _extensions_cache_find_unlocked(path, name, &key);
1393
56
    value = entry == NULL
1394
56
        ? NULL
1395
56
        : (struct extensions_cache_value *)entry->value;
1396
56
    if (value != NULL) {
1397
        /* gh-123880: If there's an existing cache value, it means a module is
1398
         * being imported recursively from its PyInit_* or Py_mod_* function.
1399
         * (That function presumably handles returning a partially
1400
         *  constructed module in such a case.)
1401
         * We can reuse the existing cache value; it is owned by the cache.
1402
         * (Entries get removed from it in exceptional circumstances,
1403
         *  after interpreter shutdown, and in runtime shutdown.)
1404
         */
1405
0
        goto finally_oldvalue;
1406
0
    }
1407
56
    newvalue = alloc_extensions_cache_value();
1408
56
    if (newvalue == NULL) {
1409
0
        goto finally;
1410
0
    }
1411
1412
    /* Populate the new cache value data. */
1413
56
    *newvalue = (struct extensions_cache_value){
1414
56
        .def=def,
1415
56
        .m_init=m_init,
1416
56
        .m_index=m_index,
1417
        /* m_dict is set by set_cached_m_dict(). */
1418
56
        .origin=origin,
1419
#ifdef Py_GIL_DISABLED
1420
        .md_requires_gil=requires_gil,
1421
#endif
1422
56
    };
1423
56
#ifndef Py_GIL_DISABLED
1424
56
    (void)requires_gil;
1425
56
#endif
1426
56
    if (init_cached_m_dict(newvalue, m_dict) < 0) {
1427
0
        goto finally;
1428
0
    }
1429
56
    fixup_cached_def(newvalue);
1430
1431
56
    if (entry == NULL) {
1432
        /* It was never added. */
1433
56
        if (_Py_hashtable_set(EXTENSIONS.hashtable, key, newvalue) < 0) {
1434
0
            PyErr_NoMemory();
1435
0
            goto finally;
1436
0
        }
1437
        /* The hashtable owns the key now. */
1438
56
        key = NULL;
1439
56
    }
1440
0
    else if (value == NULL) {
1441
        /* It was previously deleted. */
1442
0
        entry->value = newvalue;
1443
0
    }
1444
0
    else {
1445
        /* We are updating the entry for an existing module. */
1446
        /* We expect def to be static, so it must be the same pointer. */
1447
0
        assert(value->def == def);
1448
        /* We expect the same symbol to be used and the shared object file
1449
         * to have remained loaded, so it must be the same pointer. */
1450
0
        assert(value->m_init == m_init);
1451
        /* The same module can't switch between caching __dict__ and not. */
1452
0
        assert((value->m_dict == NULL) == (m_dict == NULL));
1453
        /* This shouldn't ever happen. */
1454
0
        Py_UNREACHABLE();
1455
0
    }
1456
1457
56
    value = newvalue;
1458
1459
56
finally:
1460
56
    if (value == NULL) {
1461
0
        restore_old_cached_def(def, &olddefbase);
1462
0
        if (newvalue != NULL) {
1463
0
            del_extensions_cache_value(newvalue);
1464
0
        }
1465
0
    }
1466
56
    else {
1467
56
        cleanup_old_cached_def(&olddefbase);
1468
56
    }
1469
1470
56
finally_oldvalue:
1471
56
    extensions_lock_release();
1472
56
    if (key != NULL) {
1473
0
        hashtable_destroy_str(key);
1474
0
    }
1475
1476
56
    return value;
1477
56
}
1478
1479
static void
1480
_extensions_cache_delete(PyObject *path, PyObject *name)
1481
0
{
1482
0
    extensions_lock_acquire();
1483
1484
0
    if (EXTENSIONS.hashtable == NULL) {
1485
        /* It was never added. */
1486
0
        goto finally;
1487
0
    }
1488
1489
0
    _Py_hashtable_entry_t *entry =
1490
0
            _extensions_cache_find_unlocked(path, name, NULL);
1491
0
    if (entry == NULL) {
1492
        /* It was never added. */
1493
0
        goto finally;
1494
0
    }
1495
0
    if (entry->value == NULL) {
1496
        /* It was already removed. */
1497
0
        goto finally;
1498
0
    }
1499
0
    struct extensions_cache_value *value = entry->value;
1500
0
    entry->value = NULL;
1501
1502
0
    del_extensions_cache_value(value);
1503
1504
0
finally:
1505
0
    extensions_lock_release();
1506
0
}
1507
1508
static void
1509
_extensions_cache_clear_all(void)
1510
0
{
1511
    /* The runtime (i.e. main interpreter) must be finalizing,
1512
       so we don't need to worry about the lock. */
1513
0
    _Py_hashtable_destroy(EXTENSIONS.hashtable);
1514
0
    EXTENSIONS.hashtable = NULL;
1515
0
}
1516
1517
#undef HTSEP
1518
1519
1520
static bool
1521
check_multi_interp_extensions(PyInterpreterState *interp)
1522
0
{
1523
0
    int override = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
1524
0
    if (override < 0) {
1525
0
        return false;
1526
0
    }
1527
0
    else if (override > 0) {
1528
0
        return true;
1529
0
    }
1530
0
    else if (_PyInterpreterState_HasFeature(
1531
0
                interp, Py_RTFLAGS_MULTI_INTERP_EXTENSIONS)) {
1532
0
        return true;
1533
0
    }
1534
0
    return false;
1535
0
}
1536
1537
int
1538
_PyImport_CheckSubinterpIncompatibleExtensionAllowed(const char *name)
1539
0
{
1540
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1541
0
    if (check_multi_interp_extensions(interp)) {
1542
0
        assert(!_Py_IsMainInterpreter(interp));
1543
0
        PyErr_Format(PyExc_ImportError,
1544
0
                     "module %s does not support loading in subinterpreters",
1545
0
                     name);
1546
0
        return -1;
1547
0
    }
1548
0
    return 0;
1549
0
}
1550
1551
#ifdef Py_GIL_DISABLED
1552
int
1553
_PyImport_CheckGILForModule(PyObject* module, PyObject *module_name)
1554
{
1555
    PyThreadState *tstate = _PyThreadState_GET();
1556
    if (module == NULL) {
1557
        _PyEval_DisableGIL(tstate);
1558
        return 0;
1559
    }
1560
1561
    if (!PyModule_Check(module) ||
1562
        ((PyModuleObject *)module)->md_requires_gil)
1563
    {
1564
        if (_PyEval_EnableGILPermanent(tstate)) {
1565
            int warn_result = PyErr_WarnFormat(
1566
                PyExc_RuntimeWarning,
1567
                1,
1568
                "The global interpreter lock (GIL) has been enabled to load "
1569
                "module '%U', which has not declared that it can run safely "
1570
                "without the GIL. To override this behavior and keep the GIL "
1571
                "disabled (at your own risk), run with PYTHON_GIL=0 or -Xgil=0.",
1572
                module_name
1573
            );
1574
            if (warn_result < 0) {
1575
                return warn_result;
1576
            }
1577
        }
1578
1579
        const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
1580
        if (config->enable_gil == _PyConfig_GIL_DEFAULT && config->verbose) {
1581
            PySys_FormatStderr("# loading module '%U', which requires the GIL\n",
1582
                               module_name);
1583
        }
1584
    }
1585
    else {
1586
        _PyEval_DisableGIL(tstate);
1587
    }
1588
1589
    return 0;
1590
}
1591
#endif
1592
1593
static PyThreadState *
1594
switch_to_main_interpreter(PyThreadState *tstate)
1595
683
{
1596
683
    if (_Py_IsMainInterpreter(tstate->interp)) {
1597
683
        return tstate;
1598
683
    }
1599
0
    PyThreadState *main_tstate = _PyThreadState_NewBound(
1600
0
            _PyInterpreterState_Main(), _PyThreadState_WHENCE_EXEC);
1601
0
    if (main_tstate == NULL) {
1602
0
        return NULL;
1603
0
    }
1604
#ifndef NDEBUG
1605
    PyThreadState *old_tstate = PyThreadState_Swap(main_tstate);
1606
    assert(old_tstate == tstate);
1607
#else
1608
0
    (void)PyThreadState_Swap(main_tstate);
1609
0
#endif
1610
0
    return main_tstate;
1611
0
}
1612
1613
static void
1614
switch_back_from_main_interpreter(PyThreadState *tstate,
1615
                                  PyThreadState *main_tstate,
1616
                                  PyObject *tempobj)
1617
0
{
1618
0
    assert(main_tstate == PyThreadState_GET());
1619
0
    assert(_Py_IsMainInterpreter(main_tstate->interp));
1620
0
    assert(tstate->interp != main_tstate->interp);
1621
1622
    /* Handle any exceptions, which we cannot propagate directly
1623
     * to the subinterpreter. */
1624
0
    if (PyErr_Occurred()) {
1625
0
        if (PyErr_ExceptionMatches(PyExc_MemoryError)) {
1626
            /* We trust it will be caught again soon. */
1627
0
            PyErr_Clear();
1628
0
        }
1629
0
        else {
1630
            /* Printing the exception should be sufficient. */
1631
0
            PyErr_PrintEx(0);
1632
0
        }
1633
0
    }
1634
1635
0
    Py_XDECREF(tempobj);
1636
1637
0
    PyThreadState_Clear(main_tstate);
1638
0
    (void)PyThreadState_Swap(tstate);
1639
0
    PyThreadState_Delete(main_tstate);
1640
0
}
1641
1642
static PyObject *
1643
get_core_module_dict(PyInterpreterState *interp,
1644
                     PyObject *name, PyObject *path)
1645
0
{
1646
    /* Only builtin modules are core. */
1647
0
    if (path == name) {
1648
0
        assert(!PyErr_Occurred());
1649
0
        if (PyUnicode_CompareWithASCIIString(name, "sys") == 0) {
1650
0
            return Py_NewRef(interp->sysdict_copy);
1651
0
        }
1652
0
        assert(!PyErr_Occurred());
1653
0
        if (PyUnicode_CompareWithASCIIString(name, "builtins") == 0) {
1654
0
            return Py_NewRef(interp->builtins_copy);
1655
0
        }
1656
0
        assert(!PyErr_Occurred());
1657
0
    }
1658
0
    return NULL;
1659
0
}
1660
1661
#ifndef NDEBUG
1662
static inline int
1663
is_core_module(PyInterpreterState *interp, PyObject *name, PyObject *path)
1664
{
1665
    /* This might be called before the core dict copies are in place,
1666
       so we can't rely on get_core_module_dict() here. */
1667
    if (path == name) {
1668
        if (PyUnicode_CompareWithASCIIString(name, "sys") == 0) {
1669
            return 1;
1670
        }
1671
        if (PyUnicode_CompareWithASCIIString(name, "builtins") == 0) {
1672
            return 1;
1673
        }
1674
    }
1675
    return 0;
1676
}
1677
1678
1679
static _Py_ext_module_kind
1680
_get_extension_kind(PyModuleDef *def, bool check_size)
1681
{
1682
    _Py_ext_module_kind kind;
1683
    if (def == NULL) {
1684
        /* It must be a module created by reload_singlephase_extension()
1685
         * from m_copy.  Ideally we'd do away with this case. */
1686
        kind = _Py_ext_module_kind_SINGLEPHASE;
1687
    }
1688
    else if (def->m_slots != NULL) {
1689
        kind = _Py_ext_module_kind_MULTIPHASE;
1690
    }
1691
    else if (check_size && def->m_size == -1) {
1692
        kind = _Py_ext_module_kind_SINGLEPHASE;
1693
    }
1694
    else if (def->m_base.m_init != NULL) {
1695
        kind = _Py_ext_module_kind_SINGLEPHASE;
1696
    }
1697
    else {
1698
        // This is probably single-phase init, but a multi-phase
1699
        // module *can* have NULL m_slots.
1700
        kind = _Py_ext_module_kind_UNKNOWN;
1701
    }
1702
    return kind;
1703
}
1704
1705
/* The module might not be fully initialized yet
1706
 * and PyModule_FromDefAndSpec() checks m_size
1707
 * so we skip m_size. */
1708
#define assert_multiphase_def(def)                                  \
1709
    do {                                                            \
1710
        _Py_ext_module_kind kind = _get_extension_kind(def, false); \
1711
        assert(kind == _Py_ext_module_kind_MULTIPHASE               \
1712
                /* m_slots can be NULL. */                          \
1713
                || kind == _Py_ext_module_kind_UNKNOWN);            \
1714
    } while (0)
1715
1716
#define assert_singlephase_def(def)                                 \
1717
    do {                                                            \
1718
        _Py_ext_module_kind kind = _get_extension_kind(def, true);  \
1719
        assert(kind == _Py_ext_module_kind_SINGLEPHASE              \
1720
                || kind == _Py_ext_module_kind_UNKNOWN);            \
1721
    } while (0)
1722
1723
#define assert_singlephase(cached)                                          \
1724
    do {                                                                    \
1725
        _Py_ext_module_kind kind = _get_extension_kind(cached->def, true);  \
1726
        assert(kind == _Py_ext_module_kind_SINGLEPHASE);                    \
1727
    } while (0)
1728
1729
#else  /* defined(NDEBUG) */
1730
#define assert_multiphase_def(def)
1731
#define assert_singlephase_def(def)
1732
#define assert_singlephase(cached)
1733
#endif
1734
1735
1736
struct singlephase_global_update {
1737
    PyModInitFunction m_init;
1738
    Py_ssize_t m_index;
1739
    PyObject *m_dict;
1740
    _Py_ext_module_origin origin;
1741
    bool md_requires_gil;
1742
};
1743
1744
static struct extensions_cache_value *
1745
update_global_state_for_extension(PyThreadState *tstate,
1746
                                  PyObject *path, PyObject *name,
1747
                                  PyModuleDef *def,
1748
                                  struct singlephase_global_update *singlephase)
1749
56
{
1750
56
    struct extensions_cache_value *cached = NULL;
1751
56
    PyModInitFunction m_init = NULL;
1752
56
    PyObject *m_dict = NULL;
1753
1754
    /* Set up for _extensions_cache_set(). */
1755
56
    if (singlephase == NULL) {
1756
0
        assert(def->m_base.m_init == NULL);
1757
0
        assert(def->m_base.m_copy == NULL);
1758
0
    }
1759
56
    else {
1760
56
        if (singlephase->m_init != NULL) {
1761
0
            assert(singlephase->m_dict == NULL);
1762
0
            assert(def->m_base.m_copy == NULL);
1763
0
            assert(def->m_size >= 0);
1764
            /* Remember pointer to module init function. */
1765
            // XXX If two modules share a def then def->m_base will
1766
            // reflect the last one added (here) to the global cache.
1767
            // We should prevent this somehow.  The simplest solution
1768
            // is probably to store m_copy/m_init in the cache along
1769
            // with the def, rather than within the def.
1770
0
            m_init = singlephase->m_init;
1771
0
        }
1772
56
        else if (singlephase->m_dict == NULL) {
1773
            /* It must be a core builtin module. */
1774
56
            assert(is_core_module(tstate->interp, name, path));
1775
56
            assert(def->m_size == -1);
1776
56
            assert(def->m_base.m_copy == NULL);
1777
56
            assert(def->m_base.m_init == NULL);
1778
56
        }
1779
0
        else {
1780
0
            assert(PyDict_Check(singlephase->m_dict));
1781
            // gh-88216: Extensions and def->m_base.m_copy can be updated
1782
            // when the extension module doesn't support sub-interpreters.
1783
0
            assert(def->m_size == -1);
1784
0
            assert(!is_core_module(tstate->interp, name, path));
1785
0
            assert(PyUnicode_CompareWithASCIIString(name, "sys") != 0);
1786
0
            assert(PyUnicode_CompareWithASCIIString(name, "builtins") != 0);
1787
0
            m_dict = singlephase->m_dict;
1788
0
        }
1789
56
    }
1790
1791
    /* Add the module's def to the global cache. */
1792
    // XXX Why special-case the main interpreter?
1793
56
    if (_Py_IsMainInterpreter(tstate->interp) || def->m_size == -1) {
1794
#ifndef NDEBUG
1795
        cached = _extensions_cache_get(path, name);
1796
        assert(cached == NULL || cached->def == def);
1797
#endif
1798
56
        cached = _extensions_cache_set(
1799
56
                path, name, def, m_init, singlephase->m_index, m_dict,
1800
56
                singlephase->origin, singlephase->md_requires_gil);
1801
56
        if (cached == NULL) {
1802
            // XXX Ignore this error?  Doing so would effectively
1803
            // mark the module as not loadable.
1804
0
            return NULL;
1805
0
        }
1806
56
    }
1807
1808
56
    return cached;
1809
56
}
1810
1811
/* For multi-phase init modules, the module is finished
1812
 * by PyModule_FromDefAndSpec(). */
1813
static int
1814
finish_singlephase_extension(PyThreadState *tstate, PyObject *mod,
1815
                             struct extensions_cache_value *cached,
1816
                             PyObject *name, PyObject *modules)
1817
56
{
1818
56
    assert(mod != NULL && PyModule_Check(mod));
1819
56
    assert(cached->def == _PyModule_GetDefOrNull(mod));
1820
1821
56
    Py_ssize_t index = _get_cached_module_index(cached);
1822
56
    if (_modules_by_index_set(tstate->interp, index, mod) < 0) {
1823
0
        return -1;
1824
0
    }
1825
1826
56
    if (modules != NULL) {
1827
56
        if (PyObject_SetItem(modules, name, mod) < 0) {
1828
0
            return -1;
1829
0
        }
1830
56
    }
1831
1832
56
    return 0;
1833
56
}
1834
1835
1836
static PyObject *
1837
reload_singlephase_extension(PyThreadState *tstate,
1838
                             struct extensions_cache_value *cached,
1839
                             struct _Py_ext_module_loader_info *info)
1840
0
{
1841
0
    PyModuleDef *def = cached->def;
1842
0
    assert(def != NULL);
1843
0
    assert_singlephase(cached);
1844
0
    PyObject *mod = NULL;
1845
1846
    /* It may have been successfully imported previously
1847
       in an interpreter that allows legacy modules
1848
       but is not allowed in the current interpreter. */
1849
0
    const char *name_buf = PyUnicode_AsUTF8(info->name);
1850
0
    assert(name_buf != NULL);
1851
0
    if (_PyImport_CheckSubinterpIncompatibleExtensionAllowed(name_buf) < 0) {
1852
0
        return NULL;
1853
0
    }
1854
1855
0
    PyObject *modules = get_modules_dict(tstate, true);
1856
0
    if (def->m_size == -1) {
1857
        /* Module does not support repeated initialization */
1858
0
        assert(cached->m_init == NULL);
1859
0
        assert(def->m_base.m_init == NULL);
1860
        // XXX Copying the cached dict may break interpreter isolation.
1861
        // We could solve this by temporarily acquiring the original
1862
        // interpreter's GIL.
1863
0
        PyObject *m_copy = get_cached_m_dict(cached, info->name, info->path);
1864
0
        if (m_copy == NULL) {
1865
0
            assert(!PyErr_Occurred());
1866
0
            return NULL;
1867
0
        }
1868
0
        mod = import_add_module(tstate, info->name);
1869
0
        if (mod == NULL) {
1870
0
            Py_DECREF(m_copy);
1871
0
            return NULL;
1872
0
        }
1873
0
        PyObject *mdict = PyModule_GetDict(mod);
1874
0
        if (mdict == NULL) {
1875
0
            Py_DECREF(m_copy);
1876
0
            Py_DECREF(mod);
1877
0
            return NULL;
1878
0
        }
1879
0
        int rc = PyDict_Update(mdict, m_copy);
1880
0
        Py_DECREF(m_copy);
1881
0
        if (rc < 0) {
1882
0
            Py_DECREF(mod);
1883
0
            return NULL;
1884
0
        }
1885
#ifdef Py_GIL_DISABLED
1886
        if (def->m_base.m_copy != NULL) {
1887
            // For non-core modules, fetch the GIL slot that was stored by
1888
            // import_run_extension().
1889
            ((PyModuleObject *)mod)->md_requires_gil = cached->md_requires_gil;
1890
        }
1891
#endif
1892
        /* We can't set mod->md_def if it's missing,
1893
         * because _PyImport_ClearModulesByIndex() might break
1894
         * due to violating interpreter isolation.
1895
         * See the note in set_cached_m_dict().
1896
         * Until that is solved, we leave md_def set to NULL. */
1897
0
        assert(_PyModule_GetDefOrNull(mod) == NULL
1898
0
               || _PyModule_GetDefOrNull(mod) == def);
1899
0
    }
1900
0
    else {
1901
0
        assert(cached->m_dict == NULL);
1902
0
        assert(def->m_base.m_copy == NULL);
1903
        // XXX Use cached->m_init.
1904
0
        PyModInitFunction p0 = def->m_base.m_init;
1905
0
        if (p0 == NULL) {
1906
0
            assert(!PyErr_Occurred());
1907
0
            return NULL;
1908
0
        }
1909
0
        struct _Py_ext_module_loader_result res;
1910
0
        if (_PyImport_RunModInitFunc(p0, info, &res) < 0) {
1911
0
            _Py_ext_module_loader_result_apply_error(&res, name_buf);
1912
0
            return NULL;
1913
0
        }
1914
0
        assert(!PyErr_Occurred());
1915
0
        assert(res.err == NULL);
1916
0
        assert(res.kind == _Py_ext_module_kind_SINGLEPHASE);
1917
0
        mod = res.module;
1918
        /* Tchnically, the init function could return a different module def.
1919
         * Then we would probably need to update the global cache.
1920
         * However, we don't expect anyone to change the def. */
1921
0
        assert(res.def == def);
1922
0
        _Py_ext_module_loader_result_clear(&res);
1923
1924
        /* Remember the filename as the __file__ attribute */
1925
0
        if (info->filename != NULL) {
1926
0
            if (PyModule_AddObjectRef(mod, "__file__", info->filename) < 0) {
1927
0
                PyErr_Clear(); /* Not important enough to report */
1928
0
            }
1929
0
        }
1930
1931
0
        if (PyObject_SetItem(modules, info->name, mod) == -1) {
1932
0
            Py_DECREF(mod);
1933
0
            return NULL;
1934
0
        }
1935
0
    }
1936
1937
0
    Py_ssize_t index = _get_cached_module_index(cached);
1938
0
    if (_modules_by_index_set(tstate->interp, index, mod) < 0) {
1939
0
        PyMapping_DelItem(modules, info->name);
1940
0
        Py_DECREF(mod);
1941
0
        return NULL;
1942
0
    }
1943
1944
0
    return mod;
1945
0
}
1946
1947
static PyObject *
1948
import_find_extension(PyThreadState *tstate,
1949
                      struct _Py_ext_module_loader_info *info,
1950
                      struct extensions_cache_value **p_cached)
1951
683
{
1952
    /* Only single-phase init modules will be in the cache. */
1953
683
    struct extensions_cache_value *cached
1954
683
            = _extensions_cache_get(info->path, info->name);
1955
683
    if (cached == NULL) {
1956
683
        return NULL;
1957
683
    }
1958
683
    assert(cached->def != NULL);
1959
0
    assert_singlephase(cached);
1960
0
    *p_cached = cached;
1961
1962
    /* It may have been successfully imported previously
1963
       in an interpreter that allows legacy modules
1964
       but is not allowed in the current interpreter. */
1965
0
    const char *name_buf = PyUnicode_AsUTF8(info->name);
1966
0
    assert(name_buf != NULL);
1967
0
    if (_PyImport_CheckSubinterpIncompatibleExtensionAllowed(name_buf) < 0) {
1968
0
        return NULL;
1969
0
    }
1970
1971
0
    PyObject *mod = reload_singlephase_extension(tstate, cached, info);
1972
0
    if (mod == NULL) {
1973
0
        return NULL;
1974
0
    }
1975
1976
0
    int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
1977
0
    if (verbose) {
1978
0
        PySys_FormatStderr("import %U # previously loaded (%R)\n",
1979
0
                           info->name, info->path);
1980
0
    }
1981
1982
0
    return mod;
1983
0
}
1984
1985
static PyObject *
1986
import_run_modexport(PyThreadState *tstate, PyModExportFunction ex0,
1987
                     struct _Py_ext_module_loader_info *info,
1988
                     PyObject *spec)
1989
0
{
1990
    /* This is like import_run_extension, but avoids interpreter switching
1991
     * and code for for single-phase modules.
1992
     */
1993
0
    PyModuleDef_Slot *slots = ex0();
1994
0
    if (!slots) {
1995
0
        if (!PyErr_Occurred()) {
1996
0
            PyErr_Format(
1997
0
                PyExc_SystemError,
1998
0
                "slot export function for module %s failed without setting an exception",
1999
0
                info->name);
2000
0
        }
2001
0
        return NULL;
2002
0
    }
2003
0
    if (PyErr_Occurred()) {
2004
0
        PyErr_Format(
2005
0
            PyExc_SystemError,
2006
0
            "slot export function for module %s raised unreported exception",
2007
0
            info->name);
2008
0
    }
2009
0
    PyObject *result = PyModule_FromSlotsAndSpec(slots, spec);
2010
0
    if (!result) {
2011
0
        return NULL;
2012
0
    }
2013
0
    if (PyModule_Check(result)) {
2014
0
        PyModuleObject *mod = (PyModuleObject *)result;
2015
0
        if (mod && !mod->md_token) {
2016
0
            mod->md_token = slots;
2017
0
        }
2018
0
    }
2019
0
    return result;
2020
0
}
2021
2022
static PyObject *
2023
import_run_extension(PyThreadState *tstate, PyModInitFunction p0,
2024
                     struct _Py_ext_module_loader_info *info,
2025
                     PyObject *spec, PyObject *modules)
2026
683
{
2027
    /* Core modules go through _PyImport_FixupBuiltin(). */
2028
683
    assert(!is_core_module(tstate->interp, info->name, info->path));
2029
2030
683
    PyObject *mod = NULL;
2031
683
    PyModuleDef *def = NULL;
2032
683
    struct extensions_cache_value *cached = NULL;
2033
683
    const char *name_buf = PyBytes_AS_STRING(info->name_encoded);
2034
2035
    /* We cannot know if the module is single-phase init or
2036
     * multi-phase init until after we call its init function. Even
2037
     * in isolated interpreters (that do not support single-phase init),
2038
     * the init function will run without restriction.  For multi-phase
2039
     * init modules that isn't a problem because the init function only
2040
     * runs PyModuleDef_Init() on the module's def and then returns it.
2041
     *
2042
     * However, for single-phase init the module's init function will
2043
     * create the module, create other objects (and allocate other
2044
     * memory), populate it and its module state, and initialize static
2045
     * types.  Some modules store other objects and data in global C
2046
     * variables and register callbacks with the runtime/stdlib or
2047
     * even external libraries (which is part of why we can't just
2048
     * dlclose() the module in the error case).  That's a problem
2049
     * for isolated interpreters since all of the above happens
2050
     * and only then * will the import fail.  Memory will leak,
2051
     * callbacks will still get used, and sometimes there
2052
     * will be crashes (memory access violations
2053
     * and use-after-free).
2054
     *
2055
     * To put it another way, if the module is single-phase init
2056
     * then the import will probably break interpreter isolation
2057
     * and should fail ASAP.  However, the module's init function
2058
     * will still get run.  That means it may still store state
2059
     * in the shared-object/DLL address space (which never gets
2060
     * closed/cleared), including objects (e.g. static types).
2061
     * This is a problem for isolated subinterpreters since each
2062
     * has its own object allocator.  If the loaded shared-object
2063
     * still holds a reference to an object after the corresponding
2064
     * interpreter has finalized then either we must let it leak
2065
     * or else any later use of that object by another interpreter
2066
     * (or across multiple init-fini cycles) will crash the process.
2067
     *
2068
     * To avoid all of that, we make sure the module's init function
2069
     * is always run first with the main interpreter active.  If it was
2070
     * already the main interpreter then we can continue loading the
2071
     * module like normal.  Otherwise, right after the init function,
2072
     * we take care of some import state bookkeeping, switch back
2073
     * to the subinterpreter, check for single-phase init,
2074
     * and then continue loading like normal. */
2075
2076
683
    bool switched = false;
2077
    /* We *could* leave in place a legacy interpreter here
2078
     * (one that shares obmalloc/GIL with main interp),
2079
     * but there isn't a big advantage, we anticipate
2080
     * such interpreters will be increasingly uncommon,
2081
     * and the code is a bit simpler if we always switch
2082
     * to the main interpreter. */
2083
683
    PyThreadState *main_tstate = switch_to_main_interpreter(tstate);
2084
683
    if (main_tstate == NULL) {
2085
0
        return NULL;
2086
0
    }
2087
683
    else if (main_tstate != tstate) {
2088
0
        switched = true;
2089
        /* In the switched case, we could play it safe
2090
         * by getting the main interpreter's import lock here.
2091
         * It's unlikely to matter though. */
2092
0
    }
2093
2094
683
    struct _Py_ext_module_loader_result res;
2095
683
    int rc = _PyImport_RunModInitFunc(p0, info, &res);
2096
683
    if (rc < 0) {
2097
        /* We discard res.def. */
2098
0
        assert(res.module == NULL);
2099
0
    }
2100
683
    else {
2101
683
        assert(!PyErr_Occurred());
2102
683
        assert(res.err == NULL);
2103
2104
683
        mod = res.module;
2105
683
        res.module = NULL;
2106
683
        def = res.def;
2107
683
        assert(def != NULL);
2108
2109
        /* Do anything else that should be done
2110
         * while still using the main interpreter. */
2111
683
        if (res.kind == _Py_ext_module_kind_SINGLEPHASE) {
2112
            /* Remember the filename as the __file__ attribute */
2113
0
            if (info->filename != NULL) {
2114
0
                PyObject *filename = NULL;
2115
0
                if (switched) {
2116
                    // The original filename may be allocated by subinterpreter's
2117
                    // obmalloc, so we create a copy here.
2118
0
                    filename = _PyUnicode_Copy(info->filename);
2119
0
                    if (filename == NULL) {
2120
0
                        return NULL;
2121
0
                    }
2122
0
                } else {
2123
0
                    filename = Py_NewRef(info->filename);
2124
0
                }
2125
                // XXX There's a refleak somewhere with the filename.
2126
                // Until we can track it down, we immortalize it.
2127
0
                PyInterpreterState *interp = _PyInterpreterState_GET();
2128
0
                _PyUnicode_InternImmortal(interp, &filename);
2129
2130
0
                if (PyModule_AddObjectRef(mod, "__file__", filename) < 0) {
2131
0
                    PyErr_Clear(); /* Not important enough to report */
2132
0
                }
2133
0
            }
2134
2135
            /* Update global import state. */
2136
0
            assert(def->m_base.m_index != 0);
2137
0
            struct singlephase_global_update singlephase = {
2138
                // XXX Modules that share a def should each get their own index,
2139
                // whereas currently they share (which means the per-interpreter
2140
                // cache is less reliable than it should be).
2141
0
                .m_index=def->m_base.m_index,
2142
0
                .origin=info->origin,
2143
#ifdef Py_GIL_DISABLED
2144
                .md_requires_gil=((PyModuleObject *)mod)->md_requires_gil,
2145
#endif
2146
0
            };
2147
            // gh-88216: Extensions and def->m_base.m_copy can be updated
2148
            // when the extension module doesn't support sub-interpreters.
2149
0
            if (def->m_size == -1) {
2150
                /* We will reload from m_copy. */
2151
0
                assert(def->m_base.m_init == NULL);
2152
0
                singlephase.m_dict = PyModule_GetDict(mod);
2153
0
                assert(singlephase.m_dict != NULL);
2154
0
            }
2155
0
            else {
2156
                /* We will reload via the init function. */
2157
0
                assert(def->m_size >= 0);
2158
0
                assert(def->m_base.m_copy == NULL);
2159
0
                singlephase.m_init = p0;
2160
0
            }
2161
0
            cached = update_global_state_for_extension(
2162
0
                    main_tstate, info->path, info->name, def, &singlephase);
2163
0
            if (cached == NULL) {
2164
0
                assert(PyErr_Occurred());
2165
0
                goto main_finally;
2166
0
            }
2167
0
        }
2168
683
    }
2169
2170
683
main_finally:
2171
    /* Switch back to the subinterpreter. */
2172
683
    if (switched) {
2173
0
        assert(main_tstate != tstate);
2174
0
        switch_back_from_main_interpreter(tstate, main_tstate, mod);
2175
        /* Any module we got from the init function will have to be
2176
         * reloaded in the subinterpreter. */
2177
0
        mod = NULL;
2178
0
    }
2179
2180
    /*****************************************************************/
2181
    /* At this point we are back to the interpreter we started with. */
2182
    /*****************************************************************/
2183
2184
    /* Finally we handle the error return from _PyImport_RunModInitFunc(). */
2185
683
    if (rc < 0) {
2186
0
        _Py_ext_module_loader_result_apply_error(&res, name_buf);
2187
0
        goto error;
2188
0
    }
2189
2190
683
    if (res.kind == _Py_ext_module_kind_MULTIPHASE) {
2191
683
        assert_multiphase_def(def);
2192
683
        assert(mod == NULL);
2193
        /* Note that we cheat a little by not repeating the calls
2194
         * to _PyImport_GetModuleExportHooks() and _PyImport_RunModInitFunc(). */
2195
683
        mod = PyModule_FromDefAndSpec(def, spec);
2196
683
        if (mod == NULL) {
2197
0
            goto error;
2198
0
        }
2199
683
    }
2200
0
    else {
2201
0
        assert(res.kind == _Py_ext_module_kind_SINGLEPHASE);
2202
0
        assert_singlephase_def(def);
2203
2204
0
        if (_PyImport_CheckSubinterpIncompatibleExtensionAllowed(name_buf) < 0) {
2205
0
            goto error;
2206
0
        }
2207
0
        assert(!PyErr_Occurred());
2208
2209
0
        if (switched) {
2210
            /* We switched to the main interpreter to run the init
2211
             * function, so now we will "reload" the module from the
2212
             * cached data using the original subinterpreter. */
2213
0
            assert(mod == NULL);
2214
0
            mod = reload_singlephase_extension(tstate, cached, info);
2215
0
            if (mod == NULL) {
2216
0
                goto error;
2217
0
            }
2218
0
            assert(!PyErr_Occurred());
2219
0
            assert(PyModule_Check(mod));
2220
0
        }
2221
0
        else {
2222
0
            assert(mod != NULL);
2223
0
            assert(PyModule_Check(mod));
2224
2225
            /* Update per-interpreter import state. */
2226
0
            PyObject *modules = get_modules_dict(tstate, true);
2227
0
            if (finish_singlephase_extension(
2228
0
                    tstate, mod, cached, info->name, modules) < 0)
2229
0
            {
2230
0
                goto error;
2231
0
            }
2232
0
        }
2233
0
    }
2234
2235
683
    _Py_ext_module_loader_result_clear(&res);
2236
683
    return mod;
2237
2238
0
error:
2239
0
    Py_XDECREF(mod);
2240
0
    _Py_ext_module_loader_result_clear(&res);
2241
0
    return NULL;
2242
683
}
2243
2244
2245
// Used in _PyImport_ClearExtension; see notes there.
2246
static int
2247
clear_singlephase_extension(PyInterpreterState *interp,
2248
                            PyObject *name, PyObject *path)
2249
0
{
2250
0
    struct extensions_cache_value *cached = _extensions_cache_get(path, name);
2251
0
    if (cached == NULL) {
2252
0
        if (PyErr_Occurred()) {
2253
0
            return -1;
2254
0
        }
2255
0
        return 0;
2256
0
    }
2257
0
    PyModuleDef *def = cached->def;
2258
2259
    /* Clear data set when the module was initially loaded. */
2260
0
    def->m_base.m_init = NULL;
2261
0
    Py_CLEAR(def->m_base.m_copy);
2262
0
    def->m_base.m_index = 0;
2263
2264
    /* Clear the PyState_*Module() cache entry. */
2265
0
    Py_ssize_t index = _get_cached_module_index(cached);
2266
0
    if (_modules_by_index_check(interp, index) == NULL) {
2267
0
        if (_modules_by_index_clear_one(interp, index) < 0) {
2268
0
            return -1;
2269
0
        }
2270
0
    }
2271
2272
    /* We must use the main interpreter to clean up the cache.
2273
     * See the note in import_run_extension(). */
2274
0
    PyThreadState *tstate = PyThreadState_GET();
2275
0
    PyThreadState *main_tstate = switch_to_main_interpreter(tstate);
2276
0
    if (main_tstate == NULL) {
2277
0
        return -1;
2278
0
    }
2279
2280
    /* Clear the cached module def. */
2281
0
    _extensions_cache_delete(path, name);
2282
2283
0
    if (main_tstate != tstate) {
2284
0
        switch_back_from_main_interpreter(tstate, main_tstate, NULL);
2285
0
    }
2286
2287
0
    return 0;
2288
0
}
2289
2290
2291
/*******************/
2292
/* builtin modules */
2293
/*******************/
2294
2295
int
2296
_PyImport_FixupBuiltin(PyThreadState *tstate, PyObject *mod, const char *name,
2297
                       PyObject *modules)
2298
56
{
2299
56
    int res = -1;
2300
56
    assert(mod != NULL && PyModule_Check(mod));
2301
2302
56
    PyObject *nameobj;
2303
56
    nameobj = PyUnicode_InternFromString(name);
2304
56
    if (nameobj == NULL) {
2305
0
        return -1;
2306
0
    }
2307
2308
56
    PyModuleDef *def = _PyModule_GetDefOrNull(mod);
2309
56
    if (def == NULL) {
2310
0
        assert(!PyErr_Occurred());
2311
0
        PyErr_BadInternalCall();
2312
0
        goto finally;
2313
0
    }
2314
2315
    /* We only use _PyImport_FixupBuiltin() for the core builtin modules
2316
     * (sys and builtins).  These modules are single-phase init with no
2317
     * module state, but we also don't populate def->m_base.m_copy
2318
     * for them. */
2319
56
    assert(is_core_module(tstate->interp, nameobj, nameobj));
2320
56
    assert_singlephase_def(def);
2321
56
    assert(def->m_size == -1);
2322
56
    assert(def->m_base.m_copy == NULL);
2323
56
    assert(def->m_base.m_index >= 0);
2324
2325
    /* We aren't using import_find_extension() for core modules,
2326
     * so we have to do the extra check to make sure the module
2327
     * isn't already in the global cache before calling
2328
     * update_global_state_for_extension(). */
2329
56
    struct extensions_cache_value *cached
2330
56
            = _extensions_cache_get(nameobj, nameobj);
2331
56
    if (cached == NULL) {
2332
56
        struct singlephase_global_update singlephase = {
2333
56
            .m_index=def->m_base.m_index,
2334
            /* We don't want def->m_base.m_copy populated. */
2335
56
            .m_dict=NULL,
2336
56
            .origin=_Py_ext_module_origin_CORE,
2337
#ifdef Py_GIL_DISABLED
2338
            /* Unused when m_dict == NULL. */
2339
            .md_requires_gil=false,
2340
#endif
2341
56
        };
2342
56
        cached = update_global_state_for_extension(
2343
56
                tstate, nameobj, nameobj, def, &singlephase);
2344
56
        if (cached == NULL) {
2345
0
            goto finally;
2346
0
        }
2347
56
    }
2348
2349
56
    if (finish_singlephase_extension(tstate, mod, cached, nameobj, modules) < 0) {
2350
0
        goto finally;
2351
0
    }
2352
2353
56
    res = 0;
2354
2355
56
finally:
2356
56
    Py_DECREF(nameobj);
2357
56
    return res;
2358
56
}
2359
2360
/* Helper to test for built-in module */
2361
2362
static int
2363
is_builtin(PyObject *name)
2364
14.3k
{
2365
14.3k
    int i;
2366
14.3k
    struct _inittab *inittab = INITTAB;
2367
549k
    for (i = 0; inittab[i].name != NULL; i++) {
2368
535k
        if (_PyUnicode_EqualToASCIIString(name, inittab[i].name)) {
2369
531
            if (inittab[i].initfunc == NULL)
2370
0
                return -1;
2371
531
            else
2372
531
                return 1;
2373
531
        }
2374
535k
    }
2375
13.8k
    return 0;
2376
14.3k
}
2377
2378
static PyModInitFunction
2379
lookup_inittab_initfunc(const struct _Py_ext_module_loader_info* info)
2380
559
{
2381
10.3k
    for (struct _inittab *p = INITTAB; p->name != NULL; p++) {
2382
10.3k
        if (_PyUnicode_EqualToASCIIString(info->name, p->name)) {
2383
559
            return (PyModInitFunction)p->initfunc;
2384
559
        }
2385
10.3k
    }
2386
    // not found
2387
0
    return NULL;
2388
559
}
2389
2390
static PyObject*
2391
create_builtin(
2392
    PyThreadState *tstate, PyObject *name,
2393
    PyObject *spec,
2394
    PyModInitFunction initfunc)
2395
559
{
2396
559
    struct _Py_ext_module_loader_info info;
2397
559
    if (_Py_ext_module_loader_info_init_for_builtin(&info, name) < 0) {
2398
0
        return NULL;
2399
0
    }
2400
2401
559
    struct extensions_cache_value *cached = NULL;
2402
559
    PyObject *mod = import_find_extension(tstate, &info, &cached);
2403
559
    if (mod != NULL) {
2404
0
        assert(!_PyErr_Occurred(tstate));
2405
0
        assert(cached != NULL);
2406
        /* The module might not have md_def set in certain reload cases. */
2407
0
        assert(_PyModule_GetDefOrNull(mod) == NULL
2408
0
                || cached->def == _PyModule_GetDefOrNull(mod));
2409
0
        assert_singlephase(cached);
2410
0
        goto finally;
2411
0
    }
2412
559
    else if (_PyErr_Occurred(tstate)) {
2413
0
        goto finally;
2414
0
    }
2415
2416
    /* If the module was added to the global cache
2417
     * but def->m_base.m_copy was cleared (e.g. subinterp fini)
2418
     * then we have to do a little dance here. */
2419
559
    if (cached != NULL) {
2420
0
        assert(cached->def->m_base.m_copy == NULL);
2421
        /* For now we clear the cache and move on. */
2422
0
        _extensions_cache_delete(info.path, info.name);
2423
0
    }
2424
2425
559
    PyModInitFunction p0 = initfunc;
2426
559
    if (p0 == NULL) {
2427
559
        p0 = lookup_inittab_initfunc(&info);
2428
559
        if (p0 == NULL) {
2429
            /* Cannot re-init internal module ("sys" or "builtins") */
2430
0
            assert(is_core_module(tstate->interp, info.name, info.path));
2431
0
            mod = import_add_module(tstate, info.name);
2432
0
            goto finally;
2433
0
        }
2434
559
    }
2435
2436
#ifdef Py_GIL_DISABLED
2437
    // This call (and the corresponding call to _PyImport_CheckGILForModule())
2438
    // would ideally be inside import_run_extension(). They are kept in the
2439
    // callers for now because that would complicate the control flow inside
2440
    // import_run_extension(). It should be possible to restructure
2441
    // import_run_extension() to address this.
2442
    _PyEval_EnableGILTransient(tstate);
2443
#endif
2444
    /* Now load it. */
2445
559
    mod = import_run_extension(
2446
559
                    tstate, p0, &info, spec, get_modules_dict(tstate, true));
2447
#ifdef Py_GIL_DISABLED
2448
    if (_PyImport_CheckGILForModule(mod, info.name) < 0) {
2449
        Py_CLEAR(mod);
2450
        goto finally;
2451
    }
2452
#endif
2453
2454
559
finally:
2455
559
    _Py_ext_module_loader_info_clear(&info);
2456
559
    return mod;
2457
559
}
2458
2459
PyObject*
2460
PyImport_CreateModuleFromInitfunc(
2461
    PyObject *spec, PyObject *(*initfunc)(void))
2462
0
{
2463
0
    if (initfunc == NULL) {
2464
0
        PyErr_BadInternalCall();
2465
0
        return NULL;
2466
0
    }
2467
2468
0
    PyThreadState *tstate = _PyThreadState_GET();
2469
2470
0
    PyObject *name = PyObject_GetAttr(spec, &_Py_ID(name));
2471
0
    if (name == NULL) {
2472
0
        return NULL;
2473
0
    }
2474
2475
0
    if (!PyUnicode_Check(name)) {
2476
0
        PyErr_Format(PyExc_TypeError,
2477
0
                     "spec name must be string, not %T", name);
2478
0
        Py_DECREF(name);
2479
0
        return NULL;
2480
0
    }
2481
2482
0
    PyObject *mod = create_builtin(tstate, name, spec, initfunc);
2483
0
    Py_DECREF(name);
2484
0
    return mod;
2485
0
}
2486
2487
/*****************************/
2488
/* the builtin modules table */
2489
/*****************************/
2490
2491
/* API for embedding applications that want to add their own entries
2492
   to the table of built-in modules.  This should normally be called
2493
   *before* Py_Initialize().  When the table resize fails, -1 is
2494
   returned and the existing table is unchanged.
2495
2496
   After a similar function by Just van Rossum. */
2497
2498
int
2499
PyImport_ExtendInittab(struct _inittab *newtab)
2500
0
{
2501
0
    struct _inittab *p;
2502
0
    size_t i, n;
2503
0
    int res = 0;
2504
2505
0
    if (INITTAB != NULL) {
2506
0
        Py_FatalError("PyImport_ExtendInittab() may not be called after Py_Initialize()");
2507
0
    }
2508
2509
    /* Count the number of entries in both tables */
2510
0
    for (n = 0; newtab[n].name != NULL; n++)
2511
0
        ;
2512
0
    if (n == 0)
2513
0
        return 0; /* Nothing to do */
2514
0
    for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2515
0
        ;
2516
2517
    /* Force default raw memory allocator to get a known allocator to be able
2518
       to release the memory in _PyImport_Fini2() */
2519
    /* Allocate new memory for the combined table */
2520
0
    p = NULL;
2521
0
    if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
2522
0
        size_t size = sizeof(struct _inittab) * (i + n + 1);
2523
0
        p = _PyMem_DefaultRawRealloc(inittab_copy, size);
2524
0
    }
2525
0
    if (p == NULL) {
2526
0
        res = -1;
2527
0
        goto done;
2528
0
    }
2529
2530
    /* Copy the tables into the new memory at the first call
2531
       to PyImport_ExtendInittab(). */
2532
0
    if (inittab_copy != PyImport_Inittab) {
2533
0
        memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2534
0
    }
2535
0
    memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2536
0
    PyImport_Inittab = inittab_copy = p;
2537
0
done:
2538
0
    return res;
2539
0
}
2540
2541
/* Shorthand to add a single entry given a name and a function */
2542
2543
int
2544
PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
2545
0
{
2546
0
    struct _inittab newtab[2];
2547
2548
0
    if (INITTAB != NULL) {
2549
0
        Py_FatalError("PyImport_AppendInittab() may not be called after Py_Initialize()");
2550
0
    }
2551
2552
0
    memset(newtab, '\0', sizeof newtab);
2553
2554
0
    newtab[0].name = name;
2555
0
    newtab[0].initfunc = initfunc;
2556
2557
0
    return PyImport_ExtendInittab(newtab);
2558
0
}
2559
2560
2561
/* the internal table */
2562
2563
static int
2564
init_builtin_modules_table(void)
2565
28
{
2566
28
    size_t size;
2567
1.09k
    for (size = 0; PyImport_Inittab[size].name != NULL; size++)
2568
1.06k
        ;
2569
28
    size++;
2570
2571
    /* Make the copy. */
2572
28
    struct _inittab *copied = _PyMem_DefaultRawMalloc(size * sizeof(struct _inittab));
2573
28
    if (copied == NULL) {
2574
0
        return -1;
2575
0
    }
2576
28
    memcpy(copied, PyImport_Inittab, size * sizeof(struct _inittab));
2577
28
    INITTAB = copied;
2578
28
    return 0;
2579
28
}
2580
2581
static void
2582
fini_builtin_modules_table(void)
2583
0
{
2584
0
    struct _inittab *inittab = INITTAB;
2585
0
    INITTAB = NULL;
2586
0
    _PyMem_DefaultRawFree(inittab);
2587
0
}
2588
2589
PyObject *
2590
_PyImport_GetBuiltinModuleNames(void)
2591
28
{
2592
28
    PyObject *list = PyList_New(0);
2593
28
    if (list == NULL) {
2594
0
        return NULL;
2595
0
    }
2596
28
    struct _inittab *inittab = INITTAB;
2597
1.09k
    for (Py_ssize_t i = 0; inittab[i].name != NULL; i++) {
2598
1.06k
        PyObject *name = PyUnicode_FromString(inittab[i].name);
2599
1.06k
        if (name == NULL) {
2600
0
            Py_DECREF(list);
2601
0
            return NULL;
2602
0
        }
2603
1.06k
        if (PyList_Append(list, name) < 0) {
2604
0
            Py_DECREF(name);
2605
0
            Py_DECREF(list);
2606
0
            return NULL;
2607
0
        }
2608
1.06k
        Py_DECREF(name);
2609
1.06k
    }
2610
28
    return list;
2611
28
}
2612
2613
2614
/********************/
2615
/* the magic number */
2616
/********************/
2617
2618
/* Helper for pythonrun.c -- return magic number and tag. */
2619
2620
long
2621
PyImport_GetMagicNumber(void)
2622
0
{
2623
0
    return PYC_MAGIC_NUMBER_TOKEN;
2624
0
}
2625
2626
extern const char * _PySys_ImplCacheTag;
2627
2628
const char *
2629
PyImport_GetMagicTag(void)
2630
0
{
2631
0
    return _PySys_ImplCacheTag;
2632
0
}
2633
2634
2635
/*********************************/
2636
/* a Python module's code object */
2637
/*********************************/
2638
2639
/* Execute a code object in a module and return the module object
2640
 * WITH INCREMENTED REFERENCE COUNT.  If an error occurs, name is
2641
 * removed from sys.modules, to avoid leaving damaged module objects
2642
 * in sys.modules.  The caller may wish to restore the original
2643
 * module object (if any) in this case; PyImport_ReloadModule is an
2644
 * example.
2645
 *
2646
 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
2647
 * interface.  The other two exist primarily for backward compatibility.
2648
 */
2649
PyObject *
2650
PyImport_ExecCodeModule(const char *name, PyObject *co)
2651
0
{
2652
0
    return PyImport_ExecCodeModuleWithPathnames(
2653
0
        name, co, (char *)NULL, (char *)NULL);
2654
0
}
2655
2656
PyObject *
2657
PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
2658
0
{
2659
0
    return PyImport_ExecCodeModuleWithPathnames(
2660
0
        name, co, pathname, (char *)NULL);
2661
0
}
2662
2663
PyObject *
2664
PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
2665
                                     const char *pathname,
2666
                                     const char *cpathname)
2667
0
{
2668
0
    PyObject *m = NULL;
2669
0
    PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
2670
2671
0
    nameobj = PyUnicode_FromString(name);
2672
0
    if (nameobj == NULL)
2673
0
        return NULL;
2674
2675
0
    if (cpathname != NULL) {
2676
0
        cpathobj = PyUnicode_DecodeFSDefault(cpathname);
2677
0
        if (cpathobj == NULL)
2678
0
            goto error;
2679
0
    }
2680
0
    else
2681
0
        cpathobj = NULL;
2682
2683
0
    if (pathname != NULL) {
2684
0
        pathobj = PyUnicode_DecodeFSDefault(pathname);
2685
0
        if (pathobj == NULL)
2686
0
            goto error;
2687
0
    }
2688
0
    else if (cpathobj != NULL) {
2689
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
2690
2691
0
        if (interp == NULL) {
2692
0
            Py_FatalError("no current interpreter");
2693
0
        }
2694
2695
0
        external= PyObject_GetAttrString(IMPORTLIB(interp),
2696
0
                                         "_bootstrap_external");
2697
0
        if (external != NULL) {
2698
0
            pathobj = PyObject_CallMethodOneArg(
2699
0
                external, &_Py_ID(_get_sourcefile), cpathobj);
2700
0
            Py_DECREF(external);
2701
0
        }
2702
0
        if (pathobj == NULL)
2703
0
            PyErr_Clear();
2704
0
    }
2705
0
    else
2706
0
        pathobj = NULL;
2707
2708
0
    m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
2709
0
error:
2710
0
    Py_DECREF(nameobj);
2711
0
    Py_XDECREF(pathobj);
2712
0
    Py_XDECREF(cpathobj);
2713
0
    return m;
2714
0
}
2715
2716
static PyObject *
2717
module_dict_for_exec(PyThreadState *tstate, PyObject *name)
2718
28
{
2719
28
    PyObject *m, *d;
2720
2721
28
    m = import_add_module(tstate, name);
2722
28
    if (m == NULL)
2723
0
        return NULL;
2724
    /* If the module is being reloaded, we get the old module back
2725
       and re-use its dict to exec the new code. */
2726
28
    d = PyModule_GetDict(m);
2727
28
    int r = PyDict_Contains(d, &_Py_ID(__builtins__));
2728
28
    if (r == 0) {
2729
28
        r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins());
2730
28
    }
2731
28
    if (r < 0) {
2732
0
        remove_module(tstate, name);
2733
0
        Py_DECREF(m);
2734
0
        return NULL;
2735
0
    }
2736
2737
28
    Py_INCREF(d);
2738
28
    Py_DECREF(m);
2739
28
    return d;
2740
28
}
2741
2742
static PyObject *
2743
exec_code_in_module(PyThreadState *tstate, PyObject *name,
2744
                    PyObject *module_dict, PyObject *code_object)
2745
28
{
2746
28
    PyObject *v, *m;
2747
2748
28
    v = PyEval_EvalCode(code_object, module_dict, module_dict);
2749
28
    if (v == NULL) {
2750
0
        remove_module(tstate, name);
2751
0
        return NULL;
2752
0
    }
2753
28
    Py_DECREF(v);
2754
2755
28
    m = import_get_module(tstate, name);
2756
28
    if (m == NULL && !_PyErr_Occurred(tstate)) {
2757
0
        _PyErr_Format(tstate, PyExc_ImportError,
2758
0
                      "Loaded module %R not found in sys.modules",
2759
0
                      name);
2760
0
    }
2761
2762
28
    return m;
2763
28
}
2764
2765
PyObject*
2766
PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
2767
                              PyObject *cpathname)
2768
0
{
2769
0
    PyThreadState *tstate = _PyThreadState_GET();
2770
0
    PyObject *d, *external, *res;
2771
2772
0
    d = module_dict_for_exec(tstate, name);
2773
0
    if (d == NULL) {
2774
0
        return NULL;
2775
0
    }
2776
2777
0
    if (pathname == NULL) {
2778
0
        pathname = ((PyCodeObject *)co)->co_filename;
2779
0
    }
2780
0
    external = PyObject_GetAttrString(IMPORTLIB(tstate->interp),
2781
0
                                      "_bootstrap_external");
2782
0
    if (external == NULL) {
2783
0
        Py_DECREF(d);
2784
0
        return NULL;
2785
0
    }
2786
0
    res = PyObject_CallMethodObjArgs(external, &_Py_ID(_fix_up_module),
2787
0
                                     d, name, pathname, cpathname, NULL);
2788
0
    Py_DECREF(external);
2789
0
    if (res != NULL) {
2790
0
        Py_DECREF(res);
2791
0
        res = exec_code_in_module(tstate, name, d, co);
2792
0
    }
2793
0
    Py_DECREF(d);
2794
0
    return res;
2795
0
}
2796
2797
2798
static void
2799
update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
2800
0
{
2801
0
    PyObject *constants, *tmp;
2802
0
    Py_ssize_t i, n;
2803
2804
0
    if (PyUnicode_Compare(co->co_filename, oldname))
2805
0
        return;
2806
2807
0
    Py_XSETREF(co->co_filename, Py_NewRef(newname));
2808
2809
0
    constants = co->co_consts;
2810
0
    n = PyTuple_GET_SIZE(constants);
2811
0
    for (i = 0; i < n; i++) {
2812
0
        tmp = PyTuple_GET_ITEM(constants, i);
2813
0
        if (PyCode_Check(tmp))
2814
0
            update_code_filenames((PyCodeObject *)tmp,
2815
0
                                  oldname, newname);
2816
0
    }
2817
0
}
2818
2819
static void
2820
update_compiled_module(PyCodeObject *co, PyObject *newname)
2821
6.22k
{
2822
6.22k
    PyObject *oldname;
2823
2824
6.22k
    if (PyUnicode_Compare(co->co_filename, newname) == 0)
2825
6.22k
        return;
2826
2827
0
    oldname = co->co_filename;
2828
0
    Py_INCREF(oldname);
2829
0
    update_code_filenames(co, oldname, newname);
2830
0
    Py_DECREF(oldname);
2831
0
}
2832
2833
2834
/******************/
2835
/* frozen modules */
2836
/******************/
2837
2838
/* Return true if the name is an alias.  In that case, "alias" is set
2839
   to the original module name.  If it is an alias but the original
2840
   module isn't known then "alias" is set to NULL while true is returned. */
2841
static bool
2842
resolve_module_alias(const char *name, const struct _module_alias *aliases,
2843
                     const char **alias)
2844
758
{
2845
758
    const struct _module_alias *entry;
2846
5.75k
    for (entry = aliases; ; entry++) {
2847
5.75k
        if (entry->name == NULL) {
2848
            /* It isn't an alias. */
2849
618
            return false;
2850
618
        }
2851
5.14k
        if (strcmp(name, entry->name) == 0) {
2852
140
            if (alias != NULL) {
2853
140
                *alias = entry->orig;
2854
140
            }
2855
140
            return true;
2856
140
        }
2857
5.14k
    }
2858
758
}
2859
2860
static bool
2861
use_frozen(void)
2862
14.0k
{
2863
14.0k
    PyInterpreterState *interp = _PyInterpreterState_GET();
2864
14.0k
    int override = OVERRIDE_FROZEN_MODULES(interp);
2865
14.0k
    if (override > 0) {
2866
0
        return true;
2867
0
    }
2868
14.0k
    else if (override < 0) {
2869
0
        return false;
2870
0
    }
2871
14.0k
    else {
2872
14.0k
        return interp->config.use_frozen_modules;
2873
14.0k
    }
2874
14.0k
}
2875
2876
static PyObject *
2877
list_frozen_module_names(void)
2878
0
{
2879
0
    PyObject *names = PyList_New(0);
2880
0
    if (names == NULL) {
2881
0
        return NULL;
2882
0
    }
2883
0
    bool enabled = use_frozen();
2884
0
    const struct _frozen *p;
2885
0
#define ADD_MODULE(name) \
2886
0
    do { \
2887
0
        PyObject *nameobj = PyUnicode_FromString(name); \
2888
0
        if (nameobj == NULL) { \
2889
0
            goto error; \
2890
0
        } \
2891
0
        int res = PyList_Append(names, nameobj); \
2892
0
        Py_DECREF(nameobj); \
2893
0
        if (res != 0) { \
2894
0
            goto error; \
2895
0
        } \
2896
0
    } while(0)
2897
    // We always use the bootstrap modules.
2898
0
    for (p = _PyImport_FrozenBootstrap; ; p++) {
2899
0
        if (p->name == NULL) {
2900
0
            break;
2901
0
        }
2902
0
        ADD_MODULE(p->name);
2903
0
    }
2904
    // Frozen stdlib modules may be disabled.
2905
0
    for (p = _PyImport_FrozenStdlib; ; p++) {
2906
0
        if (p->name == NULL) {
2907
0
            break;
2908
0
        }
2909
0
        if (enabled) {
2910
0
            ADD_MODULE(p->name);
2911
0
        }
2912
0
    }
2913
0
    for (p = _PyImport_FrozenTest; ; p++) {
2914
0
        if (p->name == NULL) {
2915
0
            break;
2916
0
        }
2917
0
        if (enabled) {
2918
0
            ADD_MODULE(p->name);
2919
0
        }
2920
0
    }
2921
0
#undef ADD_MODULE
2922
    // Add any custom modules.
2923
0
    if (PyImport_FrozenModules != NULL) {
2924
0
        for (p = PyImport_FrozenModules; ; p++) {
2925
0
            if (p->name == NULL) {
2926
0
                break;
2927
0
            }
2928
0
            PyObject *nameobj = PyUnicode_FromString(p->name);
2929
0
            if (nameobj == NULL) {
2930
0
                goto error;
2931
0
            }
2932
0
            int found = PySequence_Contains(names, nameobj);
2933
0
            if (found < 0) {
2934
0
                Py_DECREF(nameobj);
2935
0
                goto error;
2936
0
            }
2937
0
            else if (found) {
2938
0
                Py_DECREF(nameobj);
2939
0
            }
2940
0
            else {
2941
0
                int res = PyList_Append(names, nameobj);
2942
0
                Py_DECREF(nameobj);
2943
0
                if (res != 0) {
2944
0
                    goto error;
2945
0
                }
2946
0
            }
2947
0
        }
2948
0
    }
2949
0
    return names;
2950
2951
0
error:
2952
0
    Py_DECREF(names);
2953
0
    return NULL;
2954
0
}
2955
2956
typedef enum {
2957
    FROZEN_OKAY,
2958
    FROZEN_BAD_NAME,    // The given module name wasn't valid.
2959
    FROZEN_NOT_FOUND,   // It wasn't in PyImport_FrozenModules.
2960
    FROZEN_DISABLED,    // -X frozen_modules=off (and not essential)
2961
    FROZEN_EXCLUDED,    /* The PyImport_FrozenModules entry has NULL "code"
2962
                           (module is present but marked as unimportable, stops search). */
2963
    FROZEN_INVALID,     /* The PyImport_FrozenModules entry is bogus
2964
                           (eg. does not contain executable code). */
2965
} frozen_status;
2966
2967
static inline void
2968
set_frozen_error(frozen_status status, PyObject *modname)
2969
0
{
2970
0
    const char *err = NULL;
2971
0
    switch (status) {
2972
0
        case FROZEN_BAD_NAME:
2973
0
        case FROZEN_NOT_FOUND:
2974
0
            err = "No such frozen object named %R";
2975
0
            break;
2976
0
        case FROZEN_DISABLED:
2977
0
            err = "Frozen modules are disabled and the frozen object named %R is not essential";
2978
0
            break;
2979
0
        case FROZEN_EXCLUDED:
2980
0
            err = "Excluded frozen object named %R";
2981
0
            break;
2982
0
        case FROZEN_INVALID:
2983
0
            err = "Frozen object named %R is invalid";
2984
0
            break;
2985
0
        case FROZEN_OKAY:
2986
            // There was no error.
2987
0
            break;
2988
0
        default:
2989
0
            Py_UNREACHABLE();
2990
0
    }
2991
0
    if (err != NULL) {
2992
0
        PyObject *msg = PyUnicode_FromFormat(err, modname);
2993
0
        if (msg == NULL) {
2994
0
            PyErr_Clear();
2995
0
        }
2996
0
        PyErr_SetImportError(msg, modname, NULL);
2997
0
        Py_XDECREF(msg);
2998
0
    }
2999
0
}
3000
3001
static const struct _frozen *
3002
look_up_frozen(const char *name)
3003
14.2k
{
3004
14.2k
    const struct _frozen *p;
3005
    // We always use the bootstrap modules.
3006
56.6k
    for (p = _PyImport_FrozenBootstrap; ; p++) {
3007
56.6k
        if (p->name == NULL) {
3008
            // We hit the end-of-list sentinel value.
3009
14.0k
            break;
3010
14.0k
        }
3011
42.5k
        if (strcmp(name, p->name) == 0) {
3012
196
            return p;
3013
196
        }
3014
42.5k
    }
3015
    // Prefer custom modules, if any.  Frozen stdlib modules can be
3016
    // disabled here by setting "code" to NULL in the array entry.
3017
14.0k
    if (PyImport_FrozenModules != NULL) {
3018
0
        for (p = PyImport_FrozenModules; ; p++) {
3019
0
            if (p->name == NULL) {
3020
0
                break;
3021
0
            }
3022
0
            if (strcmp(name, p->name) == 0) {
3023
0
                return p;
3024
0
            }
3025
0
        }
3026
0
    }
3027
    // Frozen stdlib modules may be disabled.
3028
14.0k
    if (use_frozen()) {
3029
206k
        for (p = _PyImport_FrozenStdlib; ; p++) {
3030
206k
            if (p->name == NULL) {
3031
13.5k
                break;
3032
13.5k
            }
3033
192k
            if (strcmp(name, p->name) == 0) {
3034
562
                return p;
3035
562
            }
3036
192k
        }
3037
162k
        for (p = _PyImport_FrozenTest; ; p++) {
3038
162k
            if (p->name == NULL) {
3039
13.5k
                break;
3040
13.5k
            }
3041
148k
            if (strcmp(name, p->name) == 0) {
3042
0
                return p;
3043
0
            }
3044
148k
        }
3045
13.5k
    }
3046
13.5k
    return NULL;
3047
14.0k
}
3048
3049
struct frozen_info {
3050
    PyObject *nameobj;
3051
    const char *data;
3052
    Py_ssize_t size;
3053
    bool is_package;
3054
    bool is_alias;
3055
    const char *origname;
3056
};
3057
3058
static frozen_status
3059
find_frozen(PyObject *nameobj, struct frozen_info *info)
3060
14.2k
{
3061
14.2k
    if (info != NULL) {
3062
14.2k
        memset(info, 0, sizeof(*info));
3063
14.2k
    }
3064
3065
14.2k
    if (nameobj == NULL || nameobj == Py_None) {
3066
0
        return FROZEN_BAD_NAME;
3067
0
    }
3068
14.2k
    const char *name = PyUnicode_AsUTF8(nameobj);
3069
14.2k
    if (name == NULL) {
3070
        // Note that this function previously used
3071
        // _PyUnicode_EqualToASCIIString().  We clear the error here
3072
        // (instead of propagating it) to match the earlier behavior
3073
        // more closely.
3074
0
        PyErr_Clear();
3075
0
        return FROZEN_BAD_NAME;
3076
0
    }
3077
3078
14.2k
    const struct _frozen *p = look_up_frozen(name);
3079
14.2k
    if (p == NULL) {
3080
13.5k
        return FROZEN_NOT_FOUND;
3081
13.5k
    }
3082
758
    if (info != NULL) {
3083
758
        info->nameobj = nameobj;  // borrowed
3084
758
        info->data = (const char *)p->code;
3085
758
        info->size = p->size;
3086
758
        info->is_package = p->is_package;
3087
758
        if (p->size < 0) {
3088
            // backward compatibility with negative size values
3089
0
            info->size = -(p->size);
3090
0
            info->is_package = true;
3091
0
        }
3092
758
        info->origname = name;
3093
758
        info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
3094
758
                                              &info->origname);
3095
758
    }
3096
758
    if (p->code == NULL) {
3097
        /* It is frozen but marked as un-importable. */
3098
0
        return FROZEN_EXCLUDED;
3099
0
    }
3100
758
    if (p->code[0] == '\0' || p->size == 0) {
3101
        /* Does not contain executable code. */
3102
0
        return FROZEN_INVALID;
3103
0
    }
3104
758
    return FROZEN_OKAY;
3105
758
}
3106
3107
static PyObject *
3108
unmarshal_frozen_code(PyInterpreterState *interp, struct frozen_info *info)
3109
365
{
3110
365
    PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
3111
365
    if (co == NULL) {
3112
        /* Does not contain executable code. */
3113
0
        PyErr_Clear();
3114
0
        set_frozen_error(FROZEN_INVALID, info->nameobj);
3115
0
        return NULL;
3116
0
    }
3117
365
    if (!PyCode_Check(co)) {
3118
        // We stick with TypeError for backward compatibility.
3119
0
        PyErr_Format(PyExc_TypeError,
3120
0
                     "frozen object %R is not a code object",
3121
0
                     info->nameobj);
3122
0
        Py_DECREF(co);
3123
0
        return NULL;
3124
0
    }
3125
365
    return co;
3126
365
}
3127
3128
3129
/* Initialize a frozen module.
3130
   Return 1 for success, 0 if the module is not found, and -1 with
3131
   an exception set if the initialization failed.
3132
   This function is also used from frozenmain.c */
3133
3134
int
3135
PyImport_ImportFrozenModuleObject(PyObject *name)
3136
28
{
3137
28
    PyThreadState *tstate = _PyThreadState_GET();
3138
28
    PyObject *co, *m, *d = NULL;
3139
28
    int err;
3140
3141
28
    struct frozen_info info;
3142
28
    frozen_status status = find_frozen(name, &info);
3143
28
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
3144
0
        return 0;
3145
0
    }
3146
28
    else if (status == FROZEN_BAD_NAME) {
3147
0
        return 0;
3148
0
    }
3149
28
    else if (status != FROZEN_OKAY) {
3150
0
        set_frozen_error(status, name);
3151
0
        return -1;
3152
0
    }
3153
28
    co = unmarshal_frozen_code(tstate->interp, &info);
3154
28
    if (co == NULL) {
3155
0
        return -1;
3156
0
    }
3157
28
    if (info.is_package) {
3158
        /* Set __path__ to the empty list */
3159
0
        PyObject *l;
3160
0
        m = import_add_module(tstate, name);
3161
0
        if (m == NULL)
3162
0
            goto err_return;
3163
0
        d = PyModule_GetDict(m);
3164
0
        l = PyList_New(0);
3165
0
        if (l == NULL) {
3166
0
            Py_DECREF(m);
3167
0
            goto err_return;
3168
0
        }
3169
0
        err = PyDict_SetItemString(d, "__path__", l);
3170
0
        Py_DECREF(l);
3171
0
        Py_DECREF(m);
3172
0
        if (err != 0)
3173
0
            goto err_return;
3174
0
    }
3175
28
    d = module_dict_for_exec(tstate, name);
3176
28
    if (d == NULL) {
3177
0
        goto err_return;
3178
0
    }
3179
28
    m = exec_code_in_module(tstate, name, d, co);
3180
28
    if (m == NULL) {
3181
0
        goto err_return;
3182
0
    }
3183
28
    Py_DECREF(m);
3184
    /* Set __origname__ (consumed in FrozenImporter._setup_module()). */
3185
28
    PyObject *origname;
3186
28
    if (info.origname) {
3187
28
        origname = PyUnicode_FromString(info.origname);
3188
28
        if (origname == NULL) {
3189
0
            goto err_return;
3190
0
        }
3191
28
    }
3192
0
    else {
3193
0
        origname = Py_NewRef(Py_None);
3194
0
    }
3195
28
    err = PyDict_SetItemString(d, "__origname__", origname);
3196
28
    Py_DECREF(origname);
3197
28
    if (err != 0) {
3198
0
        goto err_return;
3199
0
    }
3200
28
    Py_DECREF(d);
3201
28
    Py_DECREF(co);
3202
28
    return 1;
3203
3204
0
err_return:
3205
0
    Py_XDECREF(d);
3206
0
    Py_DECREF(co);
3207
0
    return -1;
3208
28
}
3209
3210
int
3211
PyImport_ImportFrozenModule(const char *name)
3212
28
{
3213
28
    PyObject *nameobj;
3214
28
    int ret;
3215
28
    nameobj = PyUnicode_InternFromString(name);
3216
28
    if (nameobj == NULL)
3217
0
        return -1;
3218
28
    ret = PyImport_ImportFrozenModuleObject(nameobj);
3219
28
    Py_DECREF(nameobj);
3220
28
    return ret;
3221
28
}
3222
3223
3224
/*************/
3225
/* importlib */
3226
/*************/
3227
3228
/* Import the _imp extension by calling manually _imp.create_builtin() and
3229
   _imp.exec_builtin() since importlib is not initialized yet. Initializing
3230
   importlib requires the _imp module: this function fix the bootstrap issue.
3231
 */
3232
static PyObject*
3233
bootstrap_imp(PyThreadState *tstate)
3234
28
{
3235
28
    PyObject *name = PyUnicode_FromString("_imp");
3236
28
    if (name == NULL) {
3237
0
        return NULL;
3238
0
    }
3239
3240
    // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
3241
    // an object with just a name attribute.
3242
    //
3243
    // _imp.__spec__ is overridden by importlib._bootstrap._instal() anyway.
3244
28
    PyObject *attrs = Py_BuildValue("{sO}", "name", name);
3245
28
    if (attrs == NULL) {
3246
0
        goto error;
3247
0
    }
3248
28
    PyObject *spec = _PyNamespace_New(attrs);
3249
28
    Py_DECREF(attrs);
3250
28
    if (spec == NULL) {
3251
0
        goto error;
3252
0
    }
3253
3254
    // Create the _imp module from its definition.
3255
28
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
3256
28
    Py_CLEAR(name);
3257
28
    Py_DECREF(spec);
3258
28
    if (mod == NULL) {
3259
0
        goto error;
3260
0
    }
3261
28
    assert(mod != Py_None);  // not found
3262
3263
    // Execute the _imp module: call imp_module_exec().
3264
28
    if (exec_builtin_or_dynamic(mod) < 0) {
3265
0
        Py_DECREF(mod);
3266
0
        goto error;
3267
0
    }
3268
28
    return mod;
3269
3270
0
error:
3271
0
    Py_XDECREF(name);
3272
0
    return NULL;
3273
28
}
3274
3275
/* Global initializations.  Can be undone by Py_FinalizeEx().  Don't
3276
   call this twice without an intervening Py_FinalizeEx() call.  When
3277
   initializations fail, a fatal error is issued and the function does
3278
   not return.  On return, the first thread and interpreter state have
3279
   been created.
3280
3281
   Locking: you must hold the interpreter lock while calling this.
3282
   (If the lock has not yet been initialized, that's equivalent to
3283
   having the lock, but you cannot use multiple threads.)
3284
3285
*/
3286
static int
3287
init_importlib(PyThreadState *tstate, PyObject *sysmod)
3288
28
{
3289
28
    assert(!_PyErr_Occurred(tstate));
3290
3291
28
    PyInterpreterState *interp = tstate->interp;
3292
28
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
3293
3294
    // Import _importlib through its frozen version, _frozen_importlib.
3295
28
    if (verbose) {
3296
0
        PySys_FormatStderr("import _frozen_importlib # frozen\n");
3297
0
    }
3298
28
    if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
3299
0
        return -1;
3300
0
    }
3301
3302
28
    PyObject *importlib = PyImport_AddModuleRef("_frozen_importlib");
3303
28
    if (importlib == NULL) {
3304
0
        return -1;
3305
0
    }
3306
28
    IMPORTLIB(interp) = importlib;
3307
3308
    // Import the _imp module
3309
28
    if (verbose) {
3310
0
        PySys_FormatStderr("import _imp # builtin\n");
3311
0
    }
3312
28
    PyObject *imp_mod = bootstrap_imp(tstate);
3313
28
    if (imp_mod == NULL) {
3314
0
        return -1;
3315
0
    }
3316
28
    if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
3317
0
        Py_DECREF(imp_mod);
3318
0
        return -1;
3319
0
    }
3320
3321
    // Install importlib as the implementation of import
3322
28
    PyObject *value = PyObject_CallMethod(importlib, "_install",
3323
28
                                          "OO", sysmod, imp_mod);
3324
28
    Py_DECREF(imp_mod);
3325
28
    if (value == NULL) {
3326
0
        return -1;
3327
0
    }
3328
28
    Py_DECREF(value);
3329
3330
28
    assert(!_PyErr_Occurred(tstate));
3331
28
    return 0;
3332
28
}
3333
3334
3335
static int
3336
init_importlib_external(PyInterpreterState *interp)
3337
28
{
3338
28
    PyObject *value;
3339
28
    value = PyObject_CallMethod(IMPORTLIB(interp),
3340
28
                                "_install_external_importers", "");
3341
28
    if (value == NULL) {
3342
0
        return -1;
3343
0
    }
3344
28
    Py_DECREF(value);
3345
28
    return 0;
3346
28
}
3347
3348
PyObject *
3349
_PyImport_GetImportlibLoader(PyInterpreterState *interp,
3350
                             const char *loader_name)
3351
28
{
3352
28
    return PyObject_GetAttrString(IMPORTLIB(interp), loader_name);
3353
28
}
3354
3355
PyObject *
3356
_PyImport_GetImportlibExternalLoader(PyInterpreterState *interp,
3357
                                     const char *loader_name)
3358
0
{
3359
0
    PyObject *bootstrap = PyObject_GetAttrString(IMPORTLIB(interp),
3360
0
                                                 "_bootstrap_external");
3361
0
    if (bootstrap == NULL) {
3362
0
        return NULL;
3363
0
    }
3364
3365
0
    PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
3366
0
    Py_DECREF(bootstrap);
3367
0
    return loader_type;
3368
0
}
3369
3370
PyObject *
3371
_PyImport_BlessMyLoader(PyInterpreterState *interp, PyObject *module_globals)
3372
0
{
3373
0
    PyObject *external = PyObject_GetAttrString(IMPORTLIB(interp),
3374
0
                                                "_bootstrap_external");
3375
0
    if (external == NULL) {
3376
0
        return NULL;
3377
0
    }
3378
3379
0
    PyObject *loader = PyObject_CallMethod(external, "_bless_my_loader",
3380
0
                                           "O", module_globals, NULL);
3381
0
    Py_DECREF(external);
3382
0
    return loader;
3383
0
}
3384
3385
PyObject *
3386
_PyImport_ImportlibModuleRepr(PyInterpreterState *interp, PyObject *m)
3387
0
{
3388
0
    return PyObject_CallMethod(IMPORTLIB(interp), "_module_repr", "O", m);
3389
0
}
3390
3391
3392
/*******************/
3393
3394
/* Return a finder object for a sys.path/pkg.__path__ item 'p',
3395
   possibly by fetching it from the path_importer_cache dict. If it
3396
   wasn't yet cached, traverse path_hooks until a hook is found
3397
   that can handle the path item. Return None if no hook could;
3398
   this tells our caller that the path based finder could not find
3399
   a finder for this path item. Cache the result in
3400
   path_importer_cache. */
3401
3402
static PyObject *
3403
get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
3404
                  PyObject *path_hooks, PyObject *p)
3405
0
{
3406
0
    PyObject *importer;
3407
0
    Py_ssize_t j, nhooks;
3408
3409
0
    if (!PyList_Check(path_hooks)) {
3410
0
        PyErr_SetString(PyExc_RuntimeError, "sys.path_hooks is not a list");
3411
0
        return NULL;
3412
0
    }
3413
0
    if (!PyDict_Check(path_importer_cache)) {
3414
0
        PyErr_SetString(PyExc_RuntimeError, "sys.path_importer_cache is not a dict");
3415
0
        return NULL;
3416
0
    }
3417
3418
0
    nhooks = PyList_Size(path_hooks);
3419
0
    if (nhooks < 0)
3420
0
        return NULL; /* Shouldn't happen */
3421
3422
0
    if (PyDict_GetItemRef(path_importer_cache, p, &importer) != 0) {
3423
        // found or error
3424
0
        return importer;
3425
0
    }
3426
    // not found
3427
    /* set path_importer_cache[p] to None to avoid recursion */
3428
0
    if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
3429
0
        return NULL;
3430
3431
0
    for (j = 0; j < nhooks; j++) {
3432
0
        PyObject *hook = PyList_GetItem(path_hooks, j);
3433
0
        if (hook == NULL)
3434
0
            return NULL;
3435
0
        importer = PyObject_CallOneArg(hook, p);
3436
0
        if (importer != NULL)
3437
0
            break;
3438
3439
0
        if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
3440
0
            return NULL;
3441
0
        }
3442
0
        _PyErr_Clear(tstate);
3443
0
    }
3444
0
    if (importer == NULL) {
3445
0
        Py_RETURN_NONE;
3446
0
    }
3447
0
    if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
3448
0
        Py_DECREF(importer);
3449
0
        return NULL;
3450
0
    }
3451
0
    return importer;
3452
0
}
3453
3454
PyObject *
3455
PyImport_GetImporter(PyObject *path)
3456
0
{
3457
0
    PyThreadState *tstate = _PyThreadState_GET();
3458
0
    PyObject *path_importer_cache = PySys_GetAttrString("path_importer_cache");
3459
0
    if (path_importer_cache == NULL) {
3460
0
        return NULL;
3461
0
    }
3462
0
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
3463
0
    if (path_hooks == NULL) {
3464
0
        Py_DECREF(path_importer_cache);
3465
0
        return NULL;
3466
0
    }
3467
0
    PyObject *importer = get_path_importer(tstate, path_importer_cache, path_hooks, path);
3468
0
    Py_DECREF(path_hooks);
3469
0
    Py_DECREF(path_importer_cache);
3470
0
    return importer;
3471
0
}
3472
3473
3474
/*********************/
3475
/* importing modules */
3476
/*********************/
3477
3478
int
3479
_PyImport_InitDefaultImportFunc(PyInterpreterState *interp)
3480
28
{
3481
    // Get the __import__ function
3482
28
    PyObject *import_func;
3483
28
    if (PyDict_GetItemStringRef(interp->builtins, "__import__", &import_func) <= 0) {
3484
0
        return -1;
3485
0
    }
3486
28
    IMPORT_FUNC(interp) = import_func;
3487
28
    return 0;
3488
28
}
3489
3490
int
3491
_PyImport_IsDefaultImportFunc(PyInterpreterState *interp, PyObject *func)
3492
1.61M
{
3493
1.61M
    return func == IMPORT_FUNC(interp);
3494
1.61M
}
3495
3496
3497
/* Import a module, either built-in, frozen, or external, and return
3498
   its module object WITH INCREMENTED REFERENCE COUNT */
3499
3500
PyObject *
3501
PyImport_ImportModule(const char *name)
3502
422
{
3503
422
    PyObject *pname;
3504
422
    PyObject *result;
3505
3506
422
    pname = PyUnicode_FromString(name);
3507
422
    if (pname == NULL)
3508
0
        return NULL;
3509
422
    result = PyImport_Import(pname);
3510
422
    Py_DECREF(pname);
3511
422
    return result;
3512
422
}
3513
3514
3515
/* Import a module without blocking
3516
 *
3517
 * At first it tries to fetch the module from sys.modules. If the module was
3518
 * never loaded before it loads it with PyImport_ImportModule() unless another
3519
 * thread holds the import lock. In the latter case the function raises an
3520
 * ImportError instead of blocking.
3521
 *
3522
 * Returns the module object with incremented ref count.
3523
 *
3524
 * Removed in 3.15, but kept for stable ABI compatibility.
3525
 */
3526
PyAPI_FUNC(PyObject *)
3527
PyImport_ImportModuleNoBlock(const char *name)
3528
0
{
3529
0
    if (PyErr_WarnEx(PyExc_DeprecationWarning,
3530
0
        "PyImport_ImportModuleNoBlock() is deprecated and scheduled for "
3531
0
        "removal in Python 3.15. Use PyImport_ImportModule() instead.", 1))
3532
0
    {
3533
0
        return NULL;
3534
0
    }
3535
0
    return PyImport_ImportModule(name);
3536
0
}
3537
3538
3539
/* Remove importlib frames from the traceback,
3540
 * except in Verbose mode. */
3541
static void
3542
remove_importlib_frames(PyThreadState *tstate)
3543
12.3k
{
3544
12.3k
    const char *importlib_filename = "<frozen importlib._bootstrap>";
3545
12.3k
    const char *external_filename = "<frozen importlib._bootstrap_external>";
3546
12.3k
    const char *remove_frames = "_call_with_frames_removed";
3547
12.3k
    int always_trim = 0;
3548
12.3k
    int in_importlib = 0;
3549
12.3k
    PyObject **prev_link, **outer_link = NULL;
3550
12.3k
    PyObject *base_tb = NULL;
3551
3552
    /* Synopsis: if it's an ImportError, we trim all importlib chunks
3553
       from the traceback. We always trim chunks
3554
       which end with a call to "_call_with_frames_removed". */
3555
3556
12.3k
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3557
12.3k
    if (exc == NULL || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
3558
0
        goto done;
3559
0
    }
3560
3561
12.3k
    if (PyType_IsSubtype(Py_TYPE(exc), (PyTypeObject *) PyExc_ImportError)) {
3562
12.3k
        always_trim = 1;
3563
12.3k
    }
3564
3565
12.3k
    assert(PyExceptionInstance_Check(exc));
3566
12.3k
    base_tb = PyException_GetTraceback(exc);
3567
12.3k
    prev_link = &base_tb;
3568
12.3k
    PyObject *tb = base_tb;
3569
58.5k
    while (tb != NULL) {
3570
46.2k
        assert(PyTraceBack_Check(tb));
3571
46.2k
        PyTracebackObject *traceback = (PyTracebackObject *)tb;
3572
46.2k
        PyObject *next = (PyObject *) traceback->tb_next;
3573
46.2k
        PyFrameObject *frame = traceback->tb_frame;
3574
46.2k
        PyCodeObject *code = PyFrame_GetCode(frame);
3575
46.2k
        int now_in_importlib;
3576
3577
46.2k
        now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
3578
10.8k
                           _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
3579
46.2k
        if (now_in_importlib && !in_importlib) {
3580
            /* This is the link to this chunk of importlib tracebacks */
3581
12.3k
            outer_link = prev_link;
3582
12.3k
        }
3583
46.2k
        in_importlib = now_in_importlib;
3584
3585
46.2k
        if (in_importlib &&
3586
40.8k
            (always_trim ||
3587
40.8k
             _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
3588
40.8k
            Py_XSETREF(*outer_link, Py_XNewRef(next));
3589
40.8k
            prev_link = outer_link;
3590
40.8k
        }
3591
5.41k
        else {
3592
5.41k
            prev_link = (PyObject **) &traceback->tb_next;
3593
5.41k
        }
3594
46.2k
        Py_DECREF(code);
3595
46.2k
        tb = next;
3596
46.2k
    }
3597
12.3k
    if (base_tb == NULL) {
3598
6.90k
        base_tb = Py_None;
3599
6.90k
        Py_INCREF(Py_None);
3600
6.90k
    }
3601
12.3k
    PyException_SetTraceback(exc, base_tb);
3602
12.3k
done:
3603
12.3k
    Py_XDECREF(base_tb);
3604
12.3k
    _PyErr_SetRaisedException(tstate, exc);
3605
12.3k
}
3606
3607
3608
static PyObject *
3609
resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
3610
214
{
3611
214
    PyObject *abs_name;
3612
214
    PyObject *package = NULL;
3613
214
    PyObject *spec = NULL;
3614
214
    Py_ssize_t last_dot;
3615
214
    PyObject *base;
3616
214
    int level_up;
3617
3618
214
    if (globals == NULL) {
3619
0
        _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
3620
0
        goto error;
3621
0
    }
3622
214
    if (!PyDict_Check(globals)) {
3623
0
        _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
3624
0
        goto error;
3625
0
    }
3626
214
    if (PyDict_GetItemRef(globals, &_Py_ID(__package__), &package) < 0) {
3627
0
        goto error;
3628
0
    }
3629
214
    if (package == Py_None) {
3630
0
        Py_DECREF(package);
3631
0
        package = NULL;
3632
0
    }
3633
214
    if (PyDict_GetItemRef(globals, &_Py_ID(__spec__), &spec) < 0) {
3634
0
        goto error;
3635
0
    }
3636
3637
214
    if (package != NULL) {
3638
214
        if (!PyUnicode_Check(package)) {
3639
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3640
0
                             "package must be a string");
3641
0
            goto error;
3642
0
        }
3643
214
        else if (spec != NULL && spec != Py_None) {
3644
214
            int equal;
3645
214
            PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent));
3646
214
            if (parent == NULL) {
3647
0
                goto error;
3648
0
            }
3649
3650
214
            equal = PyObject_RichCompareBool(package, parent, Py_EQ);
3651
214
            Py_DECREF(parent);
3652
214
            if (equal < 0) {
3653
0
                goto error;
3654
0
            }
3655
214
            else if (equal == 0) {
3656
0
                if (PyErr_WarnEx(PyExc_DeprecationWarning,
3657
0
                        "__package__ != __spec__.parent", 1) < 0) {
3658
0
                    goto error;
3659
0
                }
3660
0
            }
3661
214
        }
3662
214
    }
3663
0
    else if (spec != NULL && spec != Py_None) {
3664
0
        package = PyObject_GetAttr(spec, &_Py_ID(parent));
3665
0
        if (package == NULL) {
3666
0
            goto error;
3667
0
        }
3668
0
        else if (!PyUnicode_Check(package)) {
3669
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3670
0
                             "__spec__.parent must be a string");
3671
0
            goto error;
3672
0
        }
3673
0
    }
3674
0
    else {
3675
0
        if (PyErr_WarnEx(PyExc_ImportWarning,
3676
0
                    "can't resolve package from __spec__ or __package__, "
3677
0
                    "falling back on __name__ and __path__", 1) < 0) {
3678
0
            goto error;
3679
0
        }
3680
3681
0
        if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &package) < 0) {
3682
0
            goto error;
3683
0
        }
3684
0
        if (package == NULL) {
3685
0
            _PyErr_SetString(tstate, PyExc_KeyError,
3686
0
                             "'__name__' not in globals");
3687
0
            goto error;
3688
0
        }
3689
3690
0
        if (!PyUnicode_Check(package)) {
3691
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3692
0
                             "__name__ must be a string");
3693
0
            goto error;
3694
0
        }
3695
3696
0
        int haspath = PyDict_Contains(globals, &_Py_ID(__path__));
3697
0
        if (haspath < 0) {
3698
0
            goto error;
3699
0
        }
3700
0
        if (!haspath) {
3701
0
            Py_ssize_t dot;
3702
3703
0
            dot = PyUnicode_FindChar(package, '.',
3704
0
                                        0, PyUnicode_GET_LENGTH(package), -1);
3705
0
            if (dot == -2) {
3706
0
                goto error;
3707
0
            }
3708
0
            else if (dot == -1) {
3709
0
                goto no_parent_error;
3710
0
            }
3711
0
            PyObject *substr = PyUnicode_Substring(package, 0, dot);
3712
0
            if (substr == NULL) {
3713
0
                goto error;
3714
0
            }
3715
0
            Py_SETREF(package, substr);
3716
0
        }
3717
0
    }
3718
3719
214
    last_dot = PyUnicode_GET_LENGTH(package);
3720
214
    if (last_dot == 0) {
3721
0
        goto no_parent_error;
3722
0
    }
3723
3724
214
    for (level_up = 1; level_up < level; level_up += 1) {
3725
0
        last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
3726
0
        if (last_dot == -2) {
3727
0
            goto error;
3728
0
        }
3729
0
        else if (last_dot == -1) {
3730
0
            _PyErr_SetString(tstate, PyExc_ImportError,
3731
0
                             "attempted relative import beyond top-level "
3732
0
                             "package");
3733
0
            goto error;
3734
0
        }
3735
0
    }
3736
3737
214
    Py_XDECREF(spec);
3738
214
    base = PyUnicode_Substring(package, 0, last_dot);
3739
214
    Py_DECREF(package);
3740
214
    if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
3741
78
        return base;
3742
78
    }
3743
3744
136
    abs_name = PyUnicode_FromFormat("%U.%U", base, name);
3745
136
    Py_DECREF(base);
3746
136
    return abs_name;
3747
3748
0
  no_parent_error:
3749
0
    _PyErr_SetString(tstate, PyExc_ImportError,
3750
0
                     "attempted relative import "
3751
0
                     "with no known parent package");
3752
3753
0
  error:
3754
0
    Py_XDECREF(spec);
3755
0
    Py_XDECREF(package);
3756
0
    return NULL;
3757
0
}
3758
3759
static PyObject *
3760
import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
3761
14.3k
{
3762
14.3k
    PyObject *mod = NULL;
3763
14.3k
    PyInterpreterState *interp = tstate->interp;
3764
14.3k
    int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
3765
14.3k
#define import_level FIND_AND_LOAD(interp).import_level
3766
14.3k
#define accumulated FIND_AND_LOAD(interp).accumulated
3767
3768
14.3k
    PyTime_t t1 = 0, accumulated_copy = accumulated;
3769
3770
    /* XOptions is initialized after first some imports.
3771
     * So we can't have negative cache before completed initialization.
3772
     * Anyway, importlib._find_and_load is much slower than
3773
     * _PyDict_GetItemIdWithError().
3774
     */
3775
14.3k
    if (import_time) {
3776
0
        _IMPORT_TIME_HEADER(interp);
3777
3778
0
        import_level++;
3779
        // ignore error: don't block import if reading the clock fails
3780
0
        (void)PyTime_PerfCounterRaw(&t1);
3781
0
        accumulated = 0;
3782
0
    }
3783
3784
14.3k
    if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
3785
0
        PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
3786
3787
14.3k
    mod = PyObject_CallMethodObjArgs(IMPORTLIB(interp), &_Py_ID(_find_and_load),
3788
14.3k
                                     abs_name, IMPORT_FUNC(interp), NULL);
3789
3790
14.3k
    if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
3791
0
        PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
3792
0
                                       mod != NULL);
3793
3794
14.3k
    if (import_time) {
3795
0
        PyTime_t t2;
3796
0
        (void)PyTime_PerfCounterRaw(&t2);
3797
0
        PyTime_t cum = t2 - t1;
3798
3799
0
        import_level--;
3800
0
        fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
3801
0
                (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
3802
0
                (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
3803
0
                import_level*2, "", PyUnicode_AsUTF8(abs_name));
3804
3805
0
        accumulated = accumulated_copy + cum;
3806
0
    }
3807
3808
14.3k
    return mod;
3809
14.3k
#undef import_level
3810
14.3k
#undef accumulated
3811
14.3k
}
3812
3813
PyObject *
3814
PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
3815
                                 PyObject *locals, PyObject *fromlist,
3816
                                 int level)
3817
1.79M
{
3818
1.79M
    PyThreadState *tstate = _PyThreadState_GET();
3819
1.79M
    PyObject *abs_name = NULL;
3820
1.79M
    PyObject *final_mod = NULL;
3821
1.79M
    PyObject *mod = NULL;
3822
1.79M
    PyObject *package = NULL;
3823
1.79M
    PyInterpreterState *interp = tstate->interp;
3824
1.79M
    int has_from;
3825
3826
1.79M
    if (name == NULL) {
3827
0
        _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
3828
0
        goto error;
3829
0
    }
3830
3831
    /* The below code is importlib.__import__() & _gcd_import(), ported to C
3832
       for added performance. */
3833
3834
1.79M
    if (!PyUnicode_Check(name)) {
3835
0
        _PyErr_SetString(tstate, PyExc_TypeError,
3836
0
                         "module name must be a string");
3837
0
        goto error;
3838
0
    }
3839
1.79M
    if (level < 0) {
3840
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
3841
0
        goto error;
3842
0
    }
3843
3844
1.79M
    if (level > 0) {
3845
214
        abs_name = resolve_name(tstate, name, globals, level);
3846
214
        if (abs_name == NULL)
3847
0
            goto error;
3848
214
    }
3849
1.79M
    else {  /* level == 0 */
3850
1.79M
        if (PyUnicode_GET_LENGTH(name) == 0) {
3851
0
            _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
3852
0
            goto error;
3853
0
        }
3854
1.79M
        abs_name = Py_NewRef(name);
3855
1.79M
    }
3856
3857
1.79M
    mod = import_get_module(tstate, abs_name);
3858
1.79M
    if (mod == NULL && _PyErr_Occurred(tstate)) {
3859
0
        goto error;
3860
0
    }
3861
3862
1.79M
    if (mod != NULL && mod != Py_None) {
3863
1.78M
        if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
3864
0
            goto error;
3865
0
        }
3866
1.78M
    }
3867
14.3k
    else {
3868
14.3k
        Py_XDECREF(mod);
3869
14.3k
        mod = import_find_and_load(tstate, abs_name);
3870
14.3k
        if (mod == NULL) {
3871
12.3k
            goto error;
3872
12.3k
        }
3873
14.3k
    }
3874
3875
1.78M
    has_from = 0;
3876
1.78M
    if (fromlist != NULL && fromlist != Py_None) {
3877
189k
        has_from = PyObject_IsTrue(fromlist);
3878
189k
        if (has_from < 0)
3879
0
            goto error;
3880
189k
    }
3881
1.78M
    if (!has_from) {
3882
1.76M
        Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3883
1.76M
        if (level == 0 || len > 0) {
3884
1.76M
            Py_ssize_t dot;
3885
3886
1.76M
            dot = PyUnicode_FindChar(name, '.', 0, len, 1);
3887
1.76M
            if (dot == -2) {
3888
0
                goto error;
3889
0
            }
3890
3891
1.76M
            if (dot == -1) {
3892
                /* No dot in module name, simple exit */
3893
1.76M
                final_mod = Py_NewRef(mod);
3894
1.76M
                goto error;
3895
1.76M
            }
3896
3897
2.44k
            if (level == 0) {
3898
2.44k
                PyObject *front = PyUnicode_Substring(name, 0, dot);
3899
2.44k
                if (front == NULL) {
3900
0
                    goto error;
3901
0
                }
3902
3903
2.44k
                final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
3904
2.44k
                Py_DECREF(front);
3905
2.44k
            }
3906
0
            else {
3907
0
                Py_ssize_t cut_off = len - dot;
3908
0
                Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
3909
0
                PyObject *to_return = PyUnicode_Substring(abs_name, 0,
3910
0
                                                        abs_name_len - cut_off);
3911
0
                if (to_return == NULL) {
3912
0
                    goto error;
3913
0
                }
3914
3915
0
                final_mod = import_get_module(tstate, to_return);
3916
0
                if (final_mod == NULL) {
3917
0
                    if (!_PyErr_Occurred(tstate)) {
3918
0
                        _PyErr_Format(tstate, PyExc_KeyError,
3919
0
                                      "%R not in sys.modules as expected",
3920
0
                                      to_return);
3921
0
                    }
3922
0
                    Py_DECREF(to_return);
3923
0
                    goto error;
3924
0
                }
3925
3926
0
                Py_DECREF(to_return);
3927
0
            }
3928
2.44k
        }
3929
0
        else {
3930
0
            final_mod = Py_NewRef(mod);
3931
0
        }
3932
1.76M
    }
3933
17.0k
    else {
3934
17.0k
        int has_path = PyObject_HasAttrWithError(mod, &_Py_ID(__path__));
3935
17.0k
        if (has_path < 0) {
3936
0
            goto error;
3937
0
        }
3938
17.0k
        if (has_path) {
3939
2.93k
            final_mod = PyObject_CallMethodObjArgs(
3940
2.93k
                        IMPORTLIB(interp), &_Py_ID(_handle_fromlist),
3941
2.93k
                        mod, fromlist, IMPORT_FUNC(interp), NULL);
3942
2.93k
        }
3943
14.1k
        else {
3944
14.1k
            final_mod = Py_NewRef(mod);
3945
14.1k
        }
3946
17.0k
    }
3947
3948
1.79M
  error:
3949
1.79M
    Py_XDECREF(abs_name);
3950
1.79M
    Py_XDECREF(mod);
3951
1.79M
    Py_XDECREF(package);
3952
1.79M
    if (final_mod == NULL) {
3953
12.3k
        remove_importlib_frames(tstate);
3954
12.3k
    }
3955
1.79M
    return final_mod;
3956
1.78M
}
3957
3958
PyObject *
3959
PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
3960
                           PyObject *fromlist, int level)
3961
224
{
3962
224
    PyObject *nameobj, *mod;
3963
224
    nameobj = PyUnicode_FromString(name);
3964
224
    if (nameobj == NULL)
3965
0
        return NULL;
3966
224
    mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
3967
224
                                           fromlist, level);
3968
224
    Py_DECREF(nameobj);
3969
224
    return mod;
3970
224
}
3971
3972
3973
/* Re-import a module of any kind and return its module object, WITH
3974
   INCREMENTED REFERENCE COUNT */
3975
3976
PyObject *
3977
PyImport_ReloadModule(PyObject *m)
3978
0
{
3979
0
    PyObject *reloaded_module = NULL;
3980
0
    PyObject *importlib = PyImport_GetModule(&_Py_ID(importlib));
3981
0
    if (importlib == NULL) {
3982
0
        if (PyErr_Occurred()) {
3983
0
            return NULL;
3984
0
        }
3985
3986
0
        importlib = PyImport_ImportModule("importlib");
3987
0
        if (importlib == NULL) {
3988
0
            return NULL;
3989
0
        }
3990
0
    }
3991
3992
0
    reloaded_module = PyObject_CallMethodOneArg(importlib, &_Py_ID(reload), m);
3993
0
    Py_DECREF(importlib);
3994
0
    return reloaded_module;
3995
0
}
3996
3997
3998
/* Higher-level import emulator which emulates the "import" statement
3999
   more accurately -- it invokes the __import__() function from the
4000
   builtins of the current globals.  This means that the import is
4001
   done using whatever import hooks are installed in the current
4002
   environment.
4003
   A dummy list ["__doc__"] is passed as the 4th argument so that
4004
   e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
4005
   will return <module "gencache"> instead of <module "win32com">. */
4006
4007
PyObject *
4008
PyImport_Import(PyObject *module_name)
4009
172k
{
4010
172k
    PyThreadState *tstate = _PyThreadState_GET();
4011
172k
    PyObject *globals = NULL;
4012
172k
    PyObject *import = NULL;
4013
172k
    PyObject *builtins = NULL;
4014
172k
    PyObject *r = NULL;
4015
4016
172k
    PyObject *from_list = PyList_New(0);
4017
172k
    if (from_list == NULL) {
4018
0
        goto err;
4019
0
    }
4020
4021
    /* Get the builtins from current globals */
4022
172k
    globals = PyEval_GetGlobals();  // borrowed
4023
172k
    if (globals != NULL) {
4024
172k
        Py_INCREF(globals);
4025
        // XXX Use _PyEval_EnsureBuiltins()?
4026
172k
        builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
4027
172k
        if (builtins == NULL) {
4028
            // XXX Fall back to interp->builtins or sys.modules['builtins']?
4029
0
            goto err;
4030
0
        }
4031
172k
    }
4032
224
    else if (_PyErr_Occurred(tstate)) {
4033
0
        goto err;
4034
0
    }
4035
224
    else {
4036
        /* No globals -- use standard builtins, and fake globals */
4037
224
        globals = PyDict_New();
4038
224
        if (globals == NULL) {
4039
0
            goto err;
4040
0
        }
4041
224
        if (_PyEval_EnsureBuiltinsWithModule(tstate, globals, &builtins) < 0) {
4042
0
            goto err;
4043
0
        }
4044
224
    }
4045
4046
    /* Get the __import__ function from the builtins */
4047
172k
    if (PyDict_Check(builtins)) {
4048
172k
        import = PyObject_GetItem(builtins, &_Py_ID(__import__));
4049
172k
        if (import == NULL) {
4050
0
            _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
4051
0
        }
4052
172k
    }
4053
224
    else
4054
224
        import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
4055
172k
    if (import == NULL)
4056
0
        goto err;
4057
4058
    /* Call the __import__ function with the proper argument list
4059
       Always use absolute import here.
4060
       Calling for side-effect of import. */
4061
172k
    r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
4062
172k
                              globals, from_list, 0, NULL);
4063
172k
    if (r == NULL)
4064
0
        goto err;
4065
172k
    Py_DECREF(r);
4066
4067
172k
    r = import_get_module(tstate, module_name);
4068
172k
    if (r == NULL && !_PyErr_Occurred(tstate)) {
4069
0
        _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
4070
0
    }
4071
4072
172k
  err:
4073
172k
    Py_XDECREF(globals);
4074
172k
    Py_XDECREF(builtins);
4075
172k
    Py_XDECREF(import);
4076
172k
    Py_XDECREF(from_list);
4077
4078
172k
    return r;
4079
172k
}
4080
4081
4082
/*********************/
4083
/* runtime lifecycle */
4084
/*********************/
4085
4086
PyStatus
4087
_PyImport_Init(void)
4088
28
{
4089
28
    if (INITTAB != NULL) {
4090
0
        return _PyStatus_ERR("global import state already initialized");
4091
0
    }
4092
28
    if (init_builtin_modules_table() != 0) {
4093
0
        return PyStatus_NoMemory();
4094
0
    }
4095
28
    return _PyStatus_OK();
4096
28
}
4097
4098
void
4099
_PyImport_Fini(void)
4100
0
{
4101
    /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
4102
    // XXX Should we actually leave them (mostly) intact, since we don't
4103
    // ever dlclose() the module files?
4104
0
    _extensions_cache_clear_all();
4105
4106
    /* Free memory allocated by _PyImport_Init() */
4107
0
    fini_builtin_modules_table();
4108
0
}
4109
4110
void
4111
_PyImport_Fini2(void)
4112
0
{
4113
    // Reset PyImport_Inittab
4114
0
    PyImport_Inittab = _PyImport_Inittab;
4115
4116
    /* Free memory allocated by PyImport_ExtendInittab() */
4117
0
    _PyMem_DefaultRawFree(inittab_copy);
4118
0
    inittab_copy = NULL;
4119
0
}
4120
4121
4122
/*************************/
4123
/* interpreter lifecycle */
4124
/*************************/
4125
4126
PyStatus
4127
_PyImport_InitCore(PyThreadState *tstate, PyObject *sysmod, int importlib)
4128
28
{
4129
    // XXX Initialize here: interp->modules and interp->import_func.
4130
    // XXX Initialize here: sys.modules and sys.meta_path.
4131
4132
28
    if (importlib) {
4133
        /* This call sets up builtin and frozen import support */
4134
28
        if (init_importlib(tstate, sysmod) < 0) {
4135
0
            return _PyStatus_ERR("failed to initialize importlib");
4136
0
        }
4137
28
    }
4138
4139
28
    return _PyStatus_OK();
4140
28
}
4141
4142
/* In some corner cases it is important to be sure that the import
4143
   machinery has been initialized (or not cleaned up yet).  For
4144
   example, see issue #4236 and PyModule_Create2(). */
4145
4146
int
4147
_PyImport_IsInitialized(PyInterpreterState *interp)
4148
0
{
4149
0
    if (MODULES(interp) == NULL)
4150
0
        return 0;
4151
0
    return 1;
4152
0
}
4153
4154
/* Clear the direct per-interpreter import state, if not cleared already. */
4155
void
4156
_PyImport_ClearCore(PyInterpreterState *interp)
4157
0
{
4158
    /* interp->modules should have been cleaned up and cleared already
4159
       by _PyImport_FiniCore(). */
4160
0
    Py_CLEAR(MODULES(interp));
4161
0
    Py_CLEAR(MODULES_BY_INDEX(interp));
4162
0
    Py_CLEAR(IMPORTLIB(interp));
4163
0
    Py_CLEAR(IMPORT_FUNC(interp));
4164
0
}
4165
4166
void
4167
_PyImport_FiniCore(PyInterpreterState *interp)
4168
0
{
4169
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4170
4171
0
    if (_PySys_ClearAttrString(interp, "meta_path", verbose) < 0) {
4172
0
        PyErr_FormatUnraisable("Exception ignored while "
4173
0
                               "clearing sys.meta_path");
4174
0
    }
4175
4176
    // XXX Pull in most of finalize_modules() in pylifecycle.c.
4177
4178
0
    if (_PySys_ClearAttrString(interp, "modules", verbose) < 0) {
4179
0
        PyErr_FormatUnraisable("Exception ignored while "
4180
0
                               "clearing sys.modules");
4181
0
    }
4182
4183
0
    _PyImport_ClearCore(interp);
4184
0
}
4185
4186
// XXX Add something like _PyImport_Disable() for use early in interp fini?
4187
4188
4189
/* "external" imports */
4190
4191
static int
4192
init_zipimport(PyThreadState *tstate, int verbose)
4193
28
{
4194
28
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
4195
28
    if (path_hooks == NULL) {
4196
0
        return -1;
4197
0
    }
4198
4199
28
    if (verbose) {
4200
0
        PySys_WriteStderr("# installing zipimport hook\n");
4201
0
    }
4202
4203
28
    PyObject *zipimporter = PyImport_ImportModuleAttrString("zipimport", "zipimporter");
4204
28
    if (zipimporter == NULL) {
4205
0
        _PyErr_Clear(tstate); /* No zipimporter object -- okay */
4206
0
        if (verbose) {
4207
0
            PySys_WriteStderr("# can't import zipimport.zipimporter\n");
4208
0
        }
4209
0
    }
4210
28
    else {
4211
        /* sys.path_hooks.insert(0, zipimporter) */
4212
28
        int err = PyList_Insert(path_hooks, 0, zipimporter);
4213
28
        Py_DECREF(zipimporter);
4214
28
        if (err < 0) {
4215
0
            Py_DECREF(path_hooks);
4216
0
            return -1;
4217
0
        }
4218
28
        if (verbose) {
4219
0
            PySys_WriteStderr("# installed zipimport hook\n");
4220
0
        }
4221
28
    }
4222
28
    Py_DECREF(path_hooks);
4223
4224
28
    return 0;
4225
28
}
4226
4227
PyStatus
4228
_PyImport_InitExternal(PyThreadState *tstate)
4229
28
{
4230
28
    int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
4231
4232
    // XXX Initialize here: sys.path_hooks and sys.path_importer_cache.
4233
4234
28
    if (init_importlib_external(tstate->interp) != 0) {
4235
0
        _PyErr_Print(tstate);
4236
0
        return _PyStatus_ERR("external importer setup failed");
4237
0
    }
4238
4239
28
    if (init_zipimport(tstate, verbose) != 0) {
4240
0
        PyErr_Print();
4241
0
        return _PyStatus_ERR("initializing zipimport failed");
4242
0
    }
4243
4244
28
    return _PyStatus_OK();
4245
28
}
4246
4247
void
4248
_PyImport_FiniExternal(PyInterpreterState *interp)
4249
0
{
4250
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4251
4252
    // XXX Uninstall importlib metapath importers here?
4253
4254
0
    if (_PySys_ClearAttrString(interp, "path_importer_cache", verbose) < 0) {
4255
0
        PyErr_FormatUnraisable("Exception ignored while "
4256
0
                               "clearing sys.path_importer_cache");
4257
0
    }
4258
0
    if (_PySys_ClearAttrString(interp, "path_hooks", verbose) < 0) {
4259
0
        PyErr_FormatUnraisable("Exception ignored while "
4260
0
                               "clearing sys.path_hooks");
4261
0
    }
4262
0
}
4263
4264
4265
/******************/
4266
/* module helpers */
4267
/******************/
4268
4269
PyObject *
4270
PyImport_ImportModuleAttr(PyObject *modname, PyObject *attrname)
4271
10.5k
{
4272
10.5k
    PyObject *mod = PyImport_Import(modname);
4273
10.5k
    if (mod == NULL) {
4274
0
        return NULL;
4275
0
    }
4276
10.5k
    PyObject *result = PyObject_GetAttr(mod, attrname);
4277
10.5k
    Py_DECREF(mod);
4278
10.5k
    return result;
4279
10.5k
}
4280
4281
PyObject *
4282
PyImport_ImportModuleAttrString(const char *modname, const char *attrname)
4283
8.30k
{
4284
8.30k
    PyObject *pmodname = PyUnicode_FromString(modname);
4285
8.30k
    if (pmodname == NULL) {
4286
0
        return NULL;
4287
0
    }
4288
8.30k
    PyObject *pattrname = PyUnicode_FromString(attrname);
4289
8.30k
    if (pattrname == NULL) {
4290
0
        Py_DECREF(pmodname);
4291
0
        return NULL;
4292
0
    }
4293
8.30k
    PyObject *result = PyImport_ImportModuleAttr(pmodname, pattrname);
4294
8.30k
    Py_DECREF(pattrname);
4295
8.30k
    Py_DECREF(pmodname);
4296
8.30k
    return result;
4297
8.30k
}
4298
4299
4300
/**************/
4301
/* the module */
4302
/**************/
4303
4304
/*[clinic input]
4305
_imp.lock_held
4306
4307
Return True if the import lock is currently held, else False.
4308
4309
On platforms without threads, return False.
4310
[clinic start generated code]*/
4311
4312
static PyObject *
4313
_imp_lock_held_impl(PyObject *module)
4314
/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
4315
0
{
4316
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4317
0
    return PyBool_FromLong(PyMutex_IsLocked(&IMPORT_LOCK(interp).mutex));
4318
0
}
4319
4320
/*[clinic input]
4321
@permit_long_docstring_body
4322
_imp.acquire_lock
4323
4324
Acquires the interpreter's import lock for the current thread.
4325
4326
This lock should be used by import hooks to ensure thread-safety when importing
4327
modules. On platforms without threads, this function does nothing.
4328
[clinic start generated code]*/
4329
4330
static PyObject *
4331
_imp_acquire_lock_impl(PyObject *module)
4332
/*[clinic end generated code: output=1aff58cb0ee1b026 input=e1a4ef049d34e7dd]*/
4333
70.7k
{
4334
70.7k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4335
70.7k
    _PyImport_AcquireLock(interp);
4336
70.7k
    Py_RETURN_NONE;
4337
70.7k
}
4338
4339
/*[clinic input]
4340
_imp.release_lock
4341
4342
Release the interpreter's import lock.
4343
4344
On platforms without threads, this function does nothing.
4345
[clinic start generated code]*/
4346
4347
static PyObject *
4348
_imp_release_lock_impl(PyObject *module)
4349
/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
4350
70.7k
{
4351
70.7k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4352
70.7k
    if (!_PyRecursiveMutex_IsLockedByCurrentThread(&IMPORT_LOCK(interp))) {
4353
0
        PyErr_SetString(PyExc_RuntimeError,
4354
0
                        "not holding the import lock");
4355
0
        return NULL;
4356
0
    }
4357
70.7k
    _PyImport_ReleaseLock(interp);
4358
70.7k
    Py_RETURN_NONE;
4359
70.7k
}
4360
4361
4362
/*[clinic input]
4363
_imp._fix_co_filename
4364
4365
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
4366
        Code object to change.
4367
4368
    path: unicode
4369
        File path to use.
4370
    /
4371
4372
Changes code.co_filename to specify the passed-in file path.
4373
[clinic start generated code]*/
4374
4375
static PyObject *
4376
_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
4377
                           PyObject *path)
4378
/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
4379
4380
6.22k
{
4381
6.22k
    update_compiled_module(code, path);
4382
4383
6.22k
    Py_RETURN_NONE;
4384
6.22k
}
4385
4386
4387
/*[clinic input]
4388
_imp.create_builtin
4389
4390
    spec: object
4391
    /
4392
4393
Create an extension module.
4394
[clinic start generated code]*/
4395
4396
static PyObject *
4397
_imp_create_builtin(PyObject *module, PyObject *spec)
4398
/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
4399
531
{
4400
531
    PyThreadState *tstate = _PyThreadState_GET();
4401
4402
531
    PyObject *name = PyObject_GetAttrString(spec, "name");
4403
531
    if (name == NULL) {
4404
0
        return NULL;
4405
0
    }
4406
4407
531
    if (!PyUnicode_Check(name)) {
4408
0
        PyErr_Format(PyExc_TypeError,
4409
0
                     "name must be string, not %.200s",
4410
0
                     Py_TYPE(name)->tp_name);
4411
0
        Py_DECREF(name);
4412
0
        return NULL;
4413
0
    }
4414
4415
531
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
4416
531
    Py_DECREF(name);
4417
531
    return mod;
4418
531
}
4419
4420
4421
/*[clinic input]
4422
_imp.extension_suffixes
4423
4424
Returns the list of file suffixes used to identify extension modules.
4425
[clinic start generated code]*/
4426
4427
static PyObject *
4428
_imp_extension_suffixes_impl(PyObject *module)
4429
/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
4430
56
{
4431
56
    PyObject *list;
4432
4433
56
    list = PyList_New(0);
4434
56
    if (list == NULL)
4435
0
        return NULL;
4436
56
#ifdef HAVE_DYNAMIC_LOADING
4437
56
    const char *suffix;
4438
56
    unsigned int index = 0;
4439
4440
224
    while ((suffix = _PyImport_DynLoadFiletab[index])) {
4441
168
        PyObject *item = PyUnicode_FromString(suffix);
4442
168
        if (item == NULL) {
4443
0
            Py_DECREF(list);
4444
0
            return NULL;
4445
0
        }
4446
168
        if (PyList_Append(list, item) < 0) {
4447
0
            Py_DECREF(list);
4448
0
            Py_DECREF(item);
4449
0
            return NULL;
4450
0
        }
4451
168
        Py_DECREF(item);
4452
168
        index += 1;
4453
168
    }
4454
56
#endif
4455
56
    return list;
4456
56
}
4457
4458
/*[clinic input]
4459
_imp.init_frozen
4460
4461
    name: unicode
4462
    /
4463
4464
Initializes a frozen module.
4465
[clinic start generated code]*/
4466
4467
static PyObject *
4468
_imp_init_frozen_impl(PyObject *module, PyObject *name)
4469
/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
4470
0
{
4471
0
    PyThreadState *tstate = _PyThreadState_GET();
4472
0
    int ret;
4473
4474
0
    ret = PyImport_ImportFrozenModuleObject(name);
4475
0
    if (ret < 0)
4476
0
        return NULL;
4477
0
    if (ret == 0) {
4478
0
        Py_RETURN_NONE;
4479
0
    }
4480
0
    return import_add_module(tstate, name);
4481
0
}
4482
4483
/*[clinic input]
4484
_imp.find_frozen
4485
4486
    name: unicode
4487
    /
4488
    *
4489
    withdata: bool = False
4490
4491
Return info about the corresponding frozen module (if there is one) or None.
4492
4493
The returned info (a 2-tuple):
4494
4495
 * data         the raw marshalled bytes
4496
 * is_package   whether or not it is a package
4497
 * origname     the originally frozen module's name, or None if not
4498
                a stdlib module (this will usually be the same as
4499
                the module's current name)
4500
[clinic start generated code]*/
4501
4502
static PyObject *
4503
_imp_find_frozen_impl(PyObject *module, PyObject *name, int withdata)
4504
/*[clinic end generated code: output=8c1c3c7f925397a5 input=22a8847c201542fd]*/
4505
13.8k
{
4506
13.8k
    struct frozen_info info;
4507
13.8k
    frozen_status status = find_frozen(name, &info);
4508
13.8k
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
4509
13.5k
        Py_RETURN_NONE;
4510
13.5k
    }
4511
337
    else if (status == FROZEN_BAD_NAME) {
4512
0
        Py_RETURN_NONE;
4513
0
    }
4514
337
    else if (status != FROZEN_OKAY) {
4515
0
        set_frozen_error(status, name);
4516
0
        return NULL;
4517
0
    }
4518
4519
337
    PyObject *data = NULL;
4520
337
    if (withdata) {
4521
0
        data = PyMemoryView_FromMemory((char *)info.data, info.size, PyBUF_READ);
4522
0
        if (data == NULL) {
4523
0
            return NULL;
4524
0
        }
4525
0
    }
4526
4527
337
    PyObject *origname = NULL;
4528
337
    if (info.origname != NULL && info.origname[0] != '\0') {
4529
337
        origname = PyUnicode_FromString(info.origname);
4530
337
        if (origname == NULL) {
4531
0
            Py_XDECREF(data);
4532
0
            return NULL;
4533
0
        }
4534
337
    }
4535
4536
337
    PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
4537
337
                                    info.is_package ? Py_True : Py_False,
4538
337
                                    origname ? origname : Py_None);
4539
337
    Py_XDECREF(origname);
4540
337
    Py_XDECREF(data);
4541
337
    return result;
4542
337
}
4543
4544
/*[clinic input]
4545
_imp.get_frozen_object
4546
4547
    name: unicode
4548
    data as dataobj: object = None
4549
    /
4550
4551
Create a code object for a frozen module.
4552
[clinic start generated code]*/
4553
4554
static PyObject *
4555
_imp_get_frozen_object_impl(PyObject *module, PyObject *name,
4556
                            PyObject *dataobj)
4557
/*[clinic end generated code: output=54368a673a35e745 input=034bdb88f6460b7b]*/
4558
337
{
4559
337
    struct frozen_info info = {0};
4560
337
    Py_buffer buf = {0};
4561
337
    if (PyObject_CheckBuffer(dataobj)) {
4562
0
        if (PyObject_GetBuffer(dataobj, &buf, PyBUF_SIMPLE) != 0) {
4563
0
            return NULL;
4564
0
        }
4565
0
        info.data = (const char *)buf.buf;
4566
0
        info.size = buf.len;
4567
0
    }
4568
337
    else if (dataobj != Py_None) {
4569
0
        _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
4570
0
        return NULL;
4571
0
    }
4572
337
    else {
4573
337
        frozen_status status = find_frozen(name, &info);
4574
337
        if (status != FROZEN_OKAY) {
4575
0
            set_frozen_error(status, name);
4576
0
            return NULL;
4577
0
        }
4578
337
    }
4579
4580
337
    if (info.nameobj == NULL) {
4581
0
        info.nameobj = name;
4582
0
    }
4583
337
    if (info.size == 0) {
4584
        /* Does not contain executable code. */
4585
0
        set_frozen_error(FROZEN_INVALID, name);
4586
0
        return NULL;
4587
0
    }
4588
4589
337
    PyInterpreterState *interp = _PyInterpreterState_GET();
4590
337
    PyObject *codeobj = unmarshal_frozen_code(interp, &info);
4591
337
    if (dataobj != Py_None) {
4592
0
        PyBuffer_Release(&buf);
4593
0
    }
4594
337
    return codeobj;
4595
337
}
4596
4597
/*[clinic input]
4598
_imp.is_frozen_package
4599
4600
    name: unicode
4601
    /
4602
4603
Returns True if the module name is of a frozen package.
4604
[clinic start generated code]*/
4605
4606
static PyObject *
4607
_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
4608
/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
4609
28
{
4610
28
    struct frozen_info info;
4611
28
    frozen_status status = find_frozen(name, &info);
4612
28
    if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
4613
0
        set_frozen_error(status, name);
4614
0
        return NULL;
4615
0
    }
4616
28
    return PyBool_FromLong(info.is_package);
4617
28
}
4618
4619
/*[clinic input]
4620
_imp.is_builtin
4621
4622
    name: unicode
4623
    /
4624
4625
Returns True if the module name corresponds to a built-in module.
4626
[clinic start generated code]*/
4627
4628
static PyObject *
4629
_imp_is_builtin_impl(PyObject *module, PyObject *name)
4630
/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
4631
14.3k
{
4632
14.3k
    return PyLong_FromLong(is_builtin(name));
4633
14.3k
}
4634
4635
/*[clinic input]
4636
_imp.is_frozen
4637
4638
    name: unicode
4639
    /
4640
4641
Returns True if the module name corresponds to a frozen module.
4642
[clinic start generated code]*/
4643
4644
static PyObject *
4645
_imp_is_frozen_impl(PyObject *module, PyObject *name)
4646
/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
4647
28
{
4648
28
    struct frozen_info info;
4649
28
    frozen_status status = find_frozen(name, &info);
4650
28
    if (status != FROZEN_OKAY) {
4651
0
        Py_RETURN_FALSE;
4652
0
    }
4653
28
    Py_RETURN_TRUE;
4654
28
}
4655
4656
/*[clinic input]
4657
_imp._frozen_module_names
4658
4659
Returns the list of available frozen modules.
4660
[clinic start generated code]*/
4661
4662
static PyObject *
4663
_imp__frozen_module_names_impl(PyObject *module)
4664
/*[clinic end generated code: output=80609ef6256310a8 input=76237fbfa94460d2]*/
4665
0
{
4666
0
    return list_frozen_module_names();
4667
0
}
4668
4669
/*[clinic input]
4670
_imp._override_frozen_modules_for_tests
4671
4672
    override: int
4673
    /
4674
4675
(internal-only) Override PyConfig.use_frozen_modules.
4676
4677
(-1: "off", 1: "on", 0: no override)
4678
See frozen_modules() in Lib/test/support/import_helper.py.
4679
[clinic start generated code]*/
4680
4681
static PyObject *
4682
_imp__override_frozen_modules_for_tests_impl(PyObject *module, int override)
4683
/*[clinic end generated code: output=36d5cb1594160811 input=8f1f95a3ef21aec3]*/
4684
0
{
4685
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4686
0
    OVERRIDE_FROZEN_MODULES(interp) = override;
4687
0
    Py_RETURN_NONE;
4688
0
}
4689
4690
/*[clinic input]
4691
_imp._override_multi_interp_extensions_check
4692
4693
    override: int
4694
    /
4695
4696
(internal-only) Override PyInterpreterConfig.check_multi_interp_extensions.
4697
4698
(-1: "never", 1: "always", 0: no override)
4699
[clinic start generated code]*/
4700
4701
static PyObject *
4702
_imp__override_multi_interp_extensions_check_impl(PyObject *module,
4703
                                                  int override)
4704
/*[clinic end generated code: output=3ff043af52bbf280 input=e086a2ea181f92ae]*/
4705
0
{
4706
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4707
0
    if (_Py_IsMainInterpreter(interp)) {
4708
0
        PyErr_SetString(PyExc_RuntimeError,
4709
0
                        "_imp._override_multi_interp_extensions_check() "
4710
0
                        "cannot be used in the main interpreter");
4711
0
        return NULL;
4712
0
    }
4713
#ifdef Py_GIL_DISABLED
4714
    PyErr_SetString(PyExc_RuntimeError,
4715
                    "_imp._override_multi_interp_extensions_check() "
4716
                    "cannot be used in the free-threaded build");
4717
    return NULL;
4718
#else
4719
0
    int oldvalue = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
4720
0
    OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) = override;
4721
0
    return PyLong_FromLong(oldvalue);
4722
0
#endif
4723
0
}
4724
4725
#ifdef HAVE_DYNAMIC_LOADING
4726
4727
/*[clinic input]
4728
_imp.create_dynamic
4729
4730
    spec: object
4731
    file: object = NULL
4732
    /
4733
4734
Create an extension module.
4735
[clinic start generated code]*/
4736
4737
static PyObject *
4738
_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
4739
/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
4740
124
{
4741
124
    PyObject *mod = NULL;
4742
124
    PyThreadState *tstate = _PyThreadState_GET();
4743
4744
124
    struct _Py_ext_module_loader_info info;
4745
124
    if (_Py_ext_module_loader_info_init_from_spec(&info, spec) < 0) {
4746
0
        return NULL;
4747
0
    }
4748
4749
124
    struct extensions_cache_value *cached = NULL;
4750
124
    mod = import_find_extension(tstate, &info, &cached);
4751
124
    if (mod != NULL) {
4752
0
        assert(!_PyErr_Occurred(tstate));
4753
0
        assert(cached != NULL);
4754
        /* The module might not have md_def set in certain reload cases. */
4755
0
        assert(_PyModule_GetDefOrNull(mod) == NULL
4756
0
                || cached->def == _PyModule_GetDefOrNull(mod));
4757
0
        assert_singlephase(cached);
4758
0
        goto finally;
4759
0
    }
4760
124
    else if (_PyErr_Occurred(tstate)) {
4761
0
        goto finally;
4762
0
    }
4763
    /* Otherwise it must be multi-phase init or the first time it's loaded. */
4764
4765
    /* If the module was added to the global cache
4766
     * but def->m_base.m_copy was cleared (e.g. subinterp fini)
4767
     * then we have to do a little dance here. */
4768
124
    if (cached != NULL) {
4769
0
        assert(cached->def->m_base.m_copy == NULL);
4770
        /* For now we clear the cache and move on. */
4771
0
        _extensions_cache_delete(info.path, info.name);
4772
0
    }
4773
4774
124
    if (PySys_Audit("import", "OOOOO", info.name, info.filename,
4775
124
                    Py_None, Py_None, Py_None) < 0)
4776
0
    {
4777
0
        goto finally;
4778
0
    }
4779
4780
    /* We would move this (and the fclose() below) into
4781
     * _PyImport_GetModuleExportHooks(), but it isn't clear if the intervening
4782
     * code relies on fp still being open. */
4783
124
    FILE *fp;
4784
124
    if (file != NULL) {
4785
0
        fp = Py_fopen(info.filename, "r");
4786
0
        if (fp == NULL) {
4787
0
            goto finally;
4788
0
        }
4789
0
    }
4790
124
    else {
4791
124
        fp = NULL;
4792
124
    }
4793
4794
124
    PyModInitFunction p0 = NULL;
4795
124
    PyModExportFunction ex0 = NULL;
4796
124
    _PyImport_GetModuleExportHooks(&info, fp, &p0, &ex0);
4797
124
    if (ex0) {
4798
0
        mod = import_run_modexport(tstate, ex0, &info, spec);
4799
0
        goto cleanup;
4800
0
    }
4801
124
    if (p0 == NULL) {
4802
0
        goto finally;
4803
0
    }
4804
4805
#ifdef Py_GIL_DISABLED
4806
    // This call (and the corresponding call to _PyImport_CheckGILForModule())
4807
    // would ideally be inside import_run_extension(). They are kept in the
4808
    // callers for now because that would complicate the control flow inside
4809
    // import_run_extension(). It should be possible to restructure
4810
    // import_run_extension() to address this.
4811
    _PyEval_EnableGILTransient(tstate);
4812
#endif
4813
124
    mod = import_run_extension(
4814
124
                    tstate, p0, &info, spec, get_modules_dict(tstate, true));
4815
#ifdef Py_GIL_DISABLED
4816
    if (_PyImport_CheckGILForModule(mod, info.name) < 0) {
4817
        Py_CLEAR(mod);
4818
        goto finally;
4819
    }
4820
#endif
4821
4822
124
cleanup:
4823
    // XXX Shouldn't this happen in the error cases too (i.e. in "finally")?
4824
124
    if (fp) {
4825
0
        fclose(fp);
4826
0
    }
4827
4828
124
finally:
4829
124
    _Py_ext_module_loader_info_clear(&info);
4830
124
    return mod;
4831
124
}
4832
4833
/*[clinic input]
4834
_imp.exec_dynamic -> int
4835
4836
    mod: object
4837
    /
4838
4839
Initialize an extension module.
4840
[clinic start generated code]*/
4841
4842
static int
4843
_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
4844
/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
4845
124
{
4846
124
    return exec_builtin_or_dynamic(mod);
4847
124
}
4848
4849
4850
#endif /* HAVE_DYNAMIC_LOADING */
4851
4852
/*[clinic input]
4853
_imp.exec_builtin -> int
4854
4855
    mod: object
4856
    /
4857
4858
Initialize a built-in module.
4859
[clinic start generated code]*/
4860
4861
static int
4862
_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
4863
/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
4864
531
{
4865
531
    return exec_builtin_or_dynamic(mod);
4866
531
}
4867
4868
/*[clinic input]
4869
_imp.source_hash
4870
4871
    key: long
4872
    source: Py_buffer
4873
[clinic start generated code]*/
4874
4875
static PyObject *
4876
_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
4877
/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
4878
0
{
4879
0
    union {
4880
0
        uint64_t x;
4881
0
        char data[sizeof(uint64_t)];
4882
0
    } hash;
4883
0
    hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
4884
#if !PY_LITTLE_ENDIAN
4885
    // Force to little-endian. There really ought to be a succinct standard way
4886
    // to do this.
4887
    for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
4888
        char tmp = hash.data[i];
4889
        hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
4890
        hash.data[sizeof(hash.data) - i - 1] = tmp;
4891
    }
4892
#endif
4893
0
    return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
4894
0
}
4895
4896
4897
PyDoc_STRVAR(doc_imp,
4898
"(Extremely) low-level import machinery bits as used by importlib.");
4899
4900
static PyMethodDef imp_methods[] = {
4901
    _IMP_EXTENSION_SUFFIXES_METHODDEF
4902
    _IMP_LOCK_HELD_METHODDEF
4903
    _IMP_ACQUIRE_LOCK_METHODDEF
4904
    _IMP_RELEASE_LOCK_METHODDEF
4905
    _IMP_FIND_FROZEN_METHODDEF
4906
    _IMP_GET_FROZEN_OBJECT_METHODDEF
4907
    _IMP_IS_FROZEN_PACKAGE_METHODDEF
4908
    _IMP_CREATE_BUILTIN_METHODDEF
4909
    _IMP_INIT_FROZEN_METHODDEF
4910
    _IMP_IS_BUILTIN_METHODDEF
4911
    _IMP_IS_FROZEN_METHODDEF
4912
    _IMP__FROZEN_MODULE_NAMES_METHODDEF
4913
    _IMP__OVERRIDE_FROZEN_MODULES_FOR_TESTS_METHODDEF
4914
    _IMP__OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK_METHODDEF
4915
    _IMP_CREATE_DYNAMIC_METHODDEF
4916
    _IMP_EXEC_DYNAMIC_METHODDEF
4917
    _IMP_EXEC_BUILTIN_METHODDEF
4918
    _IMP__FIX_CO_FILENAME_METHODDEF
4919
    _IMP_SOURCE_HASH_METHODDEF
4920
    {NULL, NULL}  /* sentinel */
4921
};
4922
4923
4924
static int
4925
imp_module_exec(PyObject *module)
4926
28
{
4927
28
    const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
4928
28
    PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
4929
28
    if (PyModule_Add(module, "check_hash_based_pycs", pyc_mode) < 0) {
4930
0
        return -1;
4931
0
    }
4932
4933
28
    if (PyModule_AddIntConstant(
4934
28
            module, "pyc_magic_number_token", PYC_MAGIC_NUMBER_TOKEN) < 0)
4935
0
    {
4936
0
        return -1;
4937
0
    }
4938
4939
28
    return 0;
4940
28
}
4941
4942
4943
static PyModuleDef_Slot imp_slots[] = {
4944
    {Py_mod_exec, imp_module_exec},
4945
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
4946
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
4947
    {0, NULL}
4948
};
4949
4950
static struct PyModuleDef imp_module = {
4951
    PyModuleDef_HEAD_INIT,
4952
    .m_name = "_imp",
4953
    .m_doc = doc_imp,
4954
    .m_size = 0,
4955
    .m_methods = imp_methods,
4956
    .m_slots = imp_slots,
4957
};
4958
4959
PyMODINIT_FUNC
4960
PyInit__imp(void)
4961
28
{
4962
28
    return PyModuleDef_Init(&imp_module);
4963
28
}