Coverage Report

Created: 2026-10-17 06:15

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