Coverage Report

Created: 2026-06-21 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/import.c
Line
Count
Source
1
/* Module definition and import implementation */
2
3
#include "Python.h"
4
#include "pycore_audit.h"         // _PySys_Audit()
5
#include "pycore_ceval.h"
6
#include "pycore_critical_section.h"  // Py_BEGIN_CRITICAL_SECTION()
7
#include "pycore_dict.h"          // _PyDict_Contains_KnownHash()
8
#include "pycore_hashtable.h"     // _Py_hashtable_new_full()
9
#include "pycore_import.h"        // _PyImport_BootstrapImp()
10
#include "pycore_initconfig.h"    // _PyStatus_OK()
11
#include "pycore_interp.h"        // struct _import_runtime_state
12
#include "pycore_interpframe.h"
13
#include "pycore_lazyimportobject.h"
14
#include "pycore_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
15.3k
#define INITTAB _PyRuntime.imports.inittab
81
1.08k
#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
10.8M
    (interp)->imports.modules
91
#define MODULES_BY_INDEX(interp) \
92
396
    (interp)->imports.modules_by_index
93
#define LAZY_MODULES(interp) \
94
3.67k
    (interp)->imports.lazy_modules
95
#define LAZY_PENDING_SUBMODULES(interp) \
96
1.36M
    (interp)->imports.lazy_pending_submodules
97
#define IMPORTLIB(interp) \
98
24.1k
    (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
14.2k
    (interp)->imports.override_frozen_modules
103
#ifdef HAVE_DLOPEN
104
#  define DLOPENFLAGS(interp) \
105
410
        (interp)->imports.dlopenflags
106
#endif
107
#define IMPORT_FUNC(interp) \
108
3.82M
    (interp)->imports.import_func
109
110
#define LAZY_IMPORT_FUNC(interp) \
111
337
    (interp)->imports.lazy_import_func
112
113
#define IMPORT_LOCK(interp) \
114
216k
    (interp)->imports.lock
115
116
#define FIND_AND_LOAD(interp) \
117
14.3k
    (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
72.0k
{
155
72.0k
    _PyRecursiveMutex_Lock(&IMPORT_LOCK(interp));
156
72.0k
}
157
158
void
159
_PyImport_ReleaseLock(PyInterpreterState *interp)
160
72.0k
{
161
72.0k
    _PyRecursiveMutex_Unlock(&IMPORT_LOCK(interp));
162
72.0k
}
163
164
void
165
_PyImport_ReInitLock(PyInterpreterState *interp)
166
0
{
167
    // gh-126688: Thread id may change after fork() on some operating systems.
168
0
    IMPORT_LOCK(interp).thread = PyThread_get_thread_ident_ex();
169
0
}
170
171
172
/***************/
173
/* sys.modules */
174
/***************/
175
176
PyObject *
177
_PyImport_InitModules(PyInterpreterState *interp)
178
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
797k
{
190
797k
    return MODULES(interp);
191
797k
}
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
10.0M
{
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
10.0M
    PyObject *modules = MODULES(tstate->interp);
222
10.0M
    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
10.0M
    return modules;
231
10.0M
}
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
10.0M
{
259
10.0M
    PyObject *modules = get_modules_dict(tstate, false);
260
10.0M
    if (modules == NULL) {
261
0
        return NULL;
262
0
    }
263
264
10.0M
    PyObject *m;
265
10.0M
    Py_INCREF(modules);
266
10.0M
    (void)PyMapping_GetOptionalItem(modules, name, &m);
267
10.0M
    Py_DECREF(modules);
268
10.0M
    return m;
269
10.0M
}
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
4.88M
{
292
4.88M
    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
4.88M
    int rc = PyObject_GetOptionalAttr(mod, &_Py_ID(__spec__), &spec);
300
4.88M
    if (rc > 0) {
301
4.88M
        rc = _PyModuleSpec_IsInitializing(spec);
302
4.88M
        Py_DECREF(spec);
303
4.88M
    }
304
4.88M
    if (rc == 0) {
305
4.88M
        goto done;
306
4.88M
    }
307
994
    else if (rc < 0) {
308
0
        return rc;
309
0
    }
310
311
    /* Wait until module is done importing. */
312
994
    PyObject *value = PyObject_CallMethodOneArg(
313
994
        IMPORTLIB(interp), &_Py_ID(_lock_unlock_module), name);
314
994
    if (value == NULL) {
315
0
        return -1;
316
0
    }
317
994
    Py_DECREF(value);
318
319
4.88M
done:
320
    /* When -X importtime=2, print an import time entry even if an
321
       imported module has already been loaded.
322
     */
323
4.88M
    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
4.88M
    return 0;
332
994
}
333
334
static void remove_importlib_frames(PyThreadState *tstate);
335
336
PyObject *
337
PyImport_GetModule(PyObject *name)
338
806k
{
339
806k
    PyThreadState *tstate = _PyThreadState_GET();
340
806k
    PyObject *mod;
341
342
806k
    mod = import_get_module(tstate, name);
343
806k
    if (mod != NULL && mod != Py_None) {
344
806k
        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
806k
        PyObject *mod_check = import_get_module(tstate, name);
351
806k
        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
806k
        Py_DECREF(mod_check);
364
806k
    }
365
806k
    return mod;
366
367
0
error:
368
0
    Py_DECREF(mod);
369
0
    remove_importlib_frames(tstate);
370
0
    return NULL;
371
806k
}
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.08k
{
510
1.08k
    return _Py_atomic_add_ssize(&LAST_MODULE_INDEX, 1) + 1;
511
1.08k
}
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.90k
# 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
410
{
911
410
    return DLOPENFLAGS(interp);
912
410
}
913
914
void
915
_PyImport_SetDLOpenFlags(PyInterpreterState *interp, int new_val)
916
0
{
917
0
    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
939
exec_builtin_or_dynamic(PyObject *mod) {
925
939
    void *state;
926
927
939
    if (!PyModule_Check(mod)) {
928
0
        return 0;
929
0
    }
930
931
939
    state = PyModule_GetState(mod);
932
939
    if (state) {
933
        /* Already initialized; skip reload */
934
0
        return 0;
935
0
    }
936
937
939
    return PyModule_Exec(mod);
938
939
}
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
975
{
1324
975
    PyMem_RawFree(ptr);
1325
975
}
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
975
    else {
1399
975
        hashtable_destroy_str(key);
1400
975
    }
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
939
{
1668
939
    if (_Py_IsMainInterpreter(tstate->interp)) {
1669
939
        return tstate;
1670
939
    }
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
939
{
2024
    /* Only single-phase init modules will be in the cache. */
2025
939
    struct extensions_cache_value *cached
2026
939
            = _extensions_cache_get(info->path, info->name);
2027
939
    if (cached == NULL) {
2028
939
        return NULL;
2029
939
    }
2030
939
    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
939
{
2099
    /* Core modules go through _PyImport_FixupBuiltin(). */
2100
939
    assert(!is_core_module(tstate->interp, info->name, info->path));
2101
2102
939
    PyObject *mod = NULL;
2103
939
    PyModuleDef *def = NULL;
2104
939
    struct extensions_cache_value *cached = NULL;
2105
939
    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
939
    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
939
    PyThreadState *main_tstate = switch_to_main_interpreter(tstate);
2156
939
    if (main_tstate == NULL) {
2157
0
        return NULL;
2158
0
    }
2159
939
    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
939
    struct _Py_ext_module_loader_result res;
2167
939
    int rc = _PyImport_RunModInitFunc(p0, info, &res);
2168
939
    bool main_error = false;
2169
939
    if (rc < 0) {
2170
        /* We discard res.def. */
2171
0
        assert(res.module == NULL);
2172
0
    }
2173
939
    else {
2174
939
        assert(!PyErr_Occurred());
2175
939
        assert(res.err == NULL);
2176
2177
939
        mod = res.module;
2178
939
        res.module = NULL;
2179
939
        def = res.def;
2180
939
        assert(def != NULL);
2181
2182
        /* Do anything else that should be done
2183
         * while still using the main interpreter. */
2184
939
        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
939
    }
2245
2246
939
main_finally:
2247
939
    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
939
    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
939
    if (rc < 0) {
2278
0
        goto error;
2279
0
    }
2280
939
    if (main_error) {
2281
0
        goto error;
2282
0
    }
2283
2284
939
    if (res.kind == _Py_ext_module_kind_MULTIPHASE) {
2285
939
        assert_multiphase_def(def);
2286
939
        assert(mod == NULL);
2287
        /* Note that we cheat a little by not repeating the calls
2288
         * to _PyImport_GetModuleExportHooks() and _PyImport_RunModInitFunc(). */
2289
939
        mod = PyModule_FromDefAndSpec(def, spec);
2290
939
        if (mod == NULL) {
2291
0
            goto error;
2292
0
        }
2293
939
    }
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
939
    _Py_ext_module_loader_result_clear(&res);
2330
939
    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
939
}
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
14.5k
{
2459
14.5k
    int i;
2460
14.5k
    struct _inittab *inittab = INITTAB;
2461
551k
    for (i = 0; inittab[i].name != NULL; i++) {
2462
537k
        if (_PyUnicode_EqualToASCIIString(name, inittab[i].name)) {
2463
698
            if (inittab[i].initfunc == NULL)
2464
0
                return -1;
2465
698
            else
2466
698
                return 1;
2467
698
        }
2468
537k
    }
2469
13.8k
    return 0;
2470
14.5k
}
2471
2472
static struct _inittab*
2473
lookup_inittab_entry(const struct _Py_ext_module_loader_info* info)
2474
734
{
2475
13.8k
    for (struct _inittab *p = INITTAB; p->name != NULL; p++) {
2476
13.8k
        if (_PyUnicode_EqualToASCIIString(info->name, p->name)) {
2477
734
            return p;
2478
734
        }
2479
13.8k
    }
2480
    // not found
2481
0
    return NULL;
2482
734
}
2483
2484
static PyObject*
2485
create_builtin(
2486
    PyThreadState *tstate, PyObject *name,
2487
    PyObject *spec,
2488
    PyModInitFunction initfunc)
2489
734
{
2490
734
    struct _Py_ext_module_loader_info info;
2491
734
    if (_Py_ext_module_loader_info_init_for_builtin(&info, name) < 0) {
2492
0
        return NULL;
2493
0
    }
2494
2495
734
    struct extensions_cache_value *cached = NULL;
2496
734
    PyObject *mod = import_find_extension(tstate, &info, &cached);
2497
734
    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
734
    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
734
    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
734
    PyModInitFunction p0 = NULL;
2520
734
    if (initfunc == NULL) {
2521
734
        struct _inittab *entry = lookup_inittab_entry(&info);
2522
734
        if (entry == NULL) {
2523
0
            mod = NULL;
2524
0
            _PyErr_SetModuleNotFoundError(name);
2525
0
            goto finally;
2526
0
        }
2527
2528
734
        p0 = (PyModInitFunction)entry->initfunc;
2529
734
    }
2530
0
    else {
2531
0
        p0 = initfunc;
2532
0
    }
2533
2534
734
    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
734
    mod = import_run_extension(
2552
734
                    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
734
finally:
2561
734
    _Py_ext_module_loader_info_clear(&info);
2562
734
    return mod;
2563
734
}
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
6.57k
{
2928
6.57k
    PyObject *oldname;
2929
2930
6.57k
    if (PyUnicode_Compare(co->co_filename, newname) == 0)
2931
6.57k
        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.22k
{
2951
1.22k
    const struct _module_alias *entry;
2952
9.63k
    for (entry = aliases; ; entry++) {
2953
9.63k
        if (entry->name == NULL) {
2954
            /* It isn't an alias. */
2955
1.04k
            return false;
2956
1.04k
        }
2957
8.58k
        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
8.58k
    }
2964
1.22k
}
2965
2966
static bool
2967
use_frozen(void)
2968
14.2k
{
2969
14.2k
    PyInterpreterState *interp = _PyInterpreterState_GET();
2970
14.2k
    int override = OVERRIDE_FROZEN_MODULES(interp);
2971
14.2k
    if (override > 0) {
2972
0
        return true;
2973
0
    }
2974
14.2k
    else if (override < 0) {
2975
0
        return false;
2976
0
    }
2977
14.2k
    else {
2978
14.2k
        return interp->config.use_frozen_modules;
2979
14.2k
    }
2980
14.2k
}
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
14.4k
{
3110
14.4k
    const struct _frozen *p;
3111
    // We always use the bootstrap modules.
3112
57.3k
    for (p = _PyImport_FrozenBootstrap; ; p++) {
3113
57.3k
        if (p->name == NULL) {
3114
            // We hit the end-of-list sentinel value.
3115
14.2k
            break;
3116
14.2k
        }
3117
43.1k
        if (strcmp(name, p->name) == 0) {
3118
252
            return p;
3119
252
        }
3120
43.1k
    }
3121
    // Prefer custom modules, if any.  Frozen stdlib modules can be
3122
    // disabled here by setting "code" to NULL in the array entry.
3123
14.2k
    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
14.2k
    if (use_frozen()) {
3135
273k
        for (p = _PyImport_FrozenStdlib; ; p++) {
3136
273k
            if (p->name == NULL) {
3137
13.2k
                break;
3138
13.2k
            }
3139
259k
            if (strcmp(name, p->name) == 0) {
3140
970
                return p;
3141
970
            }
3142
259k
        }
3143
159k
        for (p = _PyImport_FrozenTest; ; p++) {
3144
159k
            if (p->name == NULL) {
3145
13.2k
                break;
3146
13.2k
            }
3147
145k
            if (strcmp(name, p->name) == 0) {
3148
0
                return p;
3149
0
            }
3150
145k
        }
3151
13.2k
    }
3152
13.2k
    return NULL;
3153
14.2k
}
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
14.4k
{
3167
14.4k
    if (info != NULL) {
3168
14.4k
        memset(info, 0, sizeof(*info));
3169
14.4k
    }
3170
3171
14.4k
    if (nameobj == NULL || nameobj == Py_None) {
3172
0
        return FROZEN_BAD_NAME;
3173
0
    }
3174
14.4k
    const char *name = _PyUnicode_AsUTF8NoNUL(nameobj);
3175
14.4k
    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
14.4k
    const struct _frozen *p = look_up_frozen(name);
3185
14.4k
    if (p == NULL) {
3186
13.2k
        return FROZEN_NOT_FOUND;
3187
13.2k
    }
3188
1.22k
    if (info != NULL) {
3189
1.22k
        info->nameobj = nameobj;  // borrowed
3190
1.22k
        info->data = (const char *)p->code;
3191
1.22k
        info->size = p->size;
3192
1.22k
        info->is_package = p->is_package;
3193
1.22k
        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.22k
        info->origname = name;
3199
1.22k
        info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
3200
1.22k
                                              &info->origname);
3201
1.22k
    }
3202
1.22k
    if (p->code == NULL) {
3203
        /* It is frozen but marked as un-importable. */
3204
0
        return FROZEN_EXCLUDED;
3205
0
    }
3206
1.22k
    if (p->code[0] == '\0' || p->size == 0) {
3207
        /* Does not contain executable code. */
3208
0
        return FROZEN_INVALID;
3209
0
    }
3210
1.22k
    return FROZEN_OKAY;
3211
1.22k
}
3212
3213
static PyObject *
3214
unmarshal_frozen_code(PyInterpreterState *interp, struct frozen_info *info)
3215
593
{
3216
593
    PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
3217
593
    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
593
    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
593
    return co;
3232
593
}
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
3.80M
{
3606
3.80M
    return func == IMPORT_FUNC(interp);
3607
3.80M
}
3608
3609
int
3610
_PyImport_IsDefaultLazyImportFunc(PyInterpreterState *interp, PyObject *func)
3611
301
{
3612
301
    return func == LAZY_IMPORT_FUNC(interp);
3613
301
}
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
11.2k
{
3662
11.2k
    const char *importlib_filename = "<frozen importlib._bootstrap>";
3663
11.2k
    const char *external_filename = "<frozen importlib._bootstrap_external>";
3664
11.2k
    const char *remove_frames = "_call_with_frames_removed";
3665
11.2k
    int always_trim = 0;
3666
11.2k
    int in_importlib = 0;
3667
11.2k
    PyObject **prev_link, **outer_link = NULL;
3668
11.2k
    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
11.2k
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3675
11.2k
    if (exc == NULL || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
3676
0
        goto done;
3677
0
    }
3678
3679
11.2k
    if (PyType_IsSubtype(Py_TYPE(exc), (PyTypeObject *) PyExc_ImportError)) {
3680
11.2k
        always_trim = 1;
3681
11.2k
    }
3682
3683
11.2k
    assert(PyExceptionInstance_Check(exc));
3684
11.2k
    base_tb = PyException_GetTraceback(exc);
3685
11.2k
    prev_link = &base_tb;
3686
11.2k
    PyObject *tb = base_tb;
3687
53.2k
    while (tb != NULL) {
3688
42.0k
        assert(PyTraceBack_Check(tb));
3689
42.0k
        PyTracebackObject *traceback = (PyTracebackObject *)tb;
3690
42.0k
        PyObject *next = (PyObject *) traceback->tb_next;
3691
42.0k
        PyFrameObject *frame = traceback->tb_frame;
3692
42.0k
        PyCodeObject *code = PyFrame_GetCode(frame);
3693
42.0k
        int now_in_importlib;
3694
3695
42.0k
        now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
3696
9.78k
                           _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
3697
42.0k
        if (now_in_importlib && !in_importlib) {
3698
            /* This is the link to this chunk of importlib tracebacks */
3699
11.2k
            outer_link = prev_link;
3700
11.2k
        }
3701
42.0k
        in_importlib = now_in_importlib;
3702
3703
42.0k
        if (in_importlib &&
3704
37.1k
            (always_trim ||
3705
37.1k
             _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
3706
37.1k
            Py_XSETREF(*outer_link, Py_XNewRef(next));
3707
37.1k
            prev_link = outer_link;
3708
37.1k
        }
3709
4.89k
        else {
3710
4.89k
            prev_link = (PyObject **) &traceback->tb_next;
3711
4.89k
        }
3712
42.0k
        Py_DECREF(code);
3713
42.0k
        tb = next;
3714
42.0k
    }
3715
11.2k
    if (base_tb == NULL) {
3716
6.33k
        base_tb = Py_None;
3717
6.33k
        Py_INCREF(Py_None);
3718
6.33k
    }
3719
11.2k
    PyException_SetTraceback(exc, base_tb);
3720
11.2k
done:
3721
11.2k
    Py_XDECREF(base_tb);
3722
11.2k
    _PyErr_SetRaisedException(tstate, exc);
3723
11.2k
}
3724
3725
3726
static PyObject *
3727
resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
3728
545
{
3729
545
    PyObject *abs_name;
3730
545
    PyObject *package = NULL;
3731
545
    PyObject *spec = NULL;
3732
545
    Py_ssize_t last_dot;
3733
545
    PyObject *base;
3734
545
    int level_up;
3735
3736
545
    if (globals == NULL) {
3737
0
        _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
3738
0
        goto error;
3739
0
    }
3740
545
    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
545
    if (PyDict_GetItemRef(globals, &_Py_ID(__package__), &package) < 0) {
3746
0
        goto error;
3747
0
    }
3748
545
    if (package == Py_None) {
3749
0
        Py_DECREF(package);
3750
0
        package = NULL;
3751
0
    }
3752
545
    if (PyDict_GetItemRef(globals, &_Py_ID(__spec__), &spec) < 0) {
3753
0
        goto error;
3754
0
    }
3755
3756
545
    if (package != NULL) {
3757
545
        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
545
        else if (spec != NULL && spec != Py_None) {
3763
545
            int equal;
3764
545
            PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent));
3765
545
            if (parent == NULL) {
3766
0
                goto error;
3767
0
            }
3768
3769
545
            equal = PyObject_RichCompareBool(package, parent, Py_EQ);
3770
545
            Py_DECREF(parent);
3771
545
            if (equal < 0) {
3772
0
                goto error;
3773
0
            }
3774
545
            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
545
        }
3781
545
    }
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
545
    last_dot = PyUnicode_GET_LENGTH(package);
3839
545
    if (last_dot == 0) {
3840
0
        goto no_parent_error;
3841
0
    }
3842
3843
545
    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
545
    Py_XDECREF(spec);
3857
545
    base = PyUnicode_Substring(package, 0, last_dot);
3858
545
    Py_DECREF(package);
3859
545
    if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
3860
144
        return base;
3861
144
    }
3862
3863
401
    abs_name = PyUnicode_FromFormat("%U.%U", base, name);
3864
401
    Py_DECREF(base);
3865
401
    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
19
{
3888
19
    PyObject *obj = NULL;
3889
19
    PyObject *fromlist = Py_None;
3890
19
    PyObject *import_func = NULL;
3891
19
    assert(lazy_import != NULL);
3892
19
    assert(PyLazyImport_CheckExact(lazy_import));
3893
3894
19
    PyLazyImportObject *lz = (PyLazyImportObject *)lazy_import;
3895
19
    PyInterpreterState *interp = tstate->interp;
3896
3897
    // Acquire the global import lock to serialize reification
3898
19
    _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
19
    PyObject *importing = interp->imports.lazy_importing_modules;
3904
19
    if (importing == NULL) {
3905
6
        importing = interp->imports.lazy_importing_modules = PySet_New(NULL);
3906
6
        if (importing == NULL) {
3907
0
            _PyImport_ReleaseLock(interp);
3908
0
            return NULL;
3909
0
        }
3910
6
    }
3911
3912
19
    assert(PyAnySet_CheckExact(importing));
3913
19
    int is_loading = _PySet_Contains((PySetObject *)importing, lazy_import);
3914
19
    if (is_loading < 0) {
3915
0
        _PyImport_ReleaseLock(interp);
3916
0
        return NULL;
3917
0
    }
3918
19
    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
19
    else if (PySet_Add(importing, lazy_import) < 0) {
3940
0
        goto error;
3941
0
    }
3942
3943
19
    Py_ssize_t dot = -1;
3944
19
    int full = 0;
3945
19
    if (lz->lz_attr != NULL) {
3946
7
        full = 1;
3947
7
    }
3948
19
    if (!full) {
3949
12
        dot = PyUnicode_FindChar(lz->lz_from, '.', 0,
3950
12
                                 PyUnicode_GET_LENGTH(lz->lz_from), 1);
3951
12
    }
3952
19
    if (dot < 0) {
3953
19
        full = 1;
3954
19
    }
3955
3956
19
    if (lz->lz_attr != NULL) {
3957
7
        if (PyUnicode_Check(lz->lz_attr)) {
3958
7
            fromlist = PyTuple_New(1);
3959
7
            if (fromlist == NULL) {
3960
0
                goto error;
3961
0
            }
3962
7
            Py_INCREF(lz->lz_attr);
3963
7
            PyTuple_SET_ITEM(fromlist, 0, lz->lz_attr);
3964
7
        }
3965
0
        else {
3966
0
            Py_INCREF(lz->lz_attr);
3967
0
            fromlist = lz->lz_attr;
3968
0
        }
3969
7
    }
3970
3971
19
    PyObject *globals = PyEval_GetGlobals();
3972
3973
19
    if (PyMapping_GetOptionalItem(lz->lz_builtins, &_Py_ID(__import__),
3974
19
                                  &import_func) < 0) {
3975
0
        goto error;
3976
0
    }
3977
19
    if (import_func == NULL) {
3978
0
        PyErr_SetString(PyExc_ImportError, "__import__ not found");
3979
0
        goto error;
3980
0
    }
3981
19
    if (full) {
3982
19
        obj = _PyEval_ImportNameWithImport(
3983
19
            tstate, import_func, globals, globals,
3984
19
            lz->lz_from, fromlist, _PyLong_GetZero()
3985
19
        );
3986
19
    }
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
19
    if (obj == NULL) {
3999
0
        goto error;
4000
0
    }
4001
4002
19
    if (lz->lz_attr != NULL && PyUnicode_Check(lz->lz_attr)) {
4003
7
        PyObject *from = obj;
4004
7
        obj = _PyEval_ImportFrom(tstate, from, lz->lz_attr);
4005
7
        Py_DECREF(from);
4006
7
        if (obj == NULL) {
4007
0
            goto error;
4008
0
        }
4009
7
    }
4010
4011
19
    assert(!PyLazyImport_CheckExact(obj));
4012
4013
19
    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
19
ok:
4093
19
    if (PySet_Discard(importing, lazy_import) < 0) {
4094
0
        Py_CLEAR(obj);
4095
0
    }
4096
4097
    // Release the global import lock.
4098
19
    _PyImport_ReleaseLock(interp);
4099
4100
19
    Py_XDECREF(fromlist);
4101
19
    Py_XDECREF(import_func);
4102
19
    return obj;
4103
0
}
4104
4105
static PyObject *
4106
import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
4107
14.3k
{
4108
14.3k
    PyObject *mod = NULL;
4109
14.3k
    PyInterpreterState *interp = tstate->interp;
4110
14.3k
    int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
4111
14.3k
#define import_level FIND_AND_LOAD(interp).import_level
4112
14.3k
#define accumulated FIND_AND_LOAD(interp).accumulated
4113
4114
14.3k
    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
14.3k
    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
14.3k
    if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
4131
0
        PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
4132
4133
14.3k
    mod = PyObject_CallMethodObjArgs(IMPORTLIB(interp), &_Py_ID(_find_and_load),
4134
14.3k
                                     abs_name, IMPORT_FUNC(interp), NULL);
4135
4136
14.3k
    if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
4137
0
        PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
4138
0
                                       mod != NULL);
4139
4140
14.3k
    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
14.3k
    return mod;
4155
14.3k
#undef import_level
4156
14.3k
#undef accumulated
4157
14.3k
}
4158
4159
static PyObject *
4160
get_abs_name(PyThreadState *tstate, PyObject *name, PyObject *globals,
4161
             int level)
4162
4.09M
{
4163
4.09M
    if (level > 0) {
4164
545
        return resolve_name(tstate, name, globals, level);
4165
545
    }
4166
4.09M
    if (PyUnicode_GET_LENGTH(name) == 0) {
4167
0
        _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
4168
0
        return NULL;
4169
0
    }
4170
4.09M
    return Py_NewRef(name);
4171
4.09M
}
4172
4173
PyObject *
4174
_PyImport_GetAbsName(PyThreadState *tstate, PyObject *name,
4175
                     PyObject *globals, int level)
4176
4
{
4177
4
    return get_abs_name(tstate, name, globals, level);
4178
4
}
4179
4180
4181
PyObject *
4182
PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
4183
                                 PyObject *locals, PyObject *fromlist,
4184
                                 int level)
4185
4.09M
{
4186
4.09M
    PyThreadState *tstate = _PyThreadState_GET();
4187
4.09M
    PyObject *abs_name = NULL;
4188
4.09M
    PyObject *final_mod = NULL;
4189
4.09M
    PyObject *mod = NULL;
4190
4.09M
    PyInterpreterState *interp = tstate->interp;
4191
4.09M
    int has_from;
4192
4193
4.09M
    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
4.09M
    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
4.09M
    if (level < 0) {
4207
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
4208
0
        goto error;
4209
0
    }
4210
4211
4.09M
    abs_name = get_abs_name(tstate, name, globals, level);
4212
4.09M
    if (abs_name == NULL) {
4213
0
        goto error;
4214
0
    }
4215
4216
4.09M
    mod = import_get_module(tstate, abs_name);
4217
4.09M
    if (mod == NULL && _PyErr_Occurred(tstate)) {
4218
0
        goto error;
4219
0
    }
4220
4221
4.09M
    if (mod != NULL && mod != Py_None) {
4222
4.08M
        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
4.08M
        PyObject *mod_check = import_get_module(tstate, abs_name);
4232
4.08M
        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
4.08M
        else {
4244
4.08M
            Py_DECREF(mod_check);
4245
4.08M
        }
4246
4.08M
    }
4247
14.3k
    else {
4248
14.3k
        Py_XDECREF(mod);
4249
14.3k
        mod = import_find_and_load(tstate, abs_name);
4250
14.3k
        if (mod == NULL) {
4251
11.2k
            goto error;
4252
11.2k
        }
4253
14.3k
    }
4254
4255
4.08M
    has_from = 0;
4256
4.08M
    if (fromlist != NULL && fromlist != Py_None) {
4257
1.64M
        has_from = PyObject_IsTrue(fromlist);
4258
1.64M
        if (has_from < 0)
4259
0
            goto error;
4260
1.64M
    }
4261
4.08M
    if (!has_from) {
4262
2.72M
        Py_ssize_t len = PyUnicode_GET_LENGTH(name);
4263
2.72M
        if (level == 0 || len > 0) {
4264
2.72M
            Py_ssize_t dot;
4265
4266
2.72M
            dot = PyUnicode_FindChar(name, '.', 0, len, 1);
4267
2.72M
            if (dot == -2) {
4268
0
                goto error;
4269
0
            }
4270
4271
2.72M
            if (dot == -1) {
4272
                /* No dot in module name, simple exit */
4273
2.72M
                final_mod = Py_NewRef(mod);
4274
2.72M
                goto error;
4275
2.72M
            }
4276
4277
2.91k
            if (level == 0) {
4278
2.91k
                PyObject *front = PyUnicode_Substring(name, 0, dot);
4279
2.91k
                if (front == NULL) {
4280
0
                    goto error;
4281
0
                }
4282
4283
2.91k
                final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
4284
2.91k
                Py_DECREF(front);
4285
2.91k
            }
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.91k
        }
4309
0
        else {
4310
0
            final_mod = Py_NewRef(mod);
4311
0
        }
4312
2.72M
    }
4313
1.35M
    else {
4314
1.35M
        int has_path = PyObject_HasAttrWithError(mod, &_Py_ID(__path__));
4315
1.35M
        if (has_path < 0) {
4316
0
            goto error;
4317
0
        }
4318
1.35M
        if (has_path) {
4319
8.63k
            final_mod = PyObject_CallMethodObjArgs(
4320
8.63k
                        IMPORTLIB(interp), &_Py_ID(_handle_fromlist),
4321
8.63k
                        mod, fromlist, IMPORT_FUNC(interp), NULL);
4322
8.63k
        }
4323
1.35M
        else {
4324
1.35M
            final_mod = Py_NewRef(mod);
4325
1.35M
        }
4326
1.35M
    }
4327
4328
4.09M
  error:
4329
4.09M
    Py_XDECREF(abs_name);
4330
4.09M
    Py_XDECREF(mod);
4331
4.09M
    if (final_mod == NULL) {
4332
11.2k
        remove_importlib_frames(tstate);
4333
11.2k
    }
4334
4.09M
    return final_mod;
4335
4.08M
}
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
479
{
4342
479
    PyObject *lazy_submodules;
4343
479
    Py_BEGIN_CRITICAL_SECTION(lazy_modules);
4344
479
    int err = _PyDict_GetItemRef_Unicode_LockHeld(lazy_modules, parent,
4345
479
                                                  &lazy_submodules);
4346
479
    if (err == 0) {
4347
        // value isn't present
4348
263
        lazy_submodules = PySet_New(NULL);
4349
263
        if (lazy_submodules != NULL &&
4350
263
            _PyDict_SetItem_LockHeld(lazy_modules, parent,
4351
263
                                     lazy_submodules) < 0) {
4352
0
            Py_CLEAR(lazy_submodules);
4353
0
        }
4354
263
    }
4355
479
    Py_END_CRITICAL_SECTION();
4356
479
    return lazy_submodules;
4357
479
}
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
341
{
4366
341
    int ret = -1;
4367
341
    PyObject *parent = NULL;
4368
341
    PyObject *child = NULL;
4369
4370
341
    PyInterpreterState *interp = tstate->interp;
4371
341
    PyObject *lazy_pending_submodules = LAZY_PENDING_SUBMODULES(interp);
4372
341
    assert(lazy_pending_submodules != NULL);
4373
4374
341
    Py_INCREF(name);
4375
479
    while (true) {
4376
479
        Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
4377
479
                                            PyUnicode_GET_LENGTH(name), -1);
4378
479
        if (dot < 0) {
4379
341
            PyObject *lazy_submodules = ensure_lazy_pending_submodules(
4380
341
                (PyDictObject *)lazy_pending_submodules, name);
4381
341
            if (lazy_submodules == NULL) {
4382
0
                goto done;
4383
0
            }
4384
341
            Py_DECREF(lazy_submodules);
4385
341
            ret = 0;
4386
341
            goto done;
4387
341
        }
4388
138
        parent = PyUnicode_Substring(name, 0, dot);
4389
138
        if (parent == NULL) {
4390
0
            goto done;
4391
0
        }
4392
138
        Py_XDECREF(child);
4393
138
        child = PyUnicode_Substring(name, dot + 1, PyUnicode_GET_LENGTH(name));
4394
138
        if (child == NULL) {
4395
0
            goto done;
4396
0
        }
4397
4398
138
        PyObject *lazy_submodules = ensure_lazy_pending_submodules(
4399
138
            (PyDictObject *)lazy_pending_submodules, parent);
4400
138
        if (lazy_submodules == NULL) {
4401
0
            goto done;
4402
0
        }
4403
4404
138
        if (PySet_Add(lazy_submodules, child) < 0) {
4405
0
            Py_DECREF(lazy_submodules);
4406
0
            goto done;
4407
0
        }
4408
138
        Py_DECREF(lazy_submodules);
4409
4410
138
        Py_SETREF(name, parent);
4411
138
        parent = NULL;
4412
138
    }
4413
4414
341
done:
4415
341
    Py_XDECREF(child);
4416
341
    Py_XDECREF(parent);
4417
341
    Py_XDECREF(name);
4418
341
    return ret;
4419
341
}
4420
4421
static int
4422
register_from_lazy_on_parent(PyThreadState *tstate, PyObject *abs_name,
4423
                             PyObject *from)
4424
126
{
4425
126
    PyObject *fromname = PyUnicode_FromFormat("%U.%U", abs_name, from);
4426
126
    if (fromname == NULL) {
4427
0
        return -1;
4428
0
    }
4429
4430
    // Add the module name to sys.lazy_modules set (PEP 810).
4431
126
    PyObject *lazy_modules = LAZY_MODULES(tstate->interp);
4432
126
    if (PySet_Add(lazy_modules, fromname) < 0) {
4433
0
        Py_DECREF(fromname);
4434
0
        return -1;
4435
0
    }
4436
4437
126
    int res = register_lazy_on_parent(tstate, fromname);
4438
126
    Py_DECREF(fromname);
4439
126
    return res;
4440
126
}
4441
4442
PyObject *
4443
_PyImport_TryLoadLazySubmodule(PyObject *mod_name, PyObject *attr_name)
4444
1.36M
{
4445
1.36M
    PyInterpreterState *interp = _PyInterpreterState_GET();
4446
1.36M
    PyObject *lazy_pending = LAZY_PENDING_SUBMODULES(interp);
4447
1.36M
    if (lazy_pending == NULL) {
4448
0
        return NULL;
4449
0
    }
4450
4451
1.36M
    PyObject *pending_set;
4452
1.36M
    int rc = PyDict_GetItemRef(lazy_pending, mod_name, &pending_set);
4453
1.36M
    if (rc <= 0) {
4454
1.36M
        return NULL;
4455
1.36M
    }
4456
4457
181
    int contains = PySet_Contains(pending_set, attr_name);
4458
181
    if (contains <= 0) {
4459
181
        Py_DECREF(pending_set);
4460
181
        return NULL;
4461
181
    }
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
301
{
4496
301
    assert(name != NULL);
4497
301
    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
301
    if (level < 0) {
4503
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
4504
0
        return NULL;
4505
0
    }
4506
4507
301
    PyObject *abs_name = get_abs_name(tstate, name, globals, level);
4508
301
    if (abs_name == NULL) {
4509
0
        return NULL;
4510
0
    }
4511
4512
301
    PyInterpreterState *interp = tstate->interp;
4513
301
    _PyInterpreterFrame *frame = _PyEval_GetFrame();
4514
301
    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
301
    LAZY_IMPORTS_LOCK(interp);
4526
301
    PyObject *filter = Py_XNewRef(LAZY_IMPORTS_FILTER(interp));
4527
301
    LAZY_IMPORTS_UNLOCK(interp);
4528
4529
301
    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_NewRef(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
301
    PyObject *res = _PyLazyImport_New(frame, builtins, abs_name, fromlist);
4572
301
    if (res == NULL) {
4573
0
        Py_DECREF(abs_name);
4574
0
        return NULL;
4575
0
    }
4576
4577
    // Add the module name to sys.lazy_modules set (PEP 810).
4578
301
    PyObject *lazy_modules = LAZY_MODULES(tstate->interp);
4579
301
    if (PySet_Add(lazy_modules, abs_name) < 0) {
4580
0
        goto error;
4581
0
    }
4582
4583
301
    if (fromlist && PyUnicode_Check(fromlist)) {
4584
0
        if (register_from_lazy_on_parent(tstate, abs_name, fromlist) < 0) {
4585
0
            goto error;
4586
0
        }
4587
0
    }
4588
301
    else if (fromlist && PyTuple_Check(fromlist) &&
4589
86
             PyTuple_GET_SIZE(fromlist)) {
4590
212
        for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(fromlist); i++) {
4591
126
            if (register_from_lazy_on_parent(tstate, abs_name,
4592
126
                                             PyTuple_GET_ITEM(fromlist, i)) < 0)
4593
0
            {
4594
0
                goto error;
4595
0
            }
4596
126
        }
4597
86
    }
4598
215
    else if (register_lazy_on_parent(tstate, abs_name) < 0) {
4599
0
        goto error;
4600
0
    }
4601
4602
301
    Py_DECREF(abs_name);
4603
301
    return res;
4604
0
error:
4605
0
    Py_DECREF(abs_name);
4606
0
    Py_DECREF(res);
4607
0
    return NULL;
4608
301
}
4609
4610
PyObject *
4611
PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
4612
                           PyObject *fromlist, int level)
4613
288
{
4614
288
    PyObject *nameobj, *mod;
4615
288
    nameobj = PyUnicode_FromString(name);
4616
288
    if (nameobj == NULL)
4617
0
        return NULL;
4618
288
    mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
4619
288
                                           fromlist, level);
4620
288
    Py_DECREF(nameobj);
4621
288
    return mod;
4622
288
}
4623
4624
4625
/* Re-import a module of any kind and return its module object, WITH
4626
   INCREMENTED REFERENCE COUNT */
4627
4628
PyObject *
4629
PyImport_ReloadModule(PyObject *m)
4630
0
{
4631
0
    PyObject *reloaded_module = NULL;
4632
0
    PyObject *importlib = PyImport_GetModule(&_Py_ID(importlib));
4633
0
    if (importlib == NULL) {
4634
0
        if (PyErr_Occurred()) {
4635
0
            return NULL;
4636
0
        }
4637
4638
0
        importlib = PyImport_ImportModule("importlib");
4639
0
        if (importlib == NULL) {
4640
0
            return NULL;
4641
0
        }
4642
0
    }
4643
4644
0
    reloaded_module = PyObject_CallMethodOneArg(importlib, &_Py_ID(reload), m);
4645
0
    Py_DECREF(importlib);
4646
0
    return reloaded_module;
4647
0
}
4648
4649
4650
/* Higher-level import emulator which emulates the "import" statement
4651
   more accurately -- it invokes the __import__() function from the
4652
   builtins of the current globals.  This means that the import is
4653
   done using whatever import hooks are installed in the current
4654
   environment.
4655
   A dummy list ["__doc__"] is passed as the 4th argument so that
4656
   e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
4657
   will return <module "gencache"> instead of <module "win32com">. */
4658
4659
PyObject *
4660
PyImport_Import(PyObject *module_name)
4661
286k
{
4662
286k
    PyThreadState *tstate = _PyThreadState_GET();
4663
286k
    PyObject *globals = NULL;
4664
286k
    PyObject *import = NULL;
4665
286k
    PyObject *builtins = NULL;
4666
286k
    PyObject *r = NULL;
4667
4668
286k
    PyObject *from_list = PyList_New(0);
4669
286k
    if (from_list == NULL) {
4670
0
        goto err;
4671
0
    }
4672
4673
    /* Get the builtins from current globals */
4674
286k
    globals = PyEval_GetGlobals();  // borrowed
4675
286k
    if (globals != NULL) {
4676
285k
        Py_INCREF(globals);
4677
        // XXX Use _PyEval_EnsureBuiltins()?
4678
285k
        builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
4679
285k
        if (builtins == NULL) {
4680
            // XXX Fall back to interp->builtins or sys.modules['builtins']?
4681
0
            goto err;
4682
0
        }
4683
285k
    }
4684
288
    else if (_PyErr_Occurred(tstate)) {
4685
0
        goto err;
4686
0
    }
4687
288
    else {
4688
        /* No globals -- use standard builtins, and fake globals */
4689
288
        globals = PyDict_New();
4690
288
        if (globals == NULL) {
4691
0
            goto err;
4692
0
        }
4693
288
        if (_PyEval_EnsureBuiltinsWithModule(tstate, globals, &builtins) < 0) {
4694
0
            goto err;
4695
0
        }
4696
288
    }
4697
4698
    /* Get the __import__ function from the builtins */
4699
286k
    if (PyDict_Check(builtins)) {
4700
285k
        import = PyObject_GetItem(builtins, &_Py_ID(__import__));
4701
285k
        if (import == NULL) {
4702
0
            _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
4703
0
        }
4704
285k
    }
4705
288
    else
4706
288
        import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
4707
286k
    if (import == NULL)
4708
0
        goto err;
4709
4710
    /* Call the __import__ function with the proper argument list
4711
       Always use absolute import here.
4712
       Calling for side-effect of import. */
4713
286k
    r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
4714
286k
                              globals, from_list, 0, NULL);
4715
286k
    if (r == NULL)
4716
0
        goto err;
4717
286k
    Py_DECREF(r);
4718
4719
286k
    r = import_get_module(tstate, module_name);
4720
286k
    if (r == NULL && !_PyErr_Occurred(tstate)) {
4721
0
        _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
4722
0
    }
4723
4724
286k
  err:
4725
286k
    Py_XDECREF(globals);
4726
286k
    Py_XDECREF(builtins);
4727
286k
    Py_XDECREF(import);
4728
286k
    Py_XDECREF(from_list);
4729
4730
286k
    return r;
4731
286k
}
4732
4733
4734
/*********************/
4735
/* runtime lifecycle */
4736
/*********************/
4737
4738
PyStatus
4739
_PyImport_Init(void)
4740
36
{
4741
36
    if (INITTAB != NULL) {
4742
0
        return _PyStatus_ERR("global import state already initialized");
4743
0
    }
4744
36
    if (init_builtin_modules_table() != 0) {
4745
0
        return PyStatus_NoMemory();
4746
0
    }
4747
36
    return _PyStatus_OK();
4748
36
}
4749
4750
void
4751
_PyImport_Fini(void)
4752
0
{
4753
    /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
4754
    // XXX Should we actually leave them (mostly) intact, since we don't
4755
    // ever dlclose() the module files?
4756
0
    _extensions_cache_clear_all();
4757
4758
    /* Free memory allocated by _PyImport_Init() */
4759
0
    fini_builtin_modules_table();
4760
0
}
4761
4762
void
4763
_PyImport_Fini2(void)
4764
0
{
4765
    // Reset PyImport_Inittab
4766
0
    PyImport_Inittab = _PyImport_Inittab;
4767
4768
    /* Free memory allocated by PyImport_ExtendInittab() */
4769
0
    _PyMem_DefaultRawFree(inittab_copy);
4770
0
    inittab_copy = NULL;
4771
0
}
4772
4773
4774
/*************************/
4775
/* interpreter lifecycle */
4776
/*************************/
4777
4778
PyStatus
4779
_PyImport_InitCore(PyThreadState *tstate, PyObject *sysmod, int importlib)
4780
36
{
4781
    // XXX Initialize here: interp->modules and interp->import_func.
4782
    // XXX Initialize here: sys.modules and sys.meta_path.
4783
4784
36
    if (importlib) {
4785
        /* This call sets up builtin and frozen import support */
4786
36
        if (init_importlib(tstate, sysmod) < 0) {
4787
0
            return _PyStatus_ERR("failed to initialize importlib");
4788
0
        }
4789
36
    }
4790
4791
36
    return _PyStatus_OK();
4792
36
}
4793
4794
/* In some corner cases it is important to be sure that the import
4795
   machinery has been initialized (or not cleaned up yet).  For
4796
   example, see issue #4236 and PyModule_Create2(). */
4797
4798
int
4799
_PyImport_IsInitialized(PyInterpreterState *interp)
4800
0
{
4801
0
    if (MODULES(interp) == NULL)
4802
0
        return 0;
4803
0
    return 1;
4804
0
}
4805
4806
/* Clear the direct per-interpreter import state, if not cleared already. */
4807
void
4808
_PyImport_ClearCore(PyInterpreterState *interp)
4809
0
{
4810
    /* interp->modules should have been cleaned up and cleared already
4811
       by _PyImport_FiniCore(). */
4812
0
    Py_CLEAR(MODULES(interp));
4813
0
    Py_CLEAR(MODULES_BY_INDEX(interp));
4814
0
    Py_CLEAR(IMPORTLIB(interp));
4815
0
    Py_CLEAR(IMPORT_FUNC(interp));
4816
0
    Py_CLEAR(LAZY_IMPORT_FUNC(interp));
4817
0
    Py_CLEAR(interp->imports.lazy_pending_submodules);
4818
0
    Py_CLEAR(interp->imports.lazy_modules);
4819
0
    Py_CLEAR(interp->imports.lazy_importing_modules);
4820
0
    Py_CLEAR(interp->imports.lazy_imports_filter);
4821
0
}
4822
4823
void
4824
_PyImport_FiniCore(PyInterpreterState *interp)
4825
0
{
4826
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4827
4828
0
    if (_PySys_ClearAttrString(interp, "meta_path", verbose) < 0) {
4829
0
        PyErr_FormatUnraisable("Exception ignored while "
4830
0
                               "clearing sys.meta_path");
4831
0
    }
4832
4833
    // XXX Pull in most of finalize_modules() in pylifecycle.c.
4834
4835
0
    if (_PySys_ClearAttrString(interp, "modules", verbose) < 0) {
4836
0
        PyErr_FormatUnraisable("Exception ignored while "
4837
0
                               "clearing sys.modules");
4838
0
    }
4839
4840
0
    _PyImport_ClearCore(interp);
4841
0
}
4842
4843
// XXX Add something like _PyImport_Disable() for use early in interp fini?
4844
4845
4846
/* "external" imports */
4847
4848
static int
4849
init_zipimport(PyThreadState *tstate, int verbose)
4850
36
{
4851
36
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
4852
36
    if (path_hooks == NULL) {
4853
0
        return -1;
4854
0
    }
4855
4856
36
    if (verbose) {
4857
0
        PySys_WriteStderr("# installing zipimport hook\n");
4858
0
    }
4859
4860
36
    PyObject *zipimporter = PyImport_ImportModuleAttrString("zipimport", "zipimporter");
4861
36
    if (zipimporter == NULL) {
4862
0
        _PyErr_Clear(tstate); /* No zipimporter object -- okay */
4863
0
        if (verbose) {
4864
0
            PySys_WriteStderr("# can't import zipimport.zipimporter\n");
4865
0
        }
4866
0
    }
4867
36
    else {
4868
        /* sys.path_hooks.insert(0, zipimporter) */
4869
36
        int err = PyList_Insert(path_hooks, 0, zipimporter);
4870
36
        Py_DECREF(zipimporter);
4871
36
        if (err < 0) {
4872
0
            Py_DECREF(path_hooks);
4873
0
            return -1;
4874
0
        }
4875
36
        if (verbose) {
4876
0
            PySys_WriteStderr("# installed zipimport hook\n");
4877
0
        }
4878
36
    }
4879
36
    Py_DECREF(path_hooks);
4880
4881
36
    return 0;
4882
36
}
4883
4884
PyStatus
4885
_PyImport_InitExternal(PyThreadState *tstate)
4886
36
{
4887
36
    int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
4888
4889
    // XXX Initialize here: sys.path_hooks and sys.path_importer_cache.
4890
4891
36
    if (init_importlib_external(tstate->interp) != 0) {
4892
0
        _PyErr_Print(tstate);
4893
0
        return _PyStatus_ERR("external importer setup failed");
4894
0
    }
4895
4896
36
    if (init_zipimport(tstate, verbose) != 0) {
4897
0
        PyErr_Print();
4898
0
        return _PyStatus_ERR("initializing zipimport failed");
4899
0
    }
4900
4901
36
    return _PyStatus_OK();
4902
36
}
4903
4904
void
4905
_PyImport_FiniExternal(PyInterpreterState *interp)
4906
0
{
4907
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4908
4909
    // XXX Uninstall importlib metapath importers here?
4910
4911
0
    if (_PySys_ClearAttrString(interp, "path_importer_cache", verbose) < 0) {
4912
0
        PyErr_FormatUnraisable("Exception ignored while "
4913
0
                               "clearing sys.path_importer_cache");
4914
0
    }
4915
0
    if (_PySys_ClearAttrString(interp, "path_hooks", verbose) < 0) {
4916
0
        PyErr_FormatUnraisable("Exception ignored while "
4917
0
                               "clearing sys.path_hooks");
4918
0
    }
4919
0
}
4920
4921
4922
/******************/
4923
/* module helpers */
4924
/******************/
4925
4926
PyObject *
4927
PyImport_ImportModuleAttr(PyObject *modname, PyObject *attrname)
4928
24.3k
{
4929
24.3k
    PyObject *mod = PyImport_Import(modname);
4930
24.3k
    if (mod == NULL) {
4931
0
        return NULL;
4932
0
    }
4933
24.3k
    PyObject *result = PyObject_GetAttr(mod, attrname);
4934
24.3k
    Py_DECREF(mod);
4935
24.3k
    return result;
4936
24.3k
}
4937
4938
PyObject *
4939
PyImport_ImportModuleAttrString(const char *modname, const char *attrname)
4940
21.9k
{
4941
21.9k
    PyObject *pmodname = PyUnicode_FromString(modname);
4942
21.9k
    if (pmodname == NULL) {
4943
0
        return NULL;
4944
0
    }
4945
21.9k
    PyObject *pattrname = PyUnicode_FromString(attrname);
4946
21.9k
    if (pattrname == NULL) {
4947
0
        Py_DECREF(pmodname);
4948
0
        return NULL;
4949
0
    }
4950
21.9k
    PyObject *result = PyImport_ImportModuleAttr(pmodname, pattrname);
4951
21.9k
    Py_DECREF(pattrname);
4952
21.9k
    Py_DECREF(pmodname);
4953
21.9k
    return result;
4954
21.9k
}
4955
4956
int
4957
PyImport_SetLazyImportsFilter(PyObject *filter)
4958
0
{
4959
0
    if (filter == Py_None) {
4960
0
        filter = NULL;
4961
0
    }
4962
0
    if (filter != NULL && !PyCallable_Check(filter)) {
4963
0
        PyErr_SetString(PyExc_ValueError,
4964
0
                        "filter provided but is not callable");
4965
0
        return -1;
4966
0
    }
4967
4968
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4969
    // Exchange the filter w/ the lock held. We can't use Py_XSETREF
4970
    // because we need to release the lock before the decref.
4971
0
    LAZY_IMPORTS_LOCK(interp);
4972
0
    PyObject *old = LAZY_IMPORTS_FILTER(interp);
4973
0
    LAZY_IMPORTS_FILTER(interp) = Py_XNewRef(filter);
4974
0
    LAZY_IMPORTS_UNLOCK(interp);
4975
0
    Py_XDECREF(old);
4976
0
    return 0;
4977
0
}
4978
4979
/* Return a strong reference to the current lazy imports filter
4980
 * or NULL if none exists. This function always succeeds.
4981
 */
4982
PyObject *
4983
PyImport_GetLazyImportsFilter(void)
4984
0
{
4985
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4986
0
    LAZY_IMPORTS_LOCK(interp);
4987
0
    PyObject *res = Py_XNewRef(LAZY_IMPORTS_FILTER(interp));
4988
0
    LAZY_IMPORTS_UNLOCK(interp);
4989
0
    return res;
4990
0
}
4991
4992
int
4993
PyImport_SetLazyImportsMode(PyImport_LazyImportsMode mode)
4994
0
{
4995
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4996
0
    FT_ATOMIC_STORE_INT_RELAXED(LAZY_IMPORTS_MODE(interp), mode);
4997
0
    return 0;
4998
0
}
4999
5000
/* Checks if lazy imports is globally enabled or disabled. Return 1 when
5001
 * globally forced on, 0 when globally forced off, or -1 when not set.*/
5002
PyImport_LazyImportsMode
5003
PyImport_GetLazyImportsMode(void)
5004
15.4k
{
5005
15.4k
    PyInterpreterState *interp = _PyInterpreterState_GET();
5006
15.4k
    return FT_ATOMIC_LOAD_INT_RELAXED(LAZY_IMPORTS_MODE(interp));
5007
15.4k
}
5008
5009
/**************/
5010
/* the module */
5011
/**************/
5012
5013
/*[clinic input]
5014
_imp.lock_held
5015
5016
Return True if the import lock is currently held, else False.
5017
5018
On platforms without threads, return False.
5019
[clinic start generated code]*/
5020
5021
static PyObject *
5022
_imp_lock_held_impl(PyObject *module)
5023
/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
5024
0
{
5025
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
5026
0
    return PyBool_FromLong(PyMutex_IsLocked(&IMPORT_LOCK(interp).mutex));
5027
0
}
5028
5029
/*[clinic input]
5030
_imp.acquire_lock
5031
5032
Acquires the interpreter's import lock for the current thread.
5033
5034
This lock should be used by import hooks to ensure thread-safety when
5035
importing modules.  On platforms without threads, this function does
5036
nothing.
5037
[clinic start generated code]*/
5038
5039
static PyObject *
5040
_imp_acquire_lock_impl(PyObject *module)
5041
/*[clinic end generated code: output=1aff58cb0ee1b026 input=60e9c1b4ab471ead]*/
5042
72.0k
{
5043
72.0k
    PyInterpreterState *interp = _PyInterpreterState_GET();
5044
72.0k
    _PyImport_AcquireLock(interp);
5045
72.0k
    Py_RETURN_NONE;
5046
72.0k
}
5047
5048
/*[clinic input]
5049
_imp.release_lock
5050
5051
Release the interpreter's import lock.
5052
5053
On platforms without threads, this function does nothing.
5054
[clinic start generated code]*/
5055
5056
static PyObject *
5057
_imp_release_lock_impl(PyObject *module)
5058
/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
5059
72.0k
{
5060
72.0k
    PyInterpreterState *interp = _PyInterpreterState_GET();
5061
72.0k
    if (!_PyRecursiveMutex_IsLockedByCurrentThread(&IMPORT_LOCK(interp))) {
5062
0
        PyErr_SetString(PyExc_RuntimeError,
5063
0
                        "not holding the import lock");
5064
0
        return NULL;
5065
0
    }
5066
72.0k
    _PyImport_ReleaseLock(interp);
5067
72.0k
    Py_RETURN_NONE;
5068
72.0k
}
5069
5070
5071
/*[clinic input]
5072
_imp._fix_co_filename
5073
5074
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
5075
        Code object to change.
5076
5077
    path: unicode
5078
        File path to use.
5079
    /
5080
5081
Changes code.co_filename to specify the passed-in file path.
5082
[clinic start generated code]*/
5083
5084
static PyObject *
5085
_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
5086
                           PyObject *path)
5087
/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
5088
5089
6.57k
{
5090
6.57k
    update_compiled_module(code, path);
5091
5092
6.57k
    Py_RETURN_NONE;
5093
6.57k
}
5094
5095
5096
/*[clinic input]
5097
_imp.create_builtin
5098
5099
    spec: object
5100
    /
5101
5102
Create an extension module.
5103
[clinic start generated code]*/
5104
5105
static PyObject *
5106
_imp_create_builtin(PyObject *module, PyObject *spec)
5107
/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
5108
698
{
5109
698
    PyThreadState *tstate = _PyThreadState_GET();
5110
5111
698
    PyObject *name = PyObject_GetAttrString(spec, "name");
5112
698
    if (name == NULL) {
5113
0
        return NULL;
5114
0
    }
5115
5116
698
    if (!PyUnicode_Check(name)) {
5117
0
        PyErr_Format(PyExc_TypeError,
5118
0
                     "name must be string, not %.200s",
5119
0
                     Py_TYPE(name)->tp_name);
5120
0
        Py_DECREF(name);
5121
0
        return NULL;
5122
0
    }
5123
5124
698
    if (PyUnicode_GetLength(name) == 0) {
5125
0
        PyErr_Format(PyExc_ValueError, "name must not be empty");
5126
0
        Py_DECREF(name);
5127
0
        return NULL;
5128
0
    }
5129
5130
698
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
5131
698
    Py_DECREF(name);
5132
698
    return mod;
5133
698
}
5134
5135
5136
/*[clinic input]
5137
_imp.extension_suffixes
5138
5139
Returns the list of file suffixes used to identify extension modules.
5140
[clinic start generated code]*/
5141
5142
static PyObject *
5143
_imp_extension_suffixes_impl(PyObject *module)
5144
/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
5145
72
{
5146
72
    PyObject *list;
5147
5148
72
    list = PyList_New(0);
5149
72
    if (list == NULL)
5150
0
        return NULL;
5151
72
#ifdef HAVE_DYNAMIC_LOADING
5152
72
    const char *suffix;
5153
72
    unsigned int index = 0;
5154
5155
360
    while ((suffix = _PyImport_DynLoadFiletab[index])) {
5156
288
        PyObject *item = PyUnicode_FromString(suffix);
5157
288
        if (item == NULL) {
5158
0
            Py_DECREF(list);
5159
0
            return NULL;
5160
0
        }
5161
288
        if (PyList_Append(list, item) < 0) {
5162
0
            Py_DECREF(list);
5163
0
            Py_DECREF(item);
5164
0
            return NULL;
5165
0
        }
5166
288
        Py_DECREF(item);
5167
288
        index += 1;
5168
288
    }
5169
72
#endif
5170
72
    return list;
5171
72
}
5172
5173
/*[clinic input]
5174
_imp.init_frozen
5175
5176
    name: unicode
5177
    /
5178
5179
Initializes a frozen module.
5180
[clinic start generated code]*/
5181
5182
static PyObject *
5183
_imp_init_frozen_impl(PyObject *module, PyObject *name)
5184
/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
5185
0
{
5186
0
    PyThreadState *tstate = _PyThreadState_GET();
5187
0
    int ret;
5188
5189
0
    ret = PyImport_ImportFrozenModuleObject(name);
5190
0
    if (ret < 0)
5191
0
        return NULL;
5192
0
    if (ret == 0) {
5193
0
        Py_RETURN_NONE;
5194
0
    }
5195
0
    return import_add_module(tstate, name);
5196
0
}
5197
5198
/*[clinic input]
5199
@permit_long_summary
5200
_imp.find_frozen
5201
5202
    name: unicode
5203
    /
5204
    *
5205
    withdata: bool = False
5206
5207
Return info about the corresponding frozen module (if there is one) or None.
5208
5209
The returned info (a 2-tuple):
5210
5211
 * data         the raw marshalled bytes
5212
 * is_package   whether or not it is a package
5213
 * origname     the originally frozen module's name, or None if not
5214
                a stdlib module (this will usually be the same as
5215
                the module's current name)
5216
[clinic start generated code]*/
5217
5218
static PyObject *
5219
_imp_find_frozen_impl(PyObject *module, PyObject *name, int withdata)
5220
/*[clinic end generated code: output=8c1c3c7f925397a5 input=30a7a50da49eca97]*/
5221
13.8k
{
5222
13.8k
    struct frozen_info info;
5223
13.8k
    frozen_status status = find_frozen(name, &info);
5224
13.8k
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
5225
13.2k
        Py_RETURN_NONE;
5226
13.2k
    }
5227
557
    else if (status == FROZEN_BAD_NAME) {
5228
0
        Py_RETURN_NONE;
5229
0
    }
5230
557
    else if (status != FROZEN_OKAY) {
5231
0
        set_frozen_error(status, name);
5232
0
        return NULL;
5233
0
    }
5234
5235
557
    PyObject *data = NULL;
5236
557
    if (withdata) {
5237
0
        data = PyMemoryView_FromMemory((char *)info.data, info.size, PyBUF_READ);
5238
0
        if (data == NULL) {
5239
0
            return NULL;
5240
0
        }
5241
0
    }
5242
5243
557
    PyObject *origname = NULL;
5244
557
    if (info.origname != NULL && info.origname[0] != '\0') {
5245
557
        origname = PyUnicode_FromString(info.origname);
5246
557
        if (origname == NULL) {
5247
0
            Py_XDECREF(data);
5248
0
            return NULL;
5249
0
        }
5250
557
    }
5251
5252
557
    PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
5253
557
                                    info.is_package ? Py_True : Py_False,
5254
557
                                    origname ? origname : Py_None);
5255
557
    Py_XDECREF(origname);
5256
557
    Py_XDECREF(data);
5257
557
    return result;
5258
557
}
5259
5260
/*[clinic input]
5261
_imp.get_frozen_object
5262
5263
    name: unicode
5264
    data as dataobj: object = None
5265
    /
5266
5267
Create a code object for a frozen module.
5268
[clinic start generated code]*/
5269
5270
static PyObject *
5271
_imp_get_frozen_object_impl(PyObject *module, PyObject *name,
5272
                            PyObject *dataobj)
5273
/*[clinic end generated code: output=54368a673a35e745 input=034bdb88f6460b7b]*/
5274
557
{
5275
557
    struct frozen_info info = {0};
5276
557
    Py_buffer buf = {0};
5277
557
    if (PyObject_CheckBuffer(dataobj)) {
5278
0
        if (PyObject_GetBuffer(dataobj, &buf, PyBUF_SIMPLE) != 0) {
5279
0
            return NULL;
5280
0
        }
5281
0
        info.data = (const char *)buf.buf;
5282
0
        info.size = buf.len;
5283
0
    }
5284
557
    else if (dataobj != Py_None) {
5285
0
        _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
5286
0
        return NULL;
5287
0
    }
5288
557
    else {
5289
557
        frozen_status status = find_frozen(name, &info);
5290
557
        if (status != FROZEN_OKAY) {
5291
0
            set_frozen_error(status, name);
5292
0
            return NULL;
5293
0
        }
5294
557
    }
5295
5296
557
    if (info.nameobj == NULL) {
5297
0
        info.nameobj = name;
5298
0
    }
5299
557
    if (info.size == 0) {
5300
        /* Does not contain executable code. */
5301
0
        set_frozen_error(FROZEN_INVALID, name);
5302
0
        return NULL;
5303
0
    }
5304
5305
557
    PyInterpreterState *interp = _PyInterpreterState_GET();
5306
557
    PyObject *codeobj = unmarshal_frozen_code(interp, &info);
5307
557
    if (dataobj != Py_None) {
5308
0
        PyBuffer_Release(&buf);
5309
0
    }
5310
557
    return codeobj;
5311
557
}
5312
5313
/*[clinic input]
5314
_imp.is_frozen_package
5315
5316
    name: unicode
5317
    /
5318
5319
Returns True if the module name is of a frozen package.
5320
[clinic start generated code]*/
5321
5322
static PyObject *
5323
_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
5324
/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
5325
36
{
5326
36
    struct frozen_info info;
5327
36
    frozen_status status = find_frozen(name, &info);
5328
36
    if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
5329
0
        set_frozen_error(status, name);
5330
0
        return NULL;
5331
0
    }
5332
36
    return PyBool_FromLong(info.is_package);
5333
36
}
5334
5335
/*[clinic input]
5336
_imp.is_builtin
5337
5338
    name: unicode
5339
    /
5340
5341
Returns True if the module name corresponds to a built-in module.
5342
[clinic start generated code]*/
5343
5344
static PyObject *
5345
_imp_is_builtin_impl(PyObject *module, PyObject *name)
5346
/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
5347
14.5k
{
5348
14.5k
    return PyLong_FromLong(is_builtin(name));
5349
14.5k
}
5350
5351
/*[clinic input]
5352
_imp.is_frozen
5353
5354
    name: unicode
5355
    /
5356
5357
Returns True if the module name corresponds to a frozen module.
5358
[clinic start generated code]*/
5359
5360
static PyObject *
5361
_imp_is_frozen_impl(PyObject *module, PyObject *name)
5362
/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
5363
36
{
5364
36
    struct frozen_info info;
5365
36
    frozen_status status = find_frozen(name, &info);
5366
36
    if (status != FROZEN_OKAY) {
5367
0
        Py_RETURN_FALSE;
5368
0
    }
5369
36
    Py_RETURN_TRUE;
5370
36
}
5371
5372
/*[clinic input]
5373
_imp._frozen_module_names
5374
5375
Returns the list of available frozen modules.
5376
[clinic start generated code]*/
5377
5378
static PyObject *
5379
_imp__frozen_module_names_impl(PyObject *module)
5380
/*[clinic end generated code: output=80609ef6256310a8 input=76237fbfa94460d2]*/
5381
0
{
5382
0
    return list_frozen_module_names();
5383
0
}
5384
5385
/*[clinic input]
5386
_imp._override_frozen_modules_for_tests
5387
5388
    override: int
5389
    /
5390
5391
(internal-only) Override PyConfig.use_frozen_modules.
5392
5393
(-1: "off", 1: "on", 0: no override)
5394
See frozen_modules() in Lib/test/support/import_helper.py.
5395
[clinic start generated code]*/
5396
5397
static PyObject *
5398
_imp__override_frozen_modules_for_tests_impl(PyObject *module, int override)
5399
/*[clinic end generated code: output=36d5cb1594160811 input=8f1f95a3ef21aec3]*/
5400
0
{
5401
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
5402
0
    OVERRIDE_FROZEN_MODULES(interp) = override;
5403
0
    Py_RETURN_NONE;
5404
0
}
5405
5406
/*[clinic input]
5407
@permit_long_summary
5408
_imp._override_multi_interp_extensions_check
5409
5410
    override: int
5411
    /
5412
5413
(internal-only) Override PyInterpreterConfig.check_multi_interp_extensions.
5414
5415
(-1: "never", 1: "always", 0: no override)
5416
[clinic start generated code]*/
5417
5418
static PyObject *
5419
_imp__override_multi_interp_extensions_check_impl(PyObject *module,
5420
                                                  int override)
5421
/*[clinic end generated code: output=3ff043af52bbf280 input=24f23f8510a7f6e7]*/
5422
0
{
5423
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
5424
0
    if (_Py_IsMainInterpreter(interp)) {
5425
0
        PyErr_SetString(PyExc_RuntimeError,
5426
0
                        "_imp._override_multi_interp_extensions_check() "
5427
0
                        "cannot be used in the main interpreter");
5428
0
        return NULL;
5429
0
    }
5430
#ifdef Py_GIL_DISABLED
5431
    PyErr_SetString(PyExc_RuntimeError,
5432
                    "_imp._override_multi_interp_extensions_check() "
5433
                    "cannot be used in the free-threaded build");
5434
    return NULL;
5435
#else
5436
0
    int oldvalue = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
5437
0
    OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) = override;
5438
0
    return PyLong_FromLong(oldvalue);
5439
0
#endif
5440
0
}
5441
5442
#ifdef HAVE_DYNAMIC_LOADING
5443
5444
/*[clinic input]
5445
_imp.create_dynamic
5446
5447
    spec: object
5448
    file: object = NULL
5449
    /
5450
5451
Create an extension module.
5452
[clinic start generated code]*/
5453
5454
static PyObject *
5455
_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
5456
/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
5457
205
{
5458
205
    FILE *fp = NULL;
5459
205
    PyObject *mod = NULL;
5460
205
    PyThreadState *tstate = _PyThreadState_GET();
5461
5462
205
    struct _Py_ext_module_loader_info info;
5463
205
    if (_Py_ext_module_loader_info_init_from_spec(&info, spec) < 0) {
5464
0
        return NULL;
5465
0
    }
5466
5467
205
    struct extensions_cache_value *cached = NULL;
5468
205
    mod = import_find_extension(tstate, &info, &cached);
5469
205
    if (mod != NULL) {
5470
0
        assert(!_PyErr_Occurred(tstate));
5471
0
        assert(cached != NULL);
5472
        /* The module might not have md_def set in certain reload cases. */
5473
0
        assert(_PyModule_GetDefOrNull(mod) == NULL
5474
0
                || cached->def == _PyModule_GetDefOrNull(mod));
5475
0
        assert_singlephase(cached);
5476
0
        goto finally;
5477
0
    }
5478
205
    else if (_PyErr_Occurred(tstate)) {
5479
0
        goto finally;
5480
0
    }
5481
    /* Otherwise it must be multi-phase init or the first time it's loaded. */
5482
5483
    /* If the module was added to the global cache
5484
     * but def->m_base.m_copy was cleared (e.g. subinterp fini)
5485
     * then we have to do a little dance here. */
5486
205
    if (cached != NULL) {
5487
0
        assert(cached->def->m_base.m_copy == NULL);
5488
        /* For now we clear the cache and move on. */
5489
0
        _extensions_cache_delete(info.path, info.name);
5490
0
    }
5491
5492
205
    if (PySys_Audit("import", "OOOOO", info.name, info.filename,
5493
205
                    Py_None, Py_None, Py_None) < 0)
5494
0
    {
5495
0
        goto finally;
5496
0
    }
5497
5498
    /* We would move this (and the fclose() below) into
5499
     * _PyImport_GetModuleExportHooks(), but it isn't clear if the intervening
5500
     * code relies on fp still being open. */
5501
205
    if (file != NULL) {
5502
0
        fp = Py_fopen(info.filename, "r");
5503
0
        if (fp == NULL) {
5504
0
            goto finally;
5505
0
        }
5506
0
    }
5507
5508
205
    PyModInitFunction p0 = NULL;
5509
205
    PyModExportFunction ex0 = NULL;
5510
205
    _PyImport_GetModuleExportHooks(&info, fp, &p0, &ex0);
5511
205
    if (ex0) {
5512
0
        mod = import_run_modexport(tstate, ex0, &info, spec);
5513
        // Modules created from slots handle GIL enablement (Py_mod_gil slot)
5514
        // when they're created.
5515
0
        goto finally;
5516
0
    }
5517
205
    if (p0 == NULL) {
5518
0
        goto finally;
5519
0
    }
5520
5521
#ifdef Py_GIL_DISABLED
5522
    // This call (and the corresponding call to _PyImport_CheckGILForModule())
5523
    // would ideally be inside import_run_extension(). They are kept in the
5524
    // callers for now because that would complicate the control flow inside
5525
    // import_run_extension(). It should be possible to restructure
5526
    // import_run_extension() to address this.
5527
    _PyEval_EnableGILTransient(tstate);
5528
#endif
5529
205
    mod = import_run_extension(
5530
205
                    tstate, p0, &info, spec, get_modules_dict(tstate, true));
5531
#ifdef Py_GIL_DISABLED
5532
    if (_PyImport_CheckGILForModule(mod, info.name) < 0) {
5533
        Py_CLEAR(mod);
5534
        goto finally;
5535
    }
5536
#endif
5537
5538
205
finally:
5539
205
    if (fp != NULL) {
5540
0
        fclose(fp);
5541
0
    }
5542
205
    _Py_ext_module_loader_info_clear(&info);
5543
205
    return mod;
5544
205
}
5545
5546
/*[clinic input]
5547
_imp.exec_dynamic -> int
5548
5549
    mod: object
5550
    /
5551
5552
Initialize an extension module.
5553
[clinic start generated code]*/
5554
5555
static int
5556
_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
5557
/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
5558
205
{
5559
205
    return exec_builtin_or_dynamic(mod);
5560
205
}
5561
5562
5563
#endif /* HAVE_DYNAMIC_LOADING */
5564
5565
/*[clinic input]
5566
_imp.exec_builtin -> int
5567
5568
    mod: object
5569
    /
5570
5571
Initialize a built-in module.
5572
[clinic start generated code]*/
5573
5574
static int
5575
_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
5576
/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
5577
698
{
5578
698
    return exec_builtin_or_dynamic(mod);
5579
698
}
5580
5581
/*[clinic input]
5582
_imp.source_hash
5583
5584
    key: long
5585
    source: Py_buffer
5586
[clinic start generated code]*/
5587
5588
static PyObject *
5589
_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
5590
/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
5591
0
{
5592
0
    union {
5593
0
        uint64_t x;
5594
0
        char data[sizeof(uint64_t)];
5595
0
    } hash;
5596
0
    hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
5597
#if !PY_LITTLE_ENDIAN
5598
    // Force to little-endian. There really ought to be a succinct standard way
5599
    // to do this.
5600
    for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
5601
        char tmp = hash.data[i];
5602
        hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
5603
        hash.data[sizeof(hash.data) - i - 1] = tmp;
5604
    }
5605
#endif
5606
0
    return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
5607
0
}
5608
5609
/*[clinic input]
5610
_imp._set_lazy_attributes
5611
    modobj: object
5612
    name: unicode
5613
    /
5614
Sets attributes to lazy submodules on the module, as side effects.
5615
[clinic start generated code]*/
5616
5617
static PyObject *
5618
_imp__set_lazy_attributes_impl(PyObject *module, PyObject *modobj,
5619
                               PyObject *name)
5620
/*[clinic end generated code: output=3369bb3242b1f043 input=38ea6f30956dd7d6]*/
5621
3.18k
{
5622
3.18k
    PyInterpreterState *interp = _PyInterpreterState_GET();
5623
3.18k
    if (PySet_Discard(LAZY_MODULES(interp), name) < 0) {
5624
0
        return NULL;
5625
0
    }
5626
3.18k
    Py_RETURN_NONE;
5627
3.18k
}
5628
5629
PyDoc_STRVAR(doc_imp,
5630
"(Extremely) low-level import machinery bits as used by importlib.");
5631
5632
static PyMethodDef imp_methods[] = {
5633
    _IMP_EXTENSION_SUFFIXES_METHODDEF
5634
    _IMP_LOCK_HELD_METHODDEF
5635
    _IMP_ACQUIRE_LOCK_METHODDEF
5636
    _IMP_RELEASE_LOCK_METHODDEF
5637
    _IMP_FIND_FROZEN_METHODDEF
5638
    _IMP_GET_FROZEN_OBJECT_METHODDEF
5639
    _IMP_IS_FROZEN_PACKAGE_METHODDEF
5640
    _IMP_CREATE_BUILTIN_METHODDEF
5641
    _IMP_INIT_FROZEN_METHODDEF
5642
    _IMP_IS_BUILTIN_METHODDEF
5643
    _IMP_IS_FROZEN_METHODDEF
5644
    _IMP__FROZEN_MODULE_NAMES_METHODDEF
5645
    _IMP__OVERRIDE_FROZEN_MODULES_FOR_TESTS_METHODDEF
5646
    _IMP__OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK_METHODDEF
5647
    _IMP_CREATE_DYNAMIC_METHODDEF
5648
    _IMP_EXEC_DYNAMIC_METHODDEF
5649
    _IMP_EXEC_BUILTIN_METHODDEF
5650
    _IMP__FIX_CO_FILENAME_METHODDEF
5651
    _IMP_SOURCE_HASH_METHODDEF
5652
    _IMP__SET_LAZY_ATTRIBUTES_METHODDEF
5653
    {NULL, NULL}  /* sentinel */
5654
};
5655
5656
5657
static int
5658
imp_module_exec(PyObject *module)
5659
36
{
5660
36
    const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
5661
36
    PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
5662
36
    if (PyModule_Add(module, "check_hash_based_pycs", pyc_mode) < 0) {
5663
0
        return -1;
5664
0
    }
5665
5666
36
    if (PyModule_AddIntConstant(
5667
36
            module, "pyc_magic_number_token", PYC_MAGIC_NUMBER_TOKEN) < 0)
5668
0
    {
5669
0
        return -1;
5670
0
    }
5671
5672
36
    return 0;
5673
36
}
5674
5675
5676
static PyModuleDef_Slot imp_slots[] = {
5677
     _Py_ABI_SLOT,
5678
    {Py_mod_exec, imp_module_exec},
5679
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
5680
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
5681
    {0, NULL}
5682
};
5683
5684
static struct PyModuleDef imp_module = {
5685
    PyModuleDef_HEAD_INIT,
5686
    .m_name = "_imp",
5687
    .m_doc = doc_imp,
5688
    .m_size = 0,
5689
    .m_methods = imp_methods,
5690
    .m_slots = imp_slots,
5691
};
5692
5693
PyMODINIT_FUNC
5694
PyInit__imp(void)
5695
36
{
5696
36
    return PyModuleDef_Init(&imp_module);
5697
36
}