Coverage Report

Created: 2026-07-14 06:16

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