Coverage Report

Created: 2026-12-01 06:09

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