Coverage Report

Created: 2026-05-30 06:18

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.5k
#define INITTAB _PyRuntime.imports.inittab
81
1.11k
#define LAST_MODULE_INDEX _PyRuntime.imports.last_module_index
82
2.42k
#define EXTENSIONS _PyRuntime.imports.extensions
83
84
#define PKGCONTEXT (_PyRuntime.imports.pkgcontext)
85
86
87
/*******************************/
88
/* interpreter import state */
89
/*******************************/
90
91
#define MODULES(interp) \
92
10.5M
    (interp)->imports.modules
93
#define MODULES_BY_INDEX(interp) \
94
407
    (interp)->imports.modules_by_index
95
#define LAZY_MODULES(interp) \
96
3.88k
    (interp)->imports.lazy_modules
97
#define LAZY_PENDING_SUBMODULES(interp) \
98
3.75k
    (interp)->imports.lazy_pending_submodules
99
#define IMPORTLIB(interp) \
100
23.3k
    (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.3k
    (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.68M
    (interp)->imports.import_func
111
112
#define LAZY_IMPORT_FUNC(interp) \
113
345
    (interp)->imports.lazy_import_func
114
115
#define IMPORT_LOCK(interp) \
116
205k
    (interp)->imports.lock
117
118
#define FIND_AND_LOAD(interp) \
119
13.5k
    (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
68.4k
{
157
68.4k
    _PyRecursiveMutex_Lock(&IMPORT_LOCK(interp));
158
68.4k
}
159
160
void
161
_PyImport_ReleaseLock(PyInterpreterState *interp)
162
68.4k
{
163
68.4k
    _PyRecursiveMutex_Unlock(&IMPORT_LOCK(interp));
164
68.4k
}
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
37
{
181
37
    assert(MODULES(interp) == NULL);
182
37
    MODULES(interp) = PyDict_New();
183
37
    if (MODULES(interp) == NULL) {
184
0
        return NULL;
185
0
    }
186
37
    return MODULES(interp);
187
37
}
188
189
PyObject *
190
_PyImport_GetModules(PyInterpreterState *interp)
191
796k
{
192
796k
    return MODULES(interp);
193
796k
}
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.78M
{
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.78M
    PyObject *modules = MODULES(tstate->interp);
224
9.78M
    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.78M
    return modules;
233
9.78M
}
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
49
{
253
49
    PyThreadState *tstate = _PyThreadState_GET();
254
49
    PyObject *modules = get_modules_dict(tstate, true);
255
49
    return PyMapping_SetItemString(modules, name, m);
256
49
}
257
258
static PyObject *
259
import_get_module(PyThreadState *tstate, PyObject *name)
260
9.78M
{
261
9.78M
    PyObject *modules = get_modules_dict(tstate, false);
262
9.78M
    if (modules == NULL) {
263
0
        return NULL;
264
0
    }
265
266
9.78M
    PyObject *m;
267
9.78M
    Py_INCREF(modules);
268
9.78M
    (void)PyMapping_GetOptionalItem(modules, name, &m);
269
9.78M
    Py_DECREF(modules);
270
9.78M
    return m;
271
9.78M
}
272
273
PyObject *
274
_PyImport_InitLazyModules(PyInterpreterState *interp)
275
37
{
276
37
    assert(LAZY_MODULES(interp) == NULL &&
277
37
           LAZY_PENDING_SUBMODULES(interp) == NULL);
278
279
37
    LAZY_PENDING_SUBMODULES(interp) = PyDict_New();
280
37
    LAZY_MODULES(interp) = PySet_New(0);
281
37
    return LAZY_MODULES(interp);
282
37
}
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.74M
{
294
4.74M
    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.74M
    int rc = PyObject_GetOptionalAttr(mod, &_Py_ID(__spec__), &spec);
302
4.74M
    if (rc > 0) {
303
4.74M
        rc = _PyModuleSpec_IsInitializing(spec);
304
4.74M
        Py_DECREF(spec);
305
4.74M
    }
306
4.74M
    if (rc == 0) {
307
4.73M
        goto done;
308
4.73M
    }
309
1.59k
    else if (rc < 0) {
310
0
        return rc;
311
0
    }
312
313
    /* Wait until module is done importing. */
314
1.59k
    PyObject *value = PyObject_CallMethodOneArg(
315
1.59k
        IMPORTLIB(interp), &_Py_ID(_lock_unlock_module), name);
316
1.59k
    if (value == NULL) {
317
0
        return -1;
318
0
    }
319
1.59k
    Py_DECREF(value);
320
321
4.74M
done:
322
    /* When -X importtime=2, print an import time entry even if an
323
       imported module has already been loaded.
324
     */
325
4.74M
    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.74M
    return 0;
334
1.59k
}
335
336
static void remove_importlib_frames(PyThreadState *tstate);
337
338
PyObject *
339
PyImport_GetModule(PyObject *name)
340
804k
{
341
804k
    PyThreadState *tstate = _PyThreadState_GET();
342
804k
    PyObject *mod;
343
344
804k
    mod = import_get_module(tstate, name);
345
804k
    if (mod != NULL && mod != Py_None) {
346
804k
        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
804k
        PyObject *mod_check = import_get_module(tstate, name);
353
804k
        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
804k
        Py_DECREF(mod_check);
366
804k
    }
367
804k
    return mod;
368
369
0
error:
370
0
    Py_DECREF(mod);
371
0
    remove_importlib_frames(tstate);
372
0
    return NULL;
373
804k
}
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
185
{
382
185
    PyObject *m;
383
185
    if (PyMapping_GetOptionalItem(modules, name, &m) < 0) {
384
0
        return NULL;
385
0
    }
386
185
    if (m != NULL && PyModule_Check(m)) {
387
111
        return m;
388
111
    }
389
74
    Py_XDECREF(m);
390
74
    m = PyModule_NewObject(name);
391
74
    if (m == NULL)
392
0
        return NULL;
393
74
    if (PyObject_SetItem(modules, name, m) != 0) {
394
0
        Py_DECREF(m);
395
0
        return NULL;
396
0
    }
397
398
74
    return m;
399
74
}
400
401
static PyObject *
402
import_add_module(PyThreadState *tstate, PyObject *name)
403
185
{
404
185
    PyObject *modules = get_modules_dict(tstate, false);
405
185
    if (modules == NULL) {
406
0
        return NULL;
407
0
    }
408
409
185
    PyObject *m;
410
185
    Py_BEGIN_CRITICAL_SECTION(modules);
411
185
    m = import_add_module_lock_held(modules, name);
412
185
    Py_END_CRITICAL_SECTION();
413
185
    return m;
414
185
}
415
416
PyObject *
417
PyImport_AddModuleRef(const char *name)
418
111
{
419
111
    PyObject *name_obj = PyUnicode_FromString(name);
420
111
    if (name_obj == NULL) {
421
0
        return NULL;
422
0
    }
423
111
    PyThreadState *tstate = _PyThreadState_GET();
424
111
    PyObject *module = import_add_module(tstate, name_obj);
425
111
    Py_DECREF(name_obj);
426
111
    return module;
427
111
}
428
429
430
PyObject *
431
PyImport_AddModuleObject(PyObject *name)
432
37
{
433
37
    PyThreadState *tstate = _PyThreadState_GET();
434
37
    PyObject *mod = import_add_module(tstate, name);
435
37
    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
37
    PyObject *ref = PyWeakref_NewRef(mod, NULL);
450
37
    Py_DECREF(mod);
451
37
    if (ref == NULL) {
452
0
        return NULL;
453
0
    }
454
37
    mod = _PyWeakref_GET_REF(ref);
455
37
    Py_DECREF(ref);
456
37
    Py_XDECREF(mod);
457
458
37
    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
37
    return mod; /* borrowed reference */
464
37
}
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.11k
{
512
1.11k
    return _Py_atomic_add_ssize(&LAST_MODULE_INDEX, 1) + 1;
513
1.11k
}
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
74
{
535
74
    assert(index > 0);
536
74
    if (index == def->m_base.m_index) {
537
        /* There's nothing to do. */
538
74
    }
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
74
}
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
74
{
582
74
    assert(index > 0);
583
584
74
    if (MODULES_BY_INDEX(interp) == NULL) {
585
37
        MODULES_BY_INDEX(interp) = PyList_New(0);
586
37
        if (MODULES_BY_INDEX(interp) == NULL) {
587
0
            return -1;
588
0
        }
589
37
    }
590
591
259
    while (PyList_GET_SIZE(MODULES_BY_INDEX(interp)) <= index) {
592
185
        if (PyList_Append(MODULES_BY_INDEX(interp), Py_None) < 0) {
593
0
            return -1;
594
0
        }
595
185
    }
596
597
74
    return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(module));
598
74
}
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
4.01k
# define PKGCONTEXT pkgcontext
888
889
const char *
890
_PyImport_ResolveNameWithPackageContext(const char *name)
891
148
{
892
148
    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
148
    return name;
900
148
}
901
902
const char *
903
_PyImport_SwapPackageContext(const char *newcontext)
904
1.93k
{
905
1.93k
    const char *oldcontext = PKGCONTEXT;
906
1.93k
    PKGCONTEXT = newcontext;
907
1.93k
    return oldcontext;
908
1.93k
}
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
966
exec_builtin_or_dynamic(PyObject *mod) {
928
966
    void *state;
929
930
966
    if (!PyModule_Check(mod)) {
931
0
        return 0;
932
0
    }
933
934
966
    state = PyModule_GetState(mod);
935
966
    if (state) {
936
        /* Already initialized; skip reload */
937
0
        return 0;
938
0
    }
939
940
966
    return PyModule_Exec(mod);
941
966
}
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.11k
{
1040
1.11k
    PyMutex_Lock(&_PyRuntime.imports.extensions.mutex);
1041
1.11k
}
1042
1043
static inline void
1044
extensions_lock_release(void)
1045
1.11k
{
1046
1.11k
    PyMutex_Unlock(&_PyRuntime.imports.extensions.mutex);
1047
1.11k
}
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
74
{
1108
74
    struct extensions_cache_value *value
1109
74
            = PyMem_RawMalloc(sizeof(struct extensions_cache_value));
1110
74
    if (value == NULL) {
1111
0
        PyErr_NoMemory();
1112
0
        return NULL;
1113
0
    }
1114
74
    *value = (struct extensions_cache_value){0};
1115
74
    return value;
1116
74
}
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
74
{
1127
74
    assert(cached->m_index > 0);
1128
74
    return cached->m_index;
1129
74
}
1130
1131
static void
1132
fixup_cached_def(struct extensions_cache_value *value)
1133
74
{
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
74
    PyModuleDef *def = value->def;
1144
74
    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
74
    _Py_SetImmortalUntracked((PyObject *)def);
1149
1150
74
    def->m_base.m_init = value->m_init;
1151
1152
74
    assert(value->m_index > 0);
1153
74
    _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
74
    assert(def->m_base.m_copy == NULL
1158
74
           || def->m_base.m_init == NULL
1159
74
           || value->m_dict != NULL);
1160
74
    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
74
}
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
74
{
1176
74
    Py_XDECREF(oldbase->m_copy);
1177
74
}
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
74
{
1195
74
    assert(value != NULL);
1196
    /* This should only have been called without an m_dict already set. */
1197
74
    assert(value->m_dict == NULL);
1198
74
    if (m_dict == NULL) {
1199
74
        return 0;
1200
74
    }
1201
74
    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.08k
{
1285
1.08k
    const char *str1_data = _PyUnicode_AsUTF8NoNUL(str1);
1286
1.08k
    const char *str2_data = _PyUnicode_AsUTF8NoNUL(str2);
1287
1.08k
    if (str1_data == NULL || str2_data == NULL) {
1288
0
        return NULL;
1289
0
    }
1290
1.08k
    Py_ssize_t str1_len = strlen(str1_data);
1291
1.08k
    Py_ssize_t str2_len = strlen(str2_data);
1292
1293
    /* Make sure sep and the NULL byte won't cause an overflow. */
1294
1.08k
    assert(SIZE_MAX - str1_len - str2_len > 2);
1295
1.08k
    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.08k
    char *key = PyMem_RawMalloc(size);
1299
1.08k
    if (key == NULL) {
1300
0
        PyErr_NoMemory();
1301
0
        return NULL;
1302
0
    }
1303
1304
1.08k
    memcpy(key, str1_data, str1_len);
1305
1.08k
    key[str1_len] = sep;
1306
1.08k
    memcpy(key + str1_len + 1, str2_data, str2_len);
1307
1.08k
    key[size - 1] = '\0';
1308
1.08k
    assert(strlen(key) == size - 1);
1309
1.08k
    return key;
1310
1.08k
}
1311
1312
static Py_uhash_t
1313
hashtable_hash_str(const void *key)
1314
1.15k
{
1315
1.15k
    return Py_HashBuffer(key, strlen((const char *)key));
1316
1.15k
}
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
1.00k
{
1327
1.00k
    PyMem_RawFree(ptr);
1328
1.00k
}
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.08k
#define HTSEP ':'
1366
1367
static int
1368
_extensions_cache_init(void)
1369
37
{
1370
37
    _Py_hashtable_allocator_t alloc = {PyMem_RawMalloc, PyMem_RawFree};
1371
37
    EXTENSIONS.hashtable = _Py_hashtable_new_full(
1372
37
        hashtable_hash_str,
1373
37
        hashtable_compare_str,
1374
37
        hashtable_destroy_str,  // key
1375
37
        del_extensions_cache_value,  // value
1376
37
        &alloc
1377
37
    );
1378
37
    if (EXTENSIONS.hashtable == NULL) {
1379
0
        PyErr_NoMemory();
1380
0
        return -1;
1381
0
    }
1382
37
    return 0;
1383
37
}
1384
1385
static _Py_hashtable_entry_t *
1386
_extensions_cache_find_unlocked(PyObject *path, PyObject *name,
1387
                                void **p_key)
1388
1.11k
{
1389
1.11k
    if (EXTENSIONS.hashtable == NULL) {
1390
37
        return NULL;
1391
37
    }
1392
1.08k
    void *key = hashtable_key_from_2_strings(path, name, HTSEP);
1393
1.08k
    if (key == NULL) {
1394
0
        return NULL;
1395
0
    }
1396
1.08k
    _Py_hashtable_entry_t *entry =
1397
1.08k
            _Py_hashtable_get_entry(EXTENSIONS.hashtable, key);
1398
1.08k
    if (p_key != NULL) {
1399
74
        *p_key = key;
1400
74
    }
1401
1.00k
    else {
1402
1.00k
        hashtable_destroy_str(key);
1403
1.00k
    }
1404
1.08k
    return entry;
1405
1.08k
}
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.04k
{
1411
1.04k
    struct extensions_cache_value *value = NULL;
1412
1.04k
    extensions_lock_acquire();
1413
1414
1.04k
    _Py_hashtable_entry_t *entry =
1415
1.04k
            _extensions_cache_find_unlocked(path, name, NULL);
1416
1.04k
    if (entry == NULL) {
1417
        /* It was never added. */
1418
1.04k
        goto finally;
1419
1.04k
    }
1420
0
    value = (struct extensions_cache_value *)entry->value;
1421
1422
1.04k
finally:
1423
1.04k
    extensions_lock_release();
1424
1.04k
    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
74
{
1434
74
    struct extensions_cache_value *value = NULL;
1435
74
    void *key = NULL;
1436
74
    struct extensions_cache_value *newvalue = NULL;
1437
74
    PyModuleDef_Base olddefbase = def->m_base;
1438
1439
74
    assert(def != NULL);
1440
74
    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
74
    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
74
    assert(def->m_base.m_copy == NULL || m_dict != NULL);
1446
74
    assert((origin == _Py_ext_module_origin_DYNAMIC) == (name != path));
1447
74
    assert(origin != _Py_ext_module_origin_CORE || m_dict == NULL);
1448
1449
74
    extensions_lock_acquire();
1450
1451
74
    if (EXTENSIONS.hashtable == NULL) {
1452
37
        if (_extensions_cache_init() < 0) {
1453
0
            goto finally;
1454
0
        }
1455
37
    }
1456
1457
    /* Create a cached value to populate for the module. */
1458
74
    _Py_hashtable_entry_t *entry =
1459
74
            _extensions_cache_find_unlocked(path, name, &key);
1460
74
    value = entry == NULL
1461
74
        ? NULL
1462
74
        : (struct extensions_cache_value *)entry->value;
1463
74
    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
74
    newvalue = alloc_extensions_cache_value();
1475
74
    if (newvalue == NULL) {
1476
0
        goto finally;
1477
0
    }
1478
1479
    /* Populate the new cache value data. */
1480
74
    *newvalue = (struct extensions_cache_value){
1481
74
        .def=def,
1482
74
        .m_init=m_init,
1483
74
        .m_index=m_index,
1484
        /* m_dict is set by set_cached_m_dict(). */
1485
74
        .origin=origin,
1486
#ifdef Py_GIL_DISABLED
1487
        .md_requires_gil=requires_gil,
1488
#endif
1489
74
    };
1490
74
#ifndef Py_GIL_DISABLED
1491
74
    (void)requires_gil;
1492
74
#endif
1493
74
    if (init_cached_m_dict(newvalue, m_dict) < 0) {
1494
0
        goto finally;
1495
0
    }
1496
74
    fixup_cached_def(newvalue);
1497
1498
74
    if (entry == NULL) {
1499
        /* It was never added. */
1500
74
        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
74
        key = NULL;
1506
74
    }
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
74
    value = newvalue;
1525
1526
74
finally:
1527
74
    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
74
    else {
1534
74
        cleanup_old_cached_def(&olddefbase);
1535
74
    }
1536
1537
74
finally_oldvalue:
1538
74
    extensions_lock_release();
1539
74
    if (key != NULL) {
1540
0
        hashtable_destroy_str(key);
1541
0
    }
1542
1543
74
    return value;
1544
74
}
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
966
{
1671
966
    if (_Py_IsMainInterpreter(tstate->interp)) {
1672
966
        return tstate;
1673
966
    }
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
74
{
1825
74
    struct extensions_cache_value *cached = NULL;
1826
74
    PyModInitFunction m_init = NULL;
1827
74
    PyObject *m_dict = NULL;
1828
1829
    /* Set up for _extensions_cache_set(). */
1830
74
    if (singlephase == NULL) {
1831
0
        assert(def->m_base.m_init == NULL);
1832
0
        assert(def->m_base.m_copy == NULL);
1833
0
    }
1834
74
    else {
1835
74
        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
74
        else if (singlephase->m_dict == NULL) {
1848
            /* It must be a core builtin module. */
1849
74
            assert(is_core_module(tstate->interp, name, path));
1850
74
            assert(def->m_size == -1);
1851
74
            assert(def->m_base.m_copy == NULL);
1852
74
            assert(def->m_base.m_init == NULL);
1853
74
        }
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
74
    }
1865
1866
    /* Add the module's def to the global cache. */
1867
    // XXX Why special-case the main interpreter?
1868
74
    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
74
        cached = _extensions_cache_set(
1874
74
                path, name, def, m_init, singlephase->m_index, m_dict,
1875
74
                singlephase->origin, singlephase->md_requires_gil);
1876
74
        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
74
    }
1882
1883
74
    return cached;
1884
74
}
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
74
{
1893
74
    assert(mod != NULL && PyModule_Check(mod));
1894
74
    assert(cached->def == _PyModule_GetDefOrNull(mod));
1895
1896
74
    Py_ssize_t index = _get_cached_module_index(cached);
1897
74
    if (_modules_by_index_set(tstate->interp, index, mod) < 0) {
1898
0
        return -1;
1899
0
    }
1900
1901
74
    if (modules != NULL) {
1902
74
        if (PyObject_SetItem(modules, name, mod) < 0) {
1903
0
            return -1;
1904
0
        }
1905
74
    }
1906
1907
74
    return 0;
1908
74
}
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
970
{
2027
    /* Only single-phase init modules will be in the cache. */
2028
970
    struct extensions_cache_value *cached
2029
970
            = _extensions_cache_get(info->path, info->name);
2030
970
    if (cached == NULL) {
2031
970
        return NULL;
2032
970
    }
2033
970
    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
966
{
2102
    /* Core modules go through _PyImport_FixupBuiltin(). */
2103
966
    assert(!is_core_module(tstate->interp, info->name, info->path));
2104
2105
966
    PyObject *mod = NULL;
2106
966
    PyModuleDef *def = NULL;
2107
966
    struct extensions_cache_value *cached = NULL;
2108
966
    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
966
    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
966
    PyThreadState *main_tstate = switch_to_main_interpreter(tstate);
2159
966
    if (main_tstate == NULL) {
2160
0
        return NULL;
2161
0
    }
2162
966
    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
966
    struct _Py_ext_module_loader_result res;
2170
966
    int rc = _PyImport_RunModInitFunc(p0, info, &res);
2171
966
    bool main_error = false;
2172
966
    if (rc < 0) {
2173
        /* We discard res.def. */
2174
0
        assert(res.module == NULL);
2175
0
    }
2176
966
    else {
2177
966
        assert(!PyErr_Occurred());
2178
966
        assert(res.err == NULL);
2179
2180
966
        mod = res.module;
2181
966
        res.module = NULL;
2182
966
        def = res.def;
2183
966
        assert(def != NULL);
2184
2185
        /* Do anything else that should be done
2186
         * while still using the main interpreter. */
2187
966
        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
966
    }
2248
2249
966
main_finally:
2250
966
    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
966
    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
966
    if (rc < 0) {
2281
0
        goto error;
2282
0
    }
2283
966
    if (main_error) {
2284
0
        goto error;
2285
0
    }
2286
2287
966
    if (res.kind == _Py_ext_module_kind_MULTIPHASE) {
2288
966
        assert_multiphase_def(def);
2289
966
        assert(mod == NULL);
2290
        /* Note that we cheat a little by not repeating the calls
2291
         * to _PyImport_GetModuleExportHooks() and _PyImport_RunModInitFunc(). */
2292
966
        mod = PyModule_FromDefAndSpec(def, spec);
2293
966
        if (mod == NULL) {
2294
0
            goto error;
2295
0
        }
2296
966
    }
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
966
    _Py_ext_module_loader_result_clear(&res);
2333
966
    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
966
}
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
74
{
2396
74
    int res = -1;
2397
74
    assert(mod != NULL && PyModule_Check(mod));
2398
2399
74
    PyObject *nameobj;
2400
74
    nameobj = PyUnicode_InternFromString(name);
2401
74
    if (nameobj == NULL) {
2402
0
        return -1;
2403
0
    }
2404
2405
74
    PyModuleDef *def = _PyModule_GetDefOrNull(mod);
2406
74
    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
74
    assert(is_core_module(tstate->interp, nameobj, nameobj));
2417
74
    assert_singlephase_def(def);
2418
74
    assert(def->m_size == -1);
2419
74
    assert(def->m_base.m_copy == NULL);
2420
74
    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
74
    struct extensions_cache_value *cached
2427
74
            = _extensions_cache_get(nameobj, nameobj);
2428
74
    if (cached == NULL) {
2429
74
        struct singlephase_global_update singlephase = {
2430
74
            .m_index=def->m_base.m_index,
2431
            /* We don't want def->m_base.m_copy populated. */
2432
74
            .m_dict=NULL,
2433
74
            .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
74
        };
2439
74
        cached = update_global_state_for_extension(
2440
74
                tstate, nameobj, nameobj, def, &singlephase);
2441
74
        if (cached == NULL) {
2442
0
            goto finally;
2443
0
        }
2444
74
    }
2445
2446
74
    if (finish_singlephase_extension(tstate, mod, cached, nameobj, modules) < 0) {
2447
0
        goto finally;
2448
0
    }
2449
2450
74
    res = 0;
2451
2452
74
finally:
2453
74
    Py_DECREF(nameobj);
2454
74
    return res;
2455
74
}
2456
2457
/* Helper to test for built-in module */
2458
2459
static int
2460
is_builtin(PyObject *name)
2461
13.6k
{
2462
13.6k
    int i;
2463
13.6k
    struct _inittab *inittab = INITTAB;
2464
517k
    for (i = 0; inittab[i].name != NULL; i++) {
2465
504k
        if (_PyUnicode_EqualToASCIIString(name, inittab[i].name)) {
2466
724
            if (inittab[i].initfunc == NULL)
2467
0
                return -1;
2468
724
            else
2469
724
                return 1;
2470
724
        }
2471
504k
    }
2472
12.9k
    return 0;
2473
13.6k
}
2474
2475
static struct _inittab*
2476
lookup_inittab_entry(const struct _Py_ext_module_loader_info* info)
2477
761
{
2478
14.2k
    for (struct _inittab *p = INITTAB; p->name != NULL; p++) {
2479
14.2k
        if (_PyUnicode_EqualToASCIIString(info->name, p->name)) {
2480
761
            return p;
2481
761
        }
2482
14.2k
    }
2483
    // not found
2484
0
    return NULL;
2485
761
}
2486
2487
static PyObject*
2488
create_builtin(
2489
    PyThreadState *tstate, PyObject *name,
2490
    PyObject *spec,
2491
    PyModInitFunction initfunc)
2492
761
{
2493
761
    struct _Py_ext_module_loader_info info;
2494
761
    if (_Py_ext_module_loader_info_init_for_builtin(&info, name) < 0) {
2495
0
        return NULL;
2496
0
    }
2497
2498
761
    struct extensions_cache_value *cached = NULL;
2499
761
    PyObject *mod = import_find_extension(tstate, &info, &cached);
2500
761
    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
761
    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
761
    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
761
    PyModInitFunction p0 = NULL;
2523
761
    if (initfunc == NULL) {
2524
761
        struct _inittab *entry = lookup_inittab_entry(&info);
2525
761
        if (entry == NULL) {
2526
0
            mod = NULL;
2527
0
            _PyErr_SetModuleNotFoundError(name);
2528
0
            goto finally;
2529
0
        }
2530
2531
761
        p0 = (PyModInitFunction)entry->initfunc;
2532
761
    }
2533
0
    else {
2534
0
        p0 = initfunc;
2535
0
    }
2536
2537
761
    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
761
    mod = import_run_extension(
2555
761
                    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
761
finally:
2564
761
    _Py_ext_module_loader_info_clear(&info);
2565
761
    return mod;
2566
761
}
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
37
{
2675
37
    size_t size;
2676
1.44k
    for (size = 0; PyImport_Inittab[size].name != NULL; size++)
2677
1.40k
        ;
2678
37
    size++;
2679
2680
    /* Make the copy. */
2681
37
    struct _inittab *copied = _PyMem_DefaultRawMalloc(size * sizeof(struct _inittab));
2682
37
    if (copied == NULL) {
2683
0
        return -1;
2684
0
    }
2685
37
    memcpy(copied, PyImport_Inittab, size * sizeof(struct _inittab));
2686
37
    INITTAB = copied;
2687
37
    return 0;
2688
37
}
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
37
{
2701
37
    PyObject *list = PyList_New(0);
2702
37
    if (list == NULL) {
2703
0
        return NULL;
2704
0
    }
2705
37
    struct _inittab *inittab = INITTAB;
2706
1.44k
    for (Py_ssize_t i = 0; inittab[i].name != NULL; i++) {
2707
1.40k
        PyObject *name = PyUnicode_FromString(inittab[i].name);
2708
1.40k
        if (name == NULL) {
2709
0
            Py_DECREF(list);
2710
0
            return NULL;
2711
0
        }
2712
1.40k
        if (PyList_Append(list, name) < 0) {
2713
0
            Py_DECREF(name);
2714
0
            Py_DECREF(list);
2715
0
            return NULL;
2716
0
        }
2717
1.40k
        Py_DECREF(name);
2718
1.40k
    }
2719
37
    return list;
2720
37
}
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
37
{
2828
37
    PyObject *m, *d;
2829
2830
37
    m = import_add_module(tstate, name);
2831
37
    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
37
    d = PyModule_GetDict(m);
2836
37
    int r = PyDict_Contains(d, &_Py_ID(__builtins__));
2837
37
    if (r == 0) {
2838
37
        r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins());
2839
37
    }
2840
37
    if (r < 0) {
2841
0
        remove_module(tstate, name);
2842
0
        Py_DECREF(m);
2843
0
        return NULL;
2844
0
    }
2845
2846
37
    Py_INCREF(d);
2847
37
    Py_DECREF(m);
2848
37
    return d;
2849
37
}
2850
2851
static PyObject *
2852
exec_code_in_module(PyThreadState *tstate, PyObject *name,
2853
                    PyObject *module_dict, PyObject *code_object)
2854
37
{
2855
37
    PyObject *v, *m;
2856
2857
37
    v = PyEval_EvalCode(code_object, module_dict, module_dict);
2858
37
    if (v == NULL) {
2859
0
        remove_module(tstate, name);
2860
0
        return NULL;
2861
0
    }
2862
37
    Py_DECREF(v);
2863
2864
37
    m = import_get_module(tstate, name);
2865
37
    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
37
    return m;
2872
37
}
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.18k
{
2931
6.18k
    PyObject *oldname;
2932
2933
6.18k
    if (PyUnicode_Compare(co->co_filename, newname) == 0)
2934
6.18k
        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.25k
{
2954
1.25k
    const struct _module_alias *entry;
2955
9.92k
    for (entry = aliases; ; entry++) {
2956
9.92k
        if (entry->name == NULL) {
2957
            /* It isn't an alias. */
2958
1.07k
            return false;
2959
1.07k
        }
2960
8.85k
        if (strcmp(name, entry->name) == 0) {
2961
185
            if (alias != NULL) {
2962
185
                *alias = entry->orig;
2963
185
            }
2964
185
            return true;
2965
185
        }
2966
8.85k
    }
2967
1.25k
}
2968
2969
static bool
2970
use_frozen(void)
2971
13.3k
{
2972
13.3k
    PyInterpreterState *interp = _PyInterpreterState_GET();
2973
13.3k
    int override = OVERRIDE_FROZEN_MODULES(interp);
2974
13.3k
    if (override > 0) {
2975
0
        return true;
2976
0
    }
2977
13.3k
    else if (override < 0) {
2978
0
        return false;
2979
0
    }
2980
13.3k
    else {
2981
13.3k
        return interp->config.use_frozen_modules;
2982
13.3k
    }
2983
13.3k
}
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.6k
{
3113
13.6k
    const struct _frozen *p;
3114
    // We always use the bootstrap modules.
3115
53.9k
    for (p = _PyImport_FrozenBootstrap; ; p++) {
3116
53.9k
        if (p->name == NULL) {
3117
            // We hit the end-of-list sentinel value.
3118
13.3k
            break;
3119
13.3k
        }
3120
40.5k
        if (strcmp(name, p->name) == 0) {
3121
259
            return p;
3122
259
        }
3123
40.5k
    }
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.3k
    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.3k
    if (use_frozen()) {
3138
255k
        for (p = _PyImport_FrozenStdlib; ; p++) {
3139
255k
            if (p->name == NULL) {
3140
12.3k
                break;
3141
12.3k
            }
3142
243k
            if (strcmp(name, p->name) == 0) {
3143
1.00k
                return p;
3144
1.00k
            }
3145
243k
        }
3146
148k
        for (p = _PyImport_FrozenTest; ; p++) {
3147
148k
            if (p->name == NULL) {
3148
12.3k
                break;
3149
12.3k
            }
3150
136k
            if (strcmp(name, p->name) == 0) {
3151
0
                return p;
3152
0
            }
3153
136k
        }
3154
12.3k
    }
3155
12.3k
    return NULL;
3156
13.3k
}
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.6k
{
3170
13.6k
    if (info != NULL) {
3171
13.6k
        memset(info, 0, sizeof(*info));
3172
13.6k
    }
3173
3174
13.6k
    if (nameobj == NULL || nameobj == Py_None) {
3175
0
        return FROZEN_BAD_NAME;
3176
0
    }
3177
13.6k
    const char *name = PyUnicode_AsUTF8(nameobj);
3178
13.6k
    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.6k
    const struct _frozen *p = look_up_frozen(name);
3188
13.6k
    if (p == NULL) {
3189
12.3k
        return FROZEN_NOT_FOUND;
3190
12.3k
    }
3191
1.25k
    if (info != NULL) {
3192
1.25k
        info->nameobj = nameobj;  // borrowed
3193
1.25k
        info->data = (const char *)p->code;
3194
1.25k
        info->size = p->size;
3195
1.25k
        info->is_package = p->is_package;
3196
1.25k
        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.25k
        info->origname = name;
3202
1.25k
        info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
3203
1.25k
                                              &info->origname);
3204
1.25k
    }
3205
1.25k
    if (p->code == NULL) {
3206
        /* It is frozen but marked as un-importable. */
3207
0
        return FROZEN_EXCLUDED;
3208
0
    }
3209
1.25k
    if (p->code[0] == '\0' || p->size == 0) {
3210
        /* Does not contain executable code. */
3211
0
        return FROZEN_INVALID;
3212
0
    }
3213
1.25k
    return FROZEN_OKAY;
3214
1.25k
}
3215
3216
static PyObject *
3217
unmarshal_frozen_code(PyInterpreterState *interp, struct frozen_info *info)
3218
611
{
3219
611
    PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
3220
611
    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
611
    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
611
    return co;
3235
611
}
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
37
{
3246
37
    PyThreadState *tstate = _PyThreadState_GET();
3247
37
    PyObject *co, *m, *d = NULL;
3248
37
    int err;
3249
3250
37
    struct frozen_info info;
3251
37
    frozen_status status = find_frozen(name, &info);
3252
37
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
3253
0
        return 0;
3254
0
    }
3255
37
    else if (status == FROZEN_BAD_NAME) {
3256
0
        return 0;
3257
0
    }
3258
37
    else if (status != FROZEN_OKAY) {
3259
0
        set_frozen_error(status, name);
3260
0
        return -1;
3261
0
    }
3262
37
    co = unmarshal_frozen_code(tstate->interp, &info);
3263
37
    if (co == NULL) {
3264
0
        return -1;
3265
0
    }
3266
37
    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
37
    d = module_dict_for_exec(tstate, name);
3285
37
    if (d == NULL) {
3286
0
        goto err_return;
3287
0
    }
3288
37
    m = exec_code_in_module(tstate, name, d, co);
3289
37
    if (m == NULL) {
3290
0
        goto err_return;
3291
0
    }
3292
37
    Py_DECREF(m);
3293
    /* Set __origname__ (consumed in FrozenImporter._setup_module()). */
3294
37
    PyObject *origname;
3295
37
    if (info.origname) {
3296
37
        origname = PyUnicode_FromString(info.origname);
3297
37
        if (origname == NULL) {
3298
0
            goto err_return;
3299
0
        }
3300
37
    }
3301
0
    else {
3302
0
        origname = Py_NewRef(Py_None);
3303
0
    }
3304
37
    err = PyDict_SetItemString(d, "__origname__", origname);
3305
37
    Py_DECREF(origname);
3306
37
    if (err != 0) {
3307
0
        goto err_return;
3308
0
    }
3309
37
    Py_DECREF(d);
3310
37
    Py_DECREF(co);
3311
37
    return 1;
3312
3313
0
err_return:
3314
0
    Py_XDECREF(d);
3315
0
    Py_DECREF(co);
3316
0
    return -1;
3317
37
}
3318
3319
int
3320
PyImport_ImportFrozenModule(const char *name)
3321
37
{
3322
37
    PyObject *nameobj;
3323
37
    int ret;
3324
37
    nameobj = PyUnicode_InternFromString(name);
3325
37
    if (nameobj == NULL)
3326
0
        return -1;
3327
37
    ret = PyImport_ImportFrozenModuleObject(nameobj);
3328
37
    Py_DECREF(nameobj);
3329
37
    return ret;
3330
37
}
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
37
{
3344
37
    PyObject *name = PyUnicode_FromString("_imp");
3345
37
    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
37
    PyObject *attrs = Py_BuildValue("{sO}", "name", name);
3354
37
    if (attrs == NULL) {
3355
0
        goto error;
3356
0
    }
3357
37
    PyObject *spec = _PyNamespace_New(attrs);
3358
37
    Py_DECREF(attrs);
3359
37
    if (spec == NULL) {
3360
0
        goto error;
3361
0
    }
3362
3363
    // Create the _imp module from its definition.
3364
37
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
3365
37
    Py_CLEAR(name);
3366
37
    Py_DECREF(spec);
3367
37
    if (mod == NULL) {
3368
0
        goto error;
3369
0
    }
3370
37
    assert(mod != Py_None);  // not found
3371
3372
    // Execute the _imp module: call imp_module_exec().
3373
37
    if (exec_builtin_or_dynamic(mod) < 0) {
3374
0
        Py_DECREF(mod);
3375
0
        goto error;
3376
0
    }
3377
37
    return mod;
3378
3379
0
error:
3380
0
    Py_XDECREF(name);
3381
0
    return NULL;
3382
37
}
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
37
{
3398
37
    assert(!_PyErr_Occurred(tstate));
3399
3400
37
    PyInterpreterState *interp = tstate->interp;
3401
37
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
3402
3403
    // Import _importlib through its frozen version, _frozen_importlib.
3404
37
    if (verbose) {
3405
0
        PySys_FormatStderr("import _frozen_importlib # frozen\n");
3406
0
    }
3407
37
    if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
3408
0
        return -1;
3409
0
    }
3410
3411
37
    PyObject *importlib = PyImport_AddModuleRef("_frozen_importlib");
3412
37
    if (importlib == NULL) {
3413
0
        return -1;
3414
0
    }
3415
37
    IMPORTLIB(interp) = importlib;
3416
3417
    // Import the _imp module
3418
37
    if (verbose) {
3419
0
        PySys_FormatStderr("import _imp # builtin\n");
3420
0
    }
3421
37
    PyObject *imp_mod = bootstrap_imp(tstate);
3422
37
    if (imp_mod == NULL) {
3423
0
        return -1;
3424
0
    }
3425
37
    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
37
    PyObject *value = PyObject_CallMethod(importlib, "_install",
3432
37
                                          "OO", sysmod, imp_mod);
3433
37
    Py_DECREF(imp_mod);
3434
37
    if (value == NULL) {
3435
0
        return -1;
3436
0
    }
3437
37
    Py_DECREF(value);
3438
3439
37
    assert(!_PyErr_Occurred(tstate));
3440
37
    return 0;
3441
37
}
3442
3443
3444
static int
3445
init_importlib_external(PyInterpreterState *interp)
3446
37
{
3447
37
    PyObject *value;
3448
37
    value = PyObject_CallMethod(IMPORTLIB(interp),
3449
37
                                "_install_external_importers", "");
3450
37
    if (value == NULL) {
3451
0
        return -1;
3452
0
    }
3453
37
    Py_DECREF(value);
3454
37
    return 0;
3455
37
}
3456
3457
PyObject *
3458
_PyImport_GetImportlibLoader(PyInterpreterState *interp,
3459
                             const char *loader_name)
3460
37
{
3461
37
    return PyObject_GetAttrString(IMPORTLIB(interp), loader_name);
3462
37
}
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
37
{
3590
    // Get the __import__ function
3591
37
    PyObject *import_func;
3592
37
    if (PyDict_GetItemStringRef(interp->builtins, "__import__", &import_func) <= 0) {
3593
0
        return -1;
3594
0
    }
3595
37
    IMPORT_FUNC(interp) = import_func;
3596
3597
    // Get the __lazy_import__ function
3598
37
    if (PyDict_GetItemStringRef(interp->builtins, "__lazy_import__",
3599
37
                                &import_func) <= 0) {
3600
0
        return -1;
3601
0
    }
3602
37
    LAZY_IMPORT_FUNC(interp) = import_func;
3603
37
    return 0;
3604
37
}
3605
3606
int
3607
_PyImport_IsDefaultImportFunc(PyInterpreterState *interp, PyObject *func)
3608
3.65M
{
3609
3.65M
    return func == IMPORT_FUNC(interp);
3610
3.65M
}
3611
3612
int
3613
_PyImport_IsDefaultLazyImportFunc(PyInterpreterState *interp, PyObject *func)
3614
308
{
3615
308
    return func == LAZY_IMPORT_FUNC(interp);
3616
308
}
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.35k
{
3624
1.35k
    PyObject *pname;
3625
1.35k
    PyObject *result;
3626
3627
1.35k
    pname = PyUnicode_FromString(name);
3628
1.35k
    if (pname == NULL)
3629
0
        return NULL;
3630
1.35k
    result = PyImport_Import(pname);
3631
1.35k
    Py_DECREF(pname);
3632
1.35k
    return result;
3633
1.35k
}
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.1k
{
3665
10.1k
    const char *importlib_filename = "<frozen importlib._bootstrap>";
3666
10.1k
    const char *external_filename = "<frozen importlib._bootstrap_external>";
3667
10.1k
    const char *remove_frames = "_call_with_frames_removed";
3668
10.1k
    int always_trim = 0;
3669
10.1k
    int in_importlib = 0;
3670
10.1k
    PyObject **prev_link, **outer_link = NULL;
3671
10.1k
    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.1k
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3678
10.1k
    if (exc == NULL || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
3679
0
        goto done;
3680
0
    }
3681
3682
10.1k
    if (PyType_IsSubtype(Py_TYPE(exc), (PyTypeObject *) PyExc_ImportError)) {
3683
10.1k
        always_trim = 1;
3684
10.1k
    }
3685
3686
10.1k
    assert(PyExceptionInstance_Check(exc));
3687
10.1k
    base_tb = PyException_GetTraceback(exc);
3688
10.1k
    prev_link = &base_tb;
3689
10.1k
    PyObject *tb = base_tb;
3690
48.1k
    while (tb != NULL) {
3691
37.9k
        assert(PyTraceBack_Check(tb));
3692
37.9k
        PyTracebackObject *traceback = (PyTracebackObject *)tb;
3693
37.9k
        PyObject *next = (PyObject *) traceback->tb_next;
3694
37.9k
        PyFrameObject *frame = traceback->tb_frame;
3695
37.9k
        PyCodeObject *code = PyFrame_GetCode(frame);
3696
37.9k
        int now_in_importlib;
3697
3698
37.9k
        now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
3699
8.77k
                           _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
3700
37.9k
        if (now_in_importlib && !in_importlib) {
3701
            /* This is the link to this chunk of importlib tracebacks */
3702
10.1k
            outer_link = prev_link;
3703
10.1k
        }
3704
37.9k
        in_importlib = now_in_importlib;
3705
3706
37.9k
        if (in_importlib &&
3707
33.5k
            (always_trim ||
3708
33.5k
             _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
3709
33.5k
            Py_XSETREF(*outer_link, Py_XNewRef(next));
3710
33.5k
            prev_link = outer_link;
3711
33.5k
        }
3712
4.39k
        else {
3713
4.39k
            prev_link = (PyObject **) &traceback->tb_next;
3714
4.39k
        }
3715
37.9k
        Py_DECREF(code);
3716
37.9k
        tb = next;
3717
37.9k
    }
3718
10.1k
    if (base_tb == NULL) {
3719
5.80k
        base_tb = Py_None;
3720
5.80k
        Py_INCREF(Py_None);
3721
5.80k
    }
3722
10.1k
    PyException_SetTraceback(exc, base_tb);
3723
10.1k
done:
3724
10.1k
    Py_XDECREF(base_tb);
3725
10.1k
    _PyErr_SetRaisedException(tstate, exc);
3726
10.1k
}
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
497
        return base;
3864
497
    }
3865
3866
530
    abs_name = PyUnicode_FromFormat("%U.%U", base, name);
3867
530
    Py_DECREF(base);
3868
530
    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.5k
{
4111
13.5k
    PyObject *mod = NULL;
4112
13.5k
    PyInterpreterState *interp = tstate->interp;
4113
13.5k
    int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
4114
13.5k
#define import_level FIND_AND_LOAD(interp).import_level
4115
13.5k
#define accumulated FIND_AND_LOAD(interp).accumulated
4116
4117
13.5k
    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.5k
    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.5k
    if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
4134
0
        PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
4135
4136
13.5k
    mod = PyObject_CallMethodObjArgs(IMPORTLIB(interp), &_Py_ID(_find_and_load),
4137
13.5k
                                     abs_name, IMPORT_FUNC(interp), NULL);
4138
4139
13.5k
    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.5k
    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.5k
    return mod;
4158
13.5k
#undef import_level
4159
13.5k
#undef accumulated
4160
13.5k
}
4161
4162
static PyObject *
4163
get_abs_name(PyThreadState *tstate, PyObject *name, PyObject *globals,
4164
             int level)
4165
3.95M
{
4166
3.95M
    if (level > 0) {
4167
1.02k
        return resolve_name(tstate, name, globals, level);
4168
1.02k
    }
4169
3.95M
    if (PyUnicode_GET_LENGTH(name) == 0) {
4170
0
        _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
4171
0
        return NULL;
4172
0
    }
4173
3.95M
    return Py_NewRef(name);
4174
3.95M
}
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.95M
{
4189
3.95M
    PyThreadState *tstate = _PyThreadState_GET();
4190
3.95M
    PyObject *abs_name = NULL;
4191
3.95M
    PyObject *final_mod = NULL;
4192
3.95M
    PyObject *mod = NULL;
4193
3.95M
    PyInterpreterState *interp = tstate->interp;
4194
3.95M
    int has_from;
4195
4196
3.95M
    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.95M
    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.95M
    if (level < 0) {
4210
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
4211
0
        goto error;
4212
0
    }
4213
4214
3.95M
    abs_name = get_abs_name(tstate, name, globals, level);
4215
3.95M
    if (abs_name == NULL) {
4216
0
        goto error;
4217
0
    }
4218
4219
3.95M
    mod = import_get_module(tstate, abs_name);
4220
3.95M
    if (mod == NULL && _PyErr_Occurred(tstate)) {
4221
0
        goto error;
4222
0
    }
4223
4224
3.95M
    if (mod != NULL && mod != Py_None) {
4225
3.93M
        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.93M
        PyObject *mod_check = import_get_module(tstate, abs_name);
4235
3.93M
        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.93M
        else {
4247
3.93M
            Py_DECREF(mod_check);
4248
3.93M
        }
4249
3.93M
    }
4250
13.5k
    else {
4251
13.5k
        Py_XDECREF(mod);
4252
13.5k
        mod = import_find_and_load(tstate, abs_name);
4253
13.5k
        if (mod == NULL) {
4254
10.1k
            goto error;
4255
10.1k
        }
4256
13.5k
    }
4257
4258
3.94M
    has_from = 0;
4259
3.94M
    if (fromlist != NULL && fromlist != Py_None) {
4260
1.49M
        has_from = PyObject_IsTrue(fromlist);
4261
1.49M
        if (has_from < 0)
4262
0
            goto error;
4263
1.49M
    }
4264
3.94M
    if (!has_from) {
4265
2.73M
        Py_ssize_t len = PyUnicode_GET_LENGTH(name);
4266
2.73M
        if (level == 0 || len > 0) {
4267
2.73M
            Py_ssize_t dot;
4268
4269
2.73M
            dot = PyUnicode_FindChar(name, '.', 0, len, 1);
4270
2.73M
            if (dot == -2) {
4271
0
                goto error;
4272
0
            }
4273
4274
2.73M
            if (dot == -1) {
4275
                /* No dot in module name, simple exit */
4276
2.72M
                final_mod = Py_NewRef(mod);
4277
2.72M
                goto error;
4278
2.72M
            }
4279
4280
2.88k
            if (level == 0) {
4281
2.88k
                PyObject *front = PyUnicode_Substring(name, 0, dot);
4282
2.88k
                if (front == NULL) {
4283
0
                    goto error;
4284
0
                }
4285
4286
2.88k
                final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
4287
2.88k
                Py_DECREF(front);
4288
2.88k
            }
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.88k
        }
4312
0
        else {
4313
0
            final_mod = Py_NewRef(mod);
4314
0
        }
4315
2.73M
    }
4316
1.20M
    else {
4317
1.20M
        int has_path = PyObject_HasAttrWithError(mod, &_Py_ID(__path__));
4318
1.20M
        if (has_path < 0) {
4319
0
            goto error;
4320
0
        }
4321
1.20M
        if (has_path) {
4322
8.09k
            final_mod = PyObject_CallMethodObjArgs(
4323
8.09k
                        IMPORTLIB(interp), &_Py_ID(_handle_fromlist),
4324
8.09k
                        mod, fromlist, IMPORT_FUNC(interp), NULL);
4325
8.09k
        }
4326
1.20M
        else {
4327
1.20M
            final_mod = Py_NewRef(mod);
4328
1.20M
        }
4329
1.20M
    }
4330
4331
3.95M
  error:
4332
3.95M
    Py_XDECREF(abs_name);
4333
3.95M
    Py_XDECREF(mod);
4334
3.95M
    if (final_mod == NULL) {
4335
10.1k
        remove_importlib_frames(tstate);
4336
10.1k
    }
4337
3.95M
    return final_mod;
4338
3.94M
}
4339
4340
static PyObject *
4341
get_mod_dict(PyObject *module)
4342
73
{
4343
73
    if (PyModule_Check(module)) {
4344
73
        return Py_NewRef(_PyModule_GetDict(module));
4345
73
    }
4346
4347
0
    return PyObject_GetAttr(module, &_Py_ID(__dict__));
4348
73
}
4349
4350
// ensure we have the set for the parent module name in sys.lazy_modules.
4351
// Returns a new reference.
4352
static PyObject *
4353
ensure_lazy_pending_submodules(PyDictObject *lazy_modules, PyObject *parent)
4354
479
{
4355
479
    PyObject *lazy_submodules;
4356
479
    Py_BEGIN_CRITICAL_SECTION(lazy_modules);
4357
479
    int err = _PyDict_GetItemRef_Unicode_LockHeld(lazy_modules, parent,
4358
479
                                                  &lazy_submodules);
4359
479
    if (err == 0) {
4360
        // value isn't present
4361
274
        lazy_submodules = PySet_New(NULL);
4362
274
        if (lazy_submodules != NULL &&
4363
274
            _PyDict_SetItem_LockHeld(lazy_modules, parent,
4364
274
                                     lazy_submodules) < 0) {
4365
0
            Py_CLEAR(lazy_submodules);
4366
0
        }
4367
274
    }
4368
479
    Py_END_CRITICAL_SECTION();
4369
479
    return lazy_submodules;
4370
479
}
4371
4372
// Ensures that we have a LazyImportObject on the parent module for
4373
// all children modules which have been lazily imported. If the parent
4374
// module overrides the child attribute then the value is not replaced.
4375
static int
4376
register_lazy_on_parent(PyThreadState *tstate, PyObject *name,
4377
                        PyObject *builtins)
4378
350
{
4379
350
    int ret = -1;
4380
350
    PyObject *parent = NULL;
4381
350
    PyObject *child = NULL;
4382
350
    PyObject *parent_module = NULL;
4383
350
    PyObject *parent_dict = NULL;
4384
4385
350
    PyInterpreterState *interp = tstate->interp;
4386
350
    PyObject *lazy_pending_submodules = LAZY_PENDING_SUBMODULES(interp);
4387
350
    assert(lazy_pending_submodules != NULL);
4388
4389
350
    Py_INCREF(name);
4390
479
    while (true) {
4391
479
        Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
4392
479
                                            PyUnicode_GET_LENGTH(name), -1);
4393
479
        if (dot < 0) {
4394
336
            PyObject *lazy_submodules = ensure_lazy_pending_submodules(
4395
336
                (PyDictObject *)lazy_pending_submodules, name);
4396
336
            if (lazy_submodules == NULL) {
4397
0
                goto done;
4398
0
            }
4399
336
            Py_DECREF(lazy_submodules);
4400
336
            ret = 0;
4401
336
            goto done;
4402
336
        }
4403
143
        parent = PyUnicode_Substring(name, 0, dot);
4404
        // If `parent` is NULL then this has hit the end of the import, no
4405
        // more "parent.child" in the import name. The entire import will be
4406
        // resolved lazily.
4407
143
        if (parent == NULL) {
4408
0
            goto done;
4409
0
        }
4410
143
        Py_XDECREF(child);
4411
143
        child = PyUnicode_Substring(name, dot + 1, PyUnicode_GET_LENGTH(name));
4412
143
        if (child == NULL) {
4413
0
            goto done;
4414
0
        }
4415
4416
        // Record the child as being lazily imported from the parent.
4417
143
        PyObject *lazy_submodules = ensure_lazy_pending_submodules(
4418
143
            (PyDictObject *)lazy_pending_submodules, parent);
4419
143
        if (lazy_submodules == NULL) {
4420
0
            goto done;
4421
0
        }
4422
4423
143
        if (PySet_Add(lazy_submodules, child) < 0) {
4424
0
            Py_DECREF(lazy_submodules);
4425
0
            goto done;
4426
0
        }
4427
143
        Py_DECREF(lazy_submodules);
4428
4429
        // Add the lazy import for the child to the parent.
4430
143
        Py_XSETREF(parent_module, PyImport_GetModule(parent));
4431
143
        if (parent_module != NULL) {
4432
14
            Py_XSETREF(parent_dict, get_mod_dict(parent_module));
4433
14
            if (parent_dict == NULL) {
4434
0
                goto done;
4435
0
            }
4436
14
            if (PyDict_CheckExact(parent_dict)) {
4437
14
                int contains = PyDict_Contains(parent_dict, child);
4438
14
                if (contains < 0) {
4439
0
                    goto done;
4440
0
                }
4441
14
                if (!contains) {
4442
2
                    PyObject *lazy_module_attr = _PyLazyImport_New(
4443
2
                        tstate->current_frame, builtins, parent, child
4444
2
                    );
4445
2
                    if (lazy_module_attr == NULL) {
4446
0
                        goto done;
4447
0
                    }
4448
2
                    if (PyDict_SetItem(parent_dict, child,
4449
2
                                       lazy_module_attr) < 0) {
4450
0
                        Py_DECREF(lazy_module_attr);
4451
0
                        goto done;
4452
0
                    }
4453
2
                    Py_DECREF(lazy_module_attr);
4454
2
                }
4455
14
            }
4456
14
            ret = 0;
4457
14
            goto done;
4458
14
        }
4459
4460
129
        Py_SETREF(name, parent);
4461
129
        parent = NULL;
4462
129
    }
4463
4464
350
done:
4465
350
    Py_XDECREF(parent_dict);
4466
350
    Py_XDECREF(parent_module);
4467
350
    Py_XDECREF(child);
4468
350
    Py_XDECREF(parent);
4469
350
    Py_XDECREF(name);
4470
350
    return ret;
4471
350
}
4472
4473
static int
4474
register_from_lazy_on_parent(PyThreadState *tstate, PyObject *abs_name,
4475
                             PyObject *from, PyObject *builtins)
4476
131
{
4477
131
    PyObject *fromname = PyUnicode_FromFormat("%U.%U", abs_name, from);
4478
131
    if (fromname == NULL) {
4479
0
        return -1;
4480
0
    }
4481
4482
    // Add the module name to sys.lazy_modules set (PEP 810).
4483
131
    PyObject *lazy_modules = LAZY_MODULES(tstate->interp);
4484
131
    if (PySet_Add(lazy_modules, fromname) < 0) {
4485
0
        Py_DECREF(fromname);
4486
0
        return -1;
4487
0
    }
4488
4489
131
    int res = register_lazy_on_parent(tstate, fromname, builtins);
4490
131
    Py_DECREF(fromname);
4491
131
    return res;
4492
131
}
4493
4494
PyObject *
4495
_PyImport_LazyImportModuleLevelObject(PyThreadState *tstate,
4496
                                      PyObject *name, PyObject *builtins,
4497
                                      PyObject *globals, PyObject *locals,
4498
                                      PyObject *fromlist, int level)
4499
308
{
4500
308
    assert(name != NULL);
4501
308
    if (!PyUnicode_Check(name)) {
4502
0
        _PyErr_Format(tstate, PyExc_TypeError,
4503
0
                      "module name must be a string, got %T", name);
4504
0
        return NULL;
4505
0
    }
4506
308
    if (level < 0) {
4507
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
4508
0
        return NULL;
4509
0
    }
4510
4511
308
    PyObject *abs_name = get_abs_name(tstate, name, globals, level);
4512
308
    if (abs_name == NULL) {
4513
0
        return NULL;
4514
0
    }
4515
4516
308
    PyInterpreterState *interp = tstate->interp;
4517
308
    _PyInterpreterFrame *frame = _PyEval_GetFrame();
4518
308
    if (frame == NULL || frame->f_globals != frame->f_locals) {
4519
0
        Py_DECREF(abs_name);
4520
0
        PyErr_SetString(PyExc_SyntaxError,
4521
0
                        "'lazy import' is only allowed at module level");
4522
0
        return NULL;
4523
0
    }
4524
4525
    // Check if the filter disables the lazy import.
4526
    // We must hold a reference to the filter while calling it to prevent
4527
    // use-after-free if another thread replaces it via
4528
    // PyImport_SetLazyImportsFilter.
4529
308
    LAZY_IMPORTS_LOCK(interp);
4530
308
    PyObject *filter = Py_XNewRef(LAZY_IMPORTS_FILTER(interp));
4531
308
    LAZY_IMPORTS_UNLOCK(interp);
4532
4533
308
    if (filter != NULL) {
4534
0
        PyObject *modname;
4535
0
        if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &modname) < 0) {
4536
0
            Py_DECREF(filter);
4537
0
            Py_DECREF(abs_name);
4538
0
            return NULL;
4539
0
        }
4540
0
        if (modname == NULL) {
4541
0
            assert(!PyErr_Occurred());
4542
0
            modname = Py_NewRef(Py_None);
4543
0
        }
4544
0
        if (fromlist == NULL) {
4545
0
            assert(!PyErr_Occurred());
4546
0
            fromlist = Py_NewRef(Py_None);
4547
0
        }
4548
0
        PyObject *args[] = {modname, abs_name, fromlist};
4549
0
        PyObject *res = PyObject_Vectorcall(filter, args, 3, NULL);
4550
4551
0
        Py_DECREF(modname);
4552
0
        Py_DECREF(filter);
4553
4554
0
        if (res == NULL) {
4555
0
            Py_DECREF(abs_name);
4556
0
            return NULL;
4557
0
        }
4558
4559
0
        int is_true = PyObject_IsTrue(res);
4560
0
        Py_DECREF(res);
4561
4562
0
        if (is_true < 0) {
4563
0
            Py_DECREF(abs_name);
4564
0
            return NULL;
4565
0
        }
4566
0
        if (!is_true) {
4567
0
            Py_DECREF(abs_name);
4568
0
            return PyImport_ImportModuleLevelObject(
4569
0
                name, globals, locals, fromlist, level
4570
0
            );
4571
0
        }
4572
0
    }
4573
4574
    // here, 'filter' is either NULL or is equivalent to a borrowed reference
4575
308
    PyObject *res = _PyLazyImport_New(frame, builtins, abs_name, fromlist);
4576
308
    if (res == NULL) {
4577
0
        Py_DECREF(abs_name);
4578
0
        return NULL;
4579
0
    }
4580
4581
    // Add the module name to sys.lazy_modules set (PEP 810).
4582
308
    PyObject *lazy_modules = LAZY_MODULES(tstate->interp);
4583
308
    if (PySet_Add(lazy_modules, abs_name) < 0) {
4584
0
        goto error;
4585
0
    }
4586
4587
308
    if (fromlist && PyUnicode_Check(fromlist)) {
4588
0
        if (register_from_lazy_on_parent(tstate, abs_name, fromlist,
4589
0
                                         builtins) < 0) {
4590
0
            goto error;
4591
0
        }
4592
0
    }
4593
308
    else if (fromlist && PyTuple_Check(fromlist) &&
4594
89
             PyTuple_GET_SIZE(fromlist)) {
4595
220
        for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(fromlist); i++) {
4596
131
            if (register_from_lazy_on_parent(tstate, abs_name,
4597
131
                                             PyTuple_GET_ITEM(fromlist, i),
4598
131
                                             builtins) < 0)
4599
0
            {
4600
0
                goto error;
4601
0
            }
4602
131
        }
4603
89
    }
4604
219
    else if (register_lazy_on_parent(tstate, abs_name, builtins) < 0) {
4605
0
        goto error;
4606
0
    }
4607
4608
308
    Py_DECREF(abs_name);
4609
308
    return res;
4610
0
error:
4611
0
    Py_DECREF(abs_name);
4612
0
    Py_DECREF(res);
4613
0
    return NULL;
4614
308
}
4615
4616
PyObject *
4617
PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
4618
                           PyObject *fromlist, int level)
4619
296
{
4620
296
    PyObject *nameobj, *mod;
4621
296
    nameobj = PyUnicode_FromString(name);
4622
296
    if (nameobj == NULL)
4623
0
        return NULL;
4624
296
    mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
4625
296
                                           fromlist, level);
4626
296
    Py_DECREF(nameobj);
4627
296
    return mod;
4628
296
}
4629
4630
4631
/* Re-import a module of any kind and return its module object, WITH
4632
   INCREMENTED REFERENCE COUNT */
4633
4634
PyObject *
4635
PyImport_ReloadModule(PyObject *m)
4636
0
{
4637
0
    PyObject *reloaded_module = NULL;
4638
0
    PyObject *importlib = PyImport_GetModule(&_Py_ID(importlib));
4639
0
    if (importlib == NULL) {
4640
0
        if (PyErr_Occurred()) {
4641
0
            return NULL;
4642
0
        }
4643
4644
0
        importlib = PyImport_ImportModule("importlib");
4645
0
        if (importlib == NULL) {
4646
0
            return NULL;
4647
0
        }
4648
0
    }
4649
4650
0
    reloaded_module = PyObject_CallMethodOneArg(importlib, &_Py_ID(reload), m);
4651
0
    Py_DECREF(importlib);
4652
0
    return reloaded_module;
4653
0
}
4654
4655
4656
/* Higher-level import emulator which emulates the "import" statement
4657
   more accurately -- it invokes the __import__() function from the
4658
   builtins of the current globals.  This means that the import is
4659
   done using whatever import hooks are installed in the current
4660
   environment.
4661
   A dummy list ["__doc__"] is passed as the 4th argument so that
4662
   e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
4663
   will return <module "gencache"> instead of <module "win32com">. */
4664
4665
PyObject *
4666
PyImport_Import(PyObject *module_name)
4667
284k
{
4668
284k
    PyThreadState *tstate = _PyThreadState_GET();
4669
284k
    PyObject *globals = NULL;
4670
284k
    PyObject *import = NULL;
4671
284k
    PyObject *builtins = NULL;
4672
284k
    PyObject *r = NULL;
4673
4674
284k
    PyObject *from_list = PyList_New(0);
4675
284k
    if (from_list == NULL) {
4676
0
        goto err;
4677
0
    }
4678
4679
    /* Get the builtins from current globals */
4680
284k
    globals = PyEval_GetGlobals();  // borrowed
4681
284k
    if (globals != NULL) {
4682
284k
        Py_INCREF(globals);
4683
        // XXX Use _PyEval_EnsureBuiltins()?
4684
284k
        builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
4685
284k
        if (builtins == NULL) {
4686
            // XXX Fall back to interp->builtins or sys.modules['builtins']?
4687
0
            goto err;
4688
0
        }
4689
284k
    }
4690
296
    else if (_PyErr_Occurred(tstate)) {
4691
0
        goto err;
4692
0
    }
4693
296
    else {
4694
        /* No globals -- use standard builtins, and fake globals */
4695
296
        globals = PyDict_New();
4696
296
        if (globals == NULL) {
4697
0
            goto err;
4698
0
        }
4699
296
        if (_PyEval_EnsureBuiltinsWithModule(tstate, globals, &builtins) < 0) {
4700
0
            goto err;
4701
0
        }
4702
296
    }
4703
4704
    /* Get the __import__ function from the builtins */
4705
284k
    if (PyDict_Check(builtins)) {
4706
284k
        import = PyObject_GetItem(builtins, &_Py_ID(__import__));
4707
284k
        if (import == NULL) {
4708
0
            _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
4709
0
        }
4710
284k
    }
4711
296
    else
4712
296
        import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
4713
284k
    if (import == NULL)
4714
0
        goto err;
4715
4716
    /* Call the __import__ function with the proper argument list
4717
       Always use absolute import here.
4718
       Calling for side-effect of import. */
4719
284k
    r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
4720
284k
                              globals, from_list, 0, NULL);
4721
284k
    if (r == NULL)
4722
0
        goto err;
4723
284k
    Py_DECREF(r);
4724
4725
284k
    r = import_get_module(tstate, module_name);
4726
284k
    if (r == NULL && !_PyErr_Occurred(tstate)) {
4727
0
        _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
4728
0
    }
4729
4730
284k
  err:
4731
284k
    Py_XDECREF(globals);
4732
284k
    Py_XDECREF(builtins);
4733
284k
    Py_XDECREF(import);
4734
284k
    Py_XDECREF(from_list);
4735
4736
284k
    return r;
4737
284k
}
4738
4739
4740
/*********************/
4741
/* runtime lifecycle */
4742
/*********************/
4743
4744
PyStatus
4745
_PyImport_Init(void)
4746
37
{
4747
37
    if (INITTAB != NULL) {
4748
0
        return _PyStatus_ERR("global import state already initialized");
4749
0
    }
4750
37
    if (init_builtin_modules_table() != 0) {
4751
0
        return PyStatus_NoMemory();
4752
0
    }
4753
37
    return _PyStatus_OK();
4754
37
}
4755
4756
void
4757
_PyImport_Fini(void)
4758
0
{
4759
    /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
4760
    // XXX Should we actually leave them (mostly) intact, since we don't
4761
    // ever dlclose() the module files?
4762
0
    _extensions_cache_clear_all();
4763
4764
    /* Free memory allocated by _PyImport_Init() */
4765
0
    fini_builtin_modules_table();
4766
0
}
4767
4768
void
4769
_PyImport_Fini2(void)
4770
0
{
4771
    // Reset PyImport_Inittab
4772
0
    PyImport_Inittab = _PyImport_Inittab;
4773
4774
    /* Free memory allocated by PyImport_ExtendInittab() */
4775
0
    _PyMem_DefaultRawFree(inittab_copy);
4776
0
    inittab_copy = NULL;
4777
0
}
4778
4779
4780
/*************************/
4781
/* interpreter lifecycle */
4782
/*************************/
4783
4784
PyStatus
4785
_PyImport_InitCore(PyThreadState *tstate, PyObject *sysmod, int importlib)
4786
37
{
4787
    // XXX Initialize here: interp->modules and interp->import_func.
4788
    // XXX Initialize here: sys.modules and sys.meta_path.
4789
4790
37
    if (importlib) {
4791
        /* This call sets up builtin and frozen import support */
4792
37
        if (init_importlib(tstate, sysmod) < 0) {
4793
0
            return _PyStatus_ERR("failed to initialize importlib");
4794
0
        }
4795
37
    }
4796
4797
37
    return _PyStatus_OK();
4798
37
}
4799
4800
/* In some corner cases it is important to be sure that the import
4801
   machinery has been initialized (or not cleaned up yet).  For
4802
   example, see issue #4236 and PyModule_Create2(). */
4803
4804
int
4805
_PyImport_IsInitialized(PyInterpreterState *interp)
4806
0
{
4807
0
    if (MODULES(interp) == NULL)
4808
0
        return 0;
4809
0
    return 1;
4810
0
}
4811
4812
/* Clear the direct per-interpreter import state, if not cleared already. */
4813
void
4814
_PyImport_ClearCore(PyInterpreterState *interp)
4815
0
{
4816
    /* interp->modules should have been cleaned up and cleared already
4817
       by _PyImport_FiniCore(). */
4818
0
    Py_CLEAR(MODULES(interp));
4819
0
    Py_CLEAR(MODULES_BY_INDEX(interp));
4820
0
    Py_CLEAR(IMPORTLIB(interp));
4821
0
    Py_CLEAR(IMPORT_FUNC(interp));
4822
0
    Py_CLEAR(LAZY_IMPORT_FUNC(interp));
4823
0
    Py_CLEAR(interp->imports.lazy_pending_submodules);
4824
0
    Py_CLEAR(interp->imports.lazy_modules);
4825
0
    Py_CLEAR(interp->imports.lazy_importing_modules);
4826
0
    Py_CLEAR(interp->imports.lazy_imports_filter);
4827
0
}
4828
4829
void
4830
_PyImport_FiniCore(PyInterpreterState *interp)
4831
0
{
4832
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4833
4834
0
    if (_PySys_ClearAttrString(interp, "meta_path", verbose) < 0) {
4835
0
        PyErr_FormatUnraisable("Exception ignored while "
4836
0
                               "clearing sys.meta_path");
4837
0
    }
4838
4839
    // XXX Pull in most of finalize_modules() in pylifecycle.c.
4840
4841
0
    if (_PySys_ClearAttrString(interp, "modules", verbose) < 0) {
4842
0
        PyErr_FormatUnraisable("Exception ignored while "
4843
0
                               "clearing sys.modules");
4844
0
    }
4845
4846
0
    _PyImport_ClearCore(interp);
4847
0
}
4848
4849
// XXX Add something like _PyImport_Disable() for use early in interp fini?
4850
4851
4852
/* "external" imports */
4853
4854
static int
4855
init_zipimport(PyThreadState *tstate, int verbose)
4856
37
{
4857
37
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
4858
37
    if (path_hooks == NULL) {
4859
0
        return -1;
4860
0
    }
4861
4862
37
    if (verbose) {
4863
0
        PySys_WriteStderr("# installing zipimport hook\n");
4864
0
    }
4865
4866
37
    PyObject *zipimporter = PyImport_ImportModuleAttrString("zipimport", "zipimporter");
4867
37
    if (zipimporter == NULL) {
4868
0
        _PyErr_Clear(tstate); /* No zipimporter object -- okay */
4869
0
        if (verbose) {
4870
0
            PySys_WriteStderr("# can't import zipimport.zipimporter\n");
4871
0
        }
4872
0
    }
4873
37
    else {
4874
        /* sys.path_hooks.insert(0, zipimporter) */
4875
37
        int err = PyList_Insert(path_hooks, 0, zipimporter);
4876
37
        Py_DECREF(zipimporter);
4877
37
        if (err < 0) {
4878
0
            Py_DECREF(path_hooks);
4879
0
            return -1;
4880
0
        }
4881
37
        if (verbose) {
4882
0
            PySys_WriteStderr("# installed zipimport hook\n");
4883
0
        }
4884
37
    }
4885
37
    Py_DECREF(path_hooks);
4886
4887
37
    return 0;
4888
37
}
4889
4890
PyStatus
4891
_PyImport_InitExternal(PyThreadState *tstate)
4892
37
{
4893
37
    int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
4894
4895
    // XXX Initialize here: sys.path_hooks and sys.path_importer_cache.
4896
4897
37
    if (init_importlib_external(tstate->interp) != 0) {
4898
0
        _PyErr_Print(tstate);
4899
0
        return _PyStatus_ERR("external importer setup failed");
4900
0
    }
4901
4902
37
    if (init_zipimport(tstate, verbose) != 0) {
4903
0
        PyErr_Print();
4904
0
        return _PyStatus_ERR("initializing zipimport failed");
4905
0
    }
4906
4907
37
    return _PyStatus_OK();
4908
37
}
4909
4910
void
4911
_PyImport_FiniExternal(PyInterpreterState *interp)
4912
0
{
4913
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4914
4915
    // XXX Uninstall importlib metapath importers here?
4916
4917
0
    if (_PySys_ClearAttrString(interp, "path_importer_cache", verbose) < 0) {
4918
0
        PyErr_FormatUnraisable("Exception ignored while "
4919
0
                               "clearing sys.path_importer_cache");
4920
0
    }
4921
0
    if (_PySys_ClearAttrString(interp, "path_hooks", verbose) < 0) {
4922
0
        PyErr_FormatUnraisable("Exception ignored while "
4923
0
                               "clearing sys.path_hooks");
4924
0
    }
4925
0
}
4926
4927
4928
/******************/
4929
/* module helpers */
4930
/******************/
4931
4932
PyObject *
4933
PyImport_ImportModuleAttr(PyObject *modname, PyObject *attrname)
4934
23.0k
{
4935
23.0k
    PyObject *mod = PyImport_Import(modname);
4936
23.0k
    if (mod == NULL) {
4937
0
        return NULL;
4938
0
    }
4939
23.0k
    PyObject *result = PyObject_GetAttr(mod, attrname);
4940
23.0k
    Py_DECREF(mod);
4941
23.0k
    return result;
4942
23.0k
}
4943
4944
PyObject *
4945
PyImport_ImportModuleAttrString(const char *modname, const char *attrname)
4946
20.7k
{
4947
20.7k
    PyObject *pmodname = PyUnicode_FromString(modname);
4948
20.7k
    if (pmodname == NULL) {
4949
0
        return NULL;
4950
0
    }
4951
20.7k
    PyObject *pattrname = PyUnicode_FromString(attrname);
4952
20.7k
    if (pattrname == NULL) {
4953
0
        Py_DECREF(pmodname);
4954
0
        return NULL;
4955
0
    }
4956
20.7k
    PyObject *result = PyImport_ImportModuleAttr(pmodname, pattrname);
4957
20.7k
    Py_DECREF(pattrname);
4958
20.7k
    Py_DECREF(pmodname);
4959
20.7k
    return result;
4960
20.7k
}
4961
4962
int
4963
PyImport_SetLazyImportsFilter(PyObject *filter)
4964
0
{
4965
0
    if (filter == Py_None) {
4966
0
        filter = NULL;
4967
0
    }
4968
0
    if (filter != NULL && !PyCallable_Check(filter)) {
4969
0
        PyErr_SetString(PyExc_ValueError,
4970
0
                        "filter provided but is not callable");
4971
0
        return -1;
4972
0
    }
4973
4974
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4975
    // Exchange the filter w/ the lock held. We can't use Py_XSETREF
4976
    // because we need to release the lock before the decref.
4977
0
    LAZY_IMPORTS_LOCK(interp);
4978
0
    PyObject *old = LAZY_IMPORTS_FILTER(interp);
4979
0
    LAZY_IMPORTS_FILTER(interp) = Py_XNewRef(filter);
4980
0
    LAZY_IMPORTS_UNLOCK(interp);
4981
0
    Py_XDECREF(old);
4982
0
    return 0;
4983
0
}
4984
4985
/* Return a strong reference to the current lazy imports filter
4986
 * or NULL if none exists. This function always succeeds.
4987
 */
4988
PyObject *
4989
PyImport_GetLazyImportsFilter(void)
4990
0
{
4991
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4992
0
    LAZY_IMPORTS_LOCK(interp);
4993
0
    PyObject *res = Py_XNewRef(LAZY_IMPORTS_FILTER(interp));
4994
0
    LAZY_IMPORTS_UNLOCK(interp);
4995
0
    return res;
4996
0
}
4997
4998
int
4999
PyImport_SetLazyImportsMode(PyImport_LazyImportsMode mode)
5000
0
{
5001
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
5002
0
    FT_ATOMIC_STORE_INT_RELAXED(LAZY_IMPORTS_MODE(interp), mode);
5003
0
    return 0;
5004
0
}
5005
5006
/* Checks if lazy imports is globally enabled or disabled. Return 1 when
5007
 * globally forced on, 0 when globally forced off, or -1 when not set.*/
5008
PyImport_LazyImportsMode
5009
PyImport_GetLazyImportsMode(void)
5010
16.0k
{
5011
16.0k
    PyInterpreterState *interp = _PyInterpreterState_GET();
5012
16.0k
    return FT_ATOMIC_LOAD_INT_RELAXED(LAZY_IMPORTS_MODE(interp));
5013
16.0k
}
5014
5015
/**************/
5016
/* the module */
5017
/**************/
5018
5019
/*[clinic input]
5020
_imp.lock_held
5021
5022
Return True if the import lock is currently held, else False.
5023
5024
On platforms without threads, return False.
5025
[clinic start generated code]*/
5026
5027
static PyObject *
5028
_imp_lock_held_impl(PyObject *module)
5029
/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
5030
0
{
5031
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
5032
0
    return PyBool_FromLong(PyMutex_IsLocked(&IMPORT_LOCK(interp).mutex));
5033
0
}
5034
5035
/*[clinic input]
5036
_imp.acquire_lock
5037
5038
Acquires the interpreter's import lock for the current thread.
5039
5040
This lock should be used by import hooks to ensure thread-safety when
5041
importing modules.  On platforms without threads, this function does
5042
nothing.
5043
[clinic start generated code]*/
5044
5045
static PyObject *
5046
_imp_acquire_lock_impl(PyObject *module)
5047
/*[clinic end generated code: output=1aff58cb0ee1b026 input=60e9c1b4ab471ead]*/
5048
68.4k
{
5049
68.4k
    PyInterpreterState *interp = _PyInterpreterState_GET();
5050
68.4k
    _PyImport_AcquireLock(interp);
5051
68.4k
    Py_RETURN_NONE;
5052
68.4k
}
5053
5054
/*[clinic input]
5055
_imp.release_lock
5056
5057
Release the interpreter's import lock.
5058
5059
On platforms without threads, this function does nothing.
5060
[clinic start generated code]*/
5061
5062
static PyObject *
5063
_imp_release_lock_impl(PyObject *module)
5064
/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
5065
68.4k
{
5066
68.4k
    PyInterpreterState *interp = _PyInterpreterState_GET();
5067
68.4k
    if (!_PyRecursiveMutex_IsLockedByCurrentThread(&IMPORT_LOCK(interp))) {
5068
0
        PyErr_SetString(PyExc_RuntimeError,
5069
0
                        "not holding the import lock");
5070
0
        return NULL;
5071
0
    }
5072
68.4k
    _PyImport_ReleaseLock(interp);
5073
68.4k
    Py_RETURN_NONE;
5074
68.4k
}
5075
5076
5077
/*[clinic input]
5078
_imp._fix_co_filename
5079
5080
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
5081
        Code object to change.
5082
5083
    path: unicode
5084
        File path to use.
5085
    /
5086
5087
Changes code.co_filename to specify the passed-in file path.
5088
[clinic start generated code]*/
5089
5090
static PyObject *
5091
_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
5092
                           PyObject *path)
5093
/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
5094
5095
6.18k
{
5096
6.18k
    update_compiled_module(code, path);
5097
5098
6.18k
    Py_RETURN_NONE;
5099
6.18k
}
5100
5101
5102
/*[clinic input]
5103
_imp.create_builtin
5104
5105
    spec: object
5106
    /
5107
5108
Create an extension module.
5109
[clinic start generated code]*/
5110
5111
static PyObject *
5112
_imp_create_builtin(PyObject *module, PyObject *spec)
5113
/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
5114
724
{
5115
724
    PyThreadState *tstate = _PyThreadState_GET();
5116
5117
724
    PyObject *name = PyObject_GetAttrString(spec, "name");
5118
724
    if (name == NULL) {
5119
0
        return NULL;
5120
0
    }
5121
5122
724
    if (!PyUnicode_Check(name)) {
5123
0
        PyErr_Format(PyExc_TypeError,
5124
0
                     "name must be string, not %.200s",
5125
0
                     Py_TYPE(name)->tp_name);
5126
0
        Py_DECREF(name);
5127
0
        return NULL;
5128
0
    }
5129
5130
724
    if (PyUnicode_GetLength(name) == 0) {
5131
0
        PyErr_Format(PyExc_ValueError, "name must not be empty");
5132
0
        Py_DECREF(name);
5133
0
        return NULL;
5134
0
    }
5135
5136
724
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
5137
724
    Py_DECREF(name);
5138
724
    return mod;
5139
724
}
5140
5141
5142
/*[clinic input]
5143
_imp.extension_suffixes
5144
5145
Returns the list of file suffixes used to identify extension modules.
5146
[clinic start generated code]*/
5147
5148
static PyObject *
5149
_imp_extension_suffixes_impl(PyObject *module)
5150
/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
5151
74
{
5152
74
    PyObject *list;
5153
5154
74
    list = PyList_New(0);
5155
74
    if (list == NULL)
5156
0
        return NULL;
5157
74
#ifdef HAVE_DYNAMIC_LOADING
5158
74
    const char *suffix;
5159
74
    unsigned int index = 0;
5160
5161
370
    while ((suffix = _PyImport_DynLoadFiletab[index])) {
5162
296
        PyObject *item = PyUnicode_FromString(suffix);
5163
296
        if (item == NULL) {
5164
0
            Py_DECREF(list);
5165
0
            return NULL;
5166
0
        }
5167
296
        if (PyList_Append(list, item) < 0) {
5168
0
            Py_DECREF(list);
5169
0
            Py_DECREF(item);
5170
0
            return NULL;
5171
0
        }
5172
296
        Py_DECREF(item);
5173
296
        index += 1;
5174
296
    }
5175
74
#endif
5176
74
    return list;
5177
74
}
5178
5179
/*[clinic input]
5180
_imp.init_frozen
5181
5182
    name: unicode
5183
    /
5184
5185
Initializes a frozen module.
5186
[clinic start generated code]*/
5187
5188
static PyObject *
5189
_imp_init_frozen_impl(PyObject *module, PyObject *name)
5190
/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
5191
0
{
5192
0
    PyThreadState *tstate = _PyThreadState_GET();
5193
0
    int ret;
5194
5195
0
    ret = PyImport_ImportFrozenModuleObject(name);
5196
0
    if (ret < 0)
5197
0
        return NULL;
5198
0
    if (ret == 0) {
5199
0
        Py_RETURN_NONE;
5200
0
    }
5201
0
    return import_add_module(tstate, name);
5202
0
}
5203
5204
/*[clinic input]
5205
@permit_long_summary
5206
_imp.find_frozen
5207
5208
    name: unicode
5209
    /
5210
    *
5211
    withdata: bool = False
5212
5213
Return info about the corresponding frozen module (if there is one) or None.
5214
5215
The returned info (a 2-tuple):
5216
5217
 * data         the raw marshalled bytes
5218
 * is_package   whether or not it is a package
5219
 * origname     the originally frozen module's name, or None if not
5220
                a stdlib module (this will usually be the same as
5221
                the module's current name)
5222
[clinic start generated code]*/
5223
5224
static PyObject *
5225
_imp_find_frozen_impl(PyObject *module, PyObject *name, int withdata)
5226
/*[clinic end generated code: output=8c1c3c7f925397a5 input=30a7a50da49eca97]*/
5227
12.9k
{
5228
12.9k
    struct frozen_info info;
5229
12.9k
    frozen_status status = find_frozen(name, &info);
5230
12.9k
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
5231
12.3k
        Py_RETURN_NONE;
5232
12.3k
    }
5233
574
    else if (status == FROZEN_BAD_NAME) {
5234
0
        Py_RETURN_NONE;
5235
0
    }
5236
574
    else if (status != FROZEN_OKAY) {
5237
0
        set_frozen_error(status, name);
5238
0
        return NULL;
5239
0
    }
5240
5241
574
    PyObject *data = NULL;
5242
574
    if (withdata) {
5243
0
        data = PyMemoryView_FromMemory((char *)info.data, info.size, PyBUF_READ);
5244
0
        if (data == NULL) {
5245
0
            return NULL;
5246
0
        }
5247
0
    }
5248
5249
574
    PyObject *origname = NULL;
5250
574
    if (info.origname != NULL && info.origname[0] != '\0') {
5251
574
        origname = PyUnicode_FromString(info.origname);
5252
574
        if (origname == NULL) {
5253
0
            Py_XDECREF(data);
5254
0
            return NULL;
5255
0
        }
5256
574
    }
5257
5258
574
    PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
5259
574
                                    info.is_package ? Py_True : Py_False,
5260
574
                                    origname ? origname : Py_None);
5261
574
    Py_XDECREF(origname);
5262
574
    Py_XDECREF(data);
5263
574
    return result;
5264
574
}
5265
5266
/*[clinic input]
5267
_imp.get_frozen_object
5268
5269
    name: unicode
5270
    data as dataobj: object = None
5271
    /
5272
5273
Create a code object for a frozen module.
5274
[clinic start generated code]*/
5275
5276
static PyObject *
5277
_imp_get_frozen_object_impl(PyObject *module, PyObject *name,
5278
                            PyObject *dataobj)
5279
/*[clinic end generated code: output=54368a673a35e745 input=034bdb88f6460b7b]*/
5280
574
{
5281
574
    struct frozen_info info = {0};
5282
574
    Py_buffer buf = {0};
5283
574
    if (PyObject_CheckBuffer(dataobj)) {
5284
0
        if (PyObject_GetBuffer(dataobj, &buf, PyBUF_SIMPLE) != 0) {
5285
0
            return NULL;
5286
0
        }
5287
0
        info.data = (const char *)buf.buf;
5288
0
        info.size = buf.len;
5289
0
    }
5290
574
    else if (dataobj != Py_None) {
5291
0
        _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
5292
0
        return NULL;
5293
0
    }
5294
574
    else {
5295
574
        frozen_status status = find_frozen(name, &info);
5296
574
        if (status != FROZEN_OKAY) {
5297
0
            set_frozen_error(status, name);
5298
0
            return NULL;
5299
0
        }
5300
574
    }
5301
5302
574
    if (info.nameobj == NULL) {
5303
0
        info.nameobj = name;
5304
0
    }
5305
574
    if (info.size == 0) {
5306
        /* Does not contain executable code. */
5307
0
        set_frozen_error(FROZEN_INVALID, name);
5308
0
        return NULL;
5309
0
    }
5310
5311
574
    PyInterpreterState *interp = _PyInterpreterState_GET();
5312
574
    PyObject *codeobj = unmarshal_frozen_code(interp, &info);
5313
574
    if (dataobj != Py_None) {
5314
0
        PyBuffer_Release(&buf);
5315
0
    }
5316
574
    return codeobj;
5317
574
}
5318
5319
/*[clinic input]
5320
_imp.is_frozen_package
5321
5322
    name: unicode
5323
    /
5324
5325
Returns True if the module name is of a frozen package.
5326
[clinic start generated code]*/
5327
5328
static PyObject *
5329
_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
5330
/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
5331
37
{
5332
37
    struct frozen_info info;
5333
37
    frozen_status status = find_frozen(name, &info);
5334
37
    if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
5335
0
        set_frozen_error(status, name);
5336
0
        return NULL;
5337
0
    }
5338
37
    return PyBool_FromLong(info.is_package);
5339
37
}
5340
5341
/*[clinic input]
5342
_imp.is_builtin
5343
5344
    name: unicode
5345
    /
5346
5347
Returns True if the module name corresponds to a built-in module.
5348
[clinic start generated code]*/
5349
5350
static PyObject *
5351
_imp_is_builtin_impl(PyObject *module, PyObject *name)
5352
/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
5353
13.6k
{
5354
13.6k
    return PyLong_FromLong(is_builtin(name));
5355
13.6k
}
5356
5357
/*[clinic input]
5358
_imp.is_frozen
5359
5360
    name: unicode
5361
    /
5362
5363
Returns True if the module name corresponds to a frozen module.
5364
[clinic start generated code]*/
5365
5366
static PyObject *
5367
_imp_is_frozen_impl(PyObject *module, PyObject *name)
5368
/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
5369
37
{
5370
37
    struct frozen_info info;
5371
37
    frozen_status status = find_frozen(name, &info);
5372
37
    if (status != FROZEN_OKAY) {
5373
0
        Py_RETURN_FALSE;
5374
0
    }
5375
37
    Py_RETURN_TRUE;
5376
37
}
5377
5378
/*[clinic input]
5379
_imp._frozen_module_names
5380
5381
Returns the list of available frozen modules.
5382
[clinic start generated code]*/
5383
5384
static PyObject *
5385
_imp__frozen_module_names_impl(PyObject *module)
5386
/*[clinic end generated code: output=80609ef6256310a8 input=76237fbfa94460d2]*/
5387
0
{
5388
0
    return list_frozen_module_names();
5389
0
}
5390
5391
/*[clinic input]
5392
_imp._override_frozen_modules_for_tests
5393
5394
    override: int
5395
    /
5396
5397
(internal-only) Override PyConfig.use_frozen_modules.
5398
5399
(-1: "off", 1: "on", 0: no override)
5400
See frozen_modules() in Lib/test/support/import_helper.py.
5401
[clinic start generated code]*/
5402
5403
static PyObject *
5404
_imp__override_frozen_modules_for_tests_impl(PyObject *module, int override)
5405
/*[clinic end generated code: output=36d5cb1594160811 input=8f1f95a3ef21aec3]*/
5406
0
{
5407
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
5408
0
    OVERRIDE_FROZEN_MODULES(interp) = override;
5409
0
    Py_RETURN_NONE;
5410
0
}
5411
5412
/*[clinic input]
5413
@permit_long_summary
5414
_imp._override_multi_interp_extensions_check
5415
5416
    override: int
5417
    /
5418
5419
(internal-only) Override PyInterpreterConfig.check_multi_interp_extensions.
5420
5421
(-1: "never", 1: "always", 0: no override)
5422
[clinic start generated code]*/
5423
5424
static PyObject *
5425
_imp__override_multi_interp_extensions_check_impl(PyObject *module,
5426
                                                  int override)
5427
/*[clinic end generated code: output=3ff043af52bbf280 input=24f23f8510a7f6e7]*/
5428
0
{
5429
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
5430
0
    if (_Py_IsMainInterpreter(interp)) {
5431
0
        PyErr_SetString(PyExc_RuntimeError,
5432
0
                        "_imp._override_multi_interp_extensions_check() "
5433
0
                        "cannot be used in the main interpreter");
5434
0
        return NULL;
5435
0
    }
5436
#ifdef Py_GIL_DISABLED
5437
    PyErr_SetString(PyExc_RuntimeError,
5438
                    "_imp._override_multi_interp_extensions_check() "
5439
                    "cannot be used in the free-threaded build");
5440
    return NULL;
5441
#else
5442
0
    int oldvalue = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
5443
0
    OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) = override;
5444
0
    return PyLong_FromLong(oldvalue);
5445
0
#endif
5446
0
}
5447
5448
#ifdef HAVE_DYNAMIC_LOADING
5449
5450
/*[clinic input]
5451
_imp.create_dynamic
5452
5453
    spec: object
5454
    file: object = NULL
5455
    /
5456
5457
Create an extension module.
5458
[clinic start generated code]*/
5459
5460
static PyObject *
5461
_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
5462
/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
5463
209
{
5464
209
    FILE *fp = NULL;
5465
209
    PyObject *mod = NULL;
5466
209
    PyThreadState *tstate = _PyThreadState_GET();
5467
5468
209
    struct _Py_ext_module_loader_info info;
5469
209
    if (_Py_ext_module_loader_info_init_from_spec(&info, spec) < 0) {
5470
0
        return NULL;
5471
0
    }
5472
5473
209
    struct extensions_cache_value *cached = NULL;
5474
209
    mod = import_find_extension(tstate, &info, &cached);
5475
209
    if (mod != NULL) {
5476
0
        assert(!_PyErr_Occurred(tstate));
5477
0
        assert(cached != NULL);
5478
        /* The module might not have md_def set in certain reload cases. */
5479
0
        assert(_PyModule_GetDefOrNull(mod) == NULL
5480
0
                || cached->def == _PyModule_GetDefOrNull(mod));
5481
0
        assert_singlephase(cached);
5482
0
        goto finally;
5483
0
    }
5484
209
    else if (_PyErr_Occurred(tstate)) {
5485
0
        goto finally;
5486
0
    }
5487
    /* Otherwise it must be multi-phase init or the first time it's loaded. */
5488
5489
    /* If the module was added to the global cache
5490
     * but def->m_base.m_copy was cleared (e.g. subinterp fini)
5491
     * then we have to do a little dance here. */
5492
209
    if (cached != NULL) {
5493
0
        assert(cached->def->m_base.m_copy == NULL);
5494
        /* For now we clear the cache and move on. */
5495
0
        _extensions_cache_delete(info.path, info.name);
5496
0
    }
5497
5498
209
    if (PySys_Audit("import", "OOOOO", info.name, info.filename,
5499
209
                    Py_None, Py_None, Py_None) < 0)
5500
0
    {
5501
0
        goto finally;
5502
0
    }
5503
5504
    /* We would move this (and the fclose() below) into
5505
     * _PyImport_GetModuleExportHooks(), but it isn't clear if the intervening
5506
     * code relies on fp still being open. */
5507
209
    if (file != NULL) {
5508
0
        fp = Py_fopen(info.filename, "r");
5509
0
        if (fp == NULL) {
5510
0
            goto finally;
5511
0
        }
5512
0
    }
5513
5514
209
    PyModInitFunction p0 = NULL;
5515
209
    PyModExportFunction ex0 = NULL;
5516
209
    _PyImport_GetModuleExportHooks(&info, fp, &p0, &ex0);
5517
209
    if (ex0) {
5518
0
        mod = import_run_modexport(tstate, ex0, &info, spec);
5519
        // Modules created from slots handle GIL enablement (Py_mod_gil slot)
5520
        // when they're created.
5521
0
        goto finally;
5522
0
    }
5523
209
    if (p0 == NULL) {
5524
4
        goto finally;
5525
4
    }
5526
5527
#ifdef Py_GIL_DISABLED
5528
    // This call (and the corresponding call to _PyImport_CheckGILForModule())
5529
    // would ideally be inside import_run_extension(). They are kept in the
5530
    // callers for now because that would complicate the control flow inside
5531
    // import_run_extension(). It should be possible to restructure
5532
    // import_run_extension() to address this.
5533
    _PyEval_EnableGILTransient(tstate);
5534
#endif
5535
205
    mod = import_run_extension(
5536
205
                    tstate, p0, &info, spec, get_modules_dict(tstate, true));
5537
#ifdef Py_GIL_DISABLED
5538
    if (_PyImport_CheckGILForModule(mod, info.name) < 0) {
5539
        Py_CLEAR(mod);
5540
        goto finally;
5541
    }
5542
#endif
5543
5544
209
finally:
5545
209
    if (fp != NULL) {
5546
0
        fclose(fp);
5547
0
    }
5548
209
    _Py_ext_module_loader_info_clear(&info);
5549
209
    return mod;
5550
205
}
5551
5552
/*[clinic input]
5553
_imp.exec_dynamic -> int
5554
5555
    mod: object
5556
    /
5557
5558
Initialize an extension module.
5559
[clinic start generated code]*/
5560
5561
static int
5562
_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
5563
/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
5564
205
{
5565
205
    return exec_builtin_or_dynamic(mod);
5566
205
}
5567
5568
5569
#endif /* HAVE_DYNAMIC_LOADING */
5570
5571
/*[clinic input]
5572
_imp.exec_builtin -> int
5573
5574
    mod: object
5575
    /
5576
5577
Initialize a built-in module.
5578
[clinic start generated code]*/
5579
5580
static int
5581
_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
5582
/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
5583
724
{
5584
724
    return exec_builtin_or_dynamic(mod);
5585
724
}
5586
5587
/*[clinic input]
5588
_imp.source_hash
5589
5590
    key: long
5591
    source: Py_buffer
5592
[clinic start generated code]*/
5593
5594
static PyObject *
5595
_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
5596
/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
5597
0
{
5598
0
    union {
5599
0
        uint64_t x;
5600
0
        char data[sizeof(uint64_t)];
5601
0
    } hash;
5602
0
    hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
5603
#if !PY_LITTLE_ENDIAN
5604
    // Force to little-endian. There really ought to be a succinct standard way
5605
    // to do this.
5606
    for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
5607
        char tmp = hash.data[i];
5608
        hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
5609
        hash.data[sizeof(hash.data) - i - 1] = tmp;
5610
    }
5611
#endif
5612
0
    return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
5613
0
}
5614
5615
static int
5616
publish_lazy_imports_on_module(PyThreadState *tstate,
5617
                               PyObject *lazy_submodules,
5618
                               PyObject *name,
5619
                               PyObject *module_dict)
5620
59
{
5621
59
    PyObject *builtins = _PyEval_GetBuiltins(tstate);
5622
59
    PyObject *attr_name;
5623
59
    Py_ssize_t pos = 0;
5624
59
    Py_hash_t hash;
5625
5626
    // Enumerate the set of lazy submodules which have been imported from the
5627
    // parent module.
5628
93
    while (_PySet_NextEntryRef(lazy_submodules, &pos, &attr_name, &hash)) {
5629
34
        if (_PyDict_Contains_KnownHash(module_dict, attr_name, hash)) {
5630
34
            Py_DECREF(attr_name);
5631
34
            continue;
5632
34
        }
5633
        // Create a new lazy module attr for the subpackage which was
5634
        // previously lazily imported.
5635
0
        PyObject *lazy_module_attr = _PyLazyImport_New(tstate->current_frame, builtins,
5636
0
                                                       name, attr_name);
5637
0
        if (lazy_module_attr == NULL) {
5638
0
            Py_DECREF(attr_name);
5639
0
            return -1;
5640
0
        }
5641
5642
        // Publish on the module that was just imported.
5643
0
        if (PyDict_SetItem(module_dict, attr_name,
5644
0
                           lazy_module_attr) < 0) {
5645
0
            Py_DECREF(lazy_module_attr);
5646
0
            Py_DECREF(attr_name);
5647
0
            return -1;
5648
0
        }
5649
0
        Py_DECREF(lazy_module_attr);
5650
0
        Py_DECREF(attr_name);
5651
0
    }
5652
59
    return 0;
5653
59
}
5654
5655
/*[clinic input]
5656
_imp._set_lazy_attributes
5657
    modobj: object
5658
    name: unicode
5659
    /
5660
Sets attributes to lazy submodules on the module, as side effects.
5661
[clinic start generated code]*/
5662
5663
static PyObject *
5664
_imp__set_lazy_attributes_impl(PyObject *module, PyObject *modobj,
5665
                               PyObject *name)
5666
/*[clinic end generated code: output=3369bb3242b1f043 input=38ea6f30956dd7d6]*/
5667
3.37k
{
5668
3.37k
    PyThreadState *tstate = _PyThreadState_GET();
5669
3.37k
    PyObject *module_dict = NULL;
5670
3.37k
    PyObject *ret = NULL;
5671
3.37k
    PyObject *lazy_pending_modules = LAZY_PENDING_SUBMODULES(tstate->interp);
5672
3.37k
    assert(lazy_pending_modules != NULL);
5673
5674
3.37k
    PyObject *lazy_submodules;
5675
3.37k
    if (PySet_Discard(LAZY_MODULES(tstate->interp), name) < 0) {
5676
0
        return NULL;
5677
3.37k
    } else if (PyDict_GetItemRef(lazy_pending_modules, name, &lazy_submodules) < 0) {
5678
0
        return NULL;
5679
0
    }
5680
3.37k
    else if (lazy_submodules == NULL) {
5681
3.31k
        Py_RETURN_NONE;
5682
3.31k
    }
5683
5684
59
    module_dict = get_mod_dict(modobj);
5685
59
    if (module_dict == NULL || !PyDict_CheckExact(module_dict)) {
5686
0
        Py_DECREF(lazy_submodules);
5687
0
        goto done;
5688
0
    }
5689
5690
59
    assert(PyAnySet_CheckExact(lazy_submodules));
5691
59
    Py_BEGIN_CRITICAL_SECTION(lazy_submodules);
5692
59
    publish_lazy_imports_on_module(tstate, lazy_submodules, name, module_dict);
5693
59
    Py_END_CRITICAL_SECTION();
5694
59
    Py_DECREF(lazy_submodules);
5695
5696
59
    if (PyDict_DelItem(lazy_pending_modules, name) < 0) {
5697
0
        goto error;
5698
0
    }
5699
5700
59
done:
5701
59
    ret = Py_NewRef(Py_None);
5702
5703
59
error:
5704
59
    Py_XDECREF(module_dict);
5705
59
    return ret;
5706
59
}
5707
5708
PyDoc_STRVAR(doc_imp,
5709
"(Extremely) low-level import machinery bits as used by importlib.");
5710
5711
static PyMethodDef imp_methods[] = {
5712
    _IMP_EXTENSION_SUFFIXES_METHODDEF
5713
    _IMP_LOCK_HELD_METHODDEF
5714
    _IMP_ACQUIRE_LOCK_METHODDEF
5715
    _IMP_RELEASE_LOCK_METHODDEF
5716
    _IMP_FIND_FROZEN_METHODDEF
5717
    _IMP_GET_FROZEN_OBJECT_METHODDEF
5718
    _IMP_IS_FROZEN_PACKAGE_METHODDEF
5719
    _IMP_CREATE_BUILTIN_METHODDEF
5720
    _IMP_INIT_FROZEN_METHODDEF
5721
    _IMP_IS_BUILTIN_METHODDEF
5722
    _IMP_IS_FROZEN_METHODDEF
5723
    _IMP__FROZEN_MODULE_NAMES_METHODDEF
5724
    _IMP__OVERRIDE_FROZEN_MODULES_FOR_TESTS_METHODDEF
5725
    _IMP__OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK_METHODDEF
5726
    _IMP_CREATE_DYNAMIC_METHODDEF
5727
    _IMP_EXEC_DYNAMIC_METHODDEF
5728
    _IMP_EXEC_BUILTIN_METHODDEF
5729
    _IMP__FIX_CO_FILENAME_METHODDEF
5730
    _IMP_SOURCE_HASH_METHODDEF
5731
    _IMP__SET_LAZY_ATTRIBUTES_METHODDEF
5732
    {NULL, NULL}  /* sentinel */
5733
};
5734
5735
5736
static int
5737
imp_module_exec(PyObject *module)
5738
37
{
5739
37
    const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
5740
37
    PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
5741
37
    if (PyModule_Add(module, "check_hash_based_pycs", pyc_mode) < 0) {
5742
0
        return -1;
5743
0
    }
5744
5745
37
    if (PyModule_AddIntConstant(
5746
37
            module, "pyc_magic_number_token", PYC_MAGIC_NUMBER_TOKEN) < 0)
5747
0
    {
5748
0
        return -1;
5749
0
    }
5750
5751
37
    return 0;
5752
37
}
5753
5754
5755
static PyModuleDef_Slot imp_slots[] = {
5756
     _Py_ABI_SLOT,
5757
    {Py_mod_exec, imp_module_exec},
5758
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
5759
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
5760
    {0, NULL}
5761
};
5762
5763
static struct PyModuleDef imp_module = {
5764
    PyModuleDef_HEAD_INIT,
5765
    .m_name = "_imp",
5766
    .m_doc = doc_imp,
5767
    .m_size = 0,
5768
    .m_methods = imp_methods,
5769
    .m_slots = imp_slots,
5770
};
5771
5772
PyMODINIT_FUNC
5773
PyInit__imp(void)
5774
37
{
5775
37
    return PyModuleDef_Init(&imp_module);
5776
37
}