Coverage Report

Created: 2026-06-09 06:53

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