Coverage Report

Created: 2026-05-16 06:46

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