Coverage Report

Created: 2026-02-26 06:53

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