Coverage Report

Created: 2026-03-08 06:40

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
16.5k
#define INITTAB _PyRuntime.imports.inittab
81
1.08k
#define LAST_MODULE_INDEX _PyRuntime.imports.last_module_index
82
2.33k
#define EXTENSIONS _PyRuntime.imports.extensions
83
84
#define PKGCONTEXT (_PyRuntime.imports.pkgcontext)
85
86
87
/*******************************/
88
/* interpreter import state */
89
/*******************************/
90
91
#define MODULES(interp) \
92
10.0M
    (interp)->imports.modules
93
#define MODULES_BY_INDEX(interp) \
94
374
    (interp)->imports.modules_by_index
95
#define LAZY_MODULES(interp) \
96
3.53k
    (interp)->imports.lazy_modules
97
#define IMPORTLIB(interp) \
98
27.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
15.3k
    (interp)->imports.override_frozen_modules
103
#ifdef HAVE_DLOPEN
104
#  define DLOPENFLAGS(interp) \
105
450
        (interp)->imports.dlopenflags
106
#endif
107
#define IMPORT_FUNC(interp) \
108
3.73M
    (interp)->imports.import_func
109
110
#define LAZY_IMPORT_FUNC(interp) \
111
106
    (interp)->imports.lazy_import_func
112
113
#define IMPORT_LOCK(interp) \
114
234k
    (interp)->imports.lock
115
116
#define FIND_AND_LOAD(interp) \
117
15.6k
    (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
78.1k
{
155
78.1k
    _PyRecursiveMutex_Lock(&IMPORT_LOCK(interp));
156
78.1k
}
157
158
void
159
_PyImport_ReleaseLock(PyInterpreterState *interp)
160
78.1k
{
161
78.1k
    _PyRecursiveMutex_Unlock(&IMPORT_LOCK(interp));
162
78.1k
}
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
34
{
179
34
    assert(MODULES(interp) == NULL);
180
34
    MODULES(interp) = PyDict_New();
181
34
    if (MODULES(interp) == NULL) {
182
0
        return NULL;
183
0
    }
184
34
    return MODULES(interp);
185
34
}
186
187
PyObject *
188
_PyImport_GetModules(PyInterpreterState *interp)
189
635k
{
190
635k
    return MODULES(interp);
191
635k
}
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
9.43M
{
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
9.43M
    PyObject *modules = MODULES(tstate->interp);
222
9.43M
    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
9.43M
    return modules;
231
9.43M
}
232
233
PyObject *
234
PyImport_GetModuleDict(void)
235
0
{
236
0
    PyThreadState *tstate = _PyThreadState_GET();
237
0
    return get_modules_dict(tstate, true);
238
0
}
239
240
int
241
_PyImport_SetModule(PyObject *name, PyObject *m)
242
8
{
243
8
    PyThreadState *tstate = _PyThreadState_GET();
244
8
    PyObject *modules = get_modules_dict(tstate, true);
245
8
    return PyObject_SetItem(modules, name, m);
246
8
}
247
248
int
249
_PyImport_SetModuleString(const char *name, PyObject *m)
250
48
{
251
48
    PyThreadState *tstate = _PyThreadState_GET();
252
48
    PyObject *modules = get_modules_dict(tstate, true);
253
48
    return PyMapping_SetItemString(modules, name, m);
254
48
}
255
256
static PyObject *
257
import_get_module(PyThreadState *tstate, PyObject *name)
258
9.43M
{
259
9.43M
    PyObject *modules = get_modules_dict(tstate, false);
260
9.43M
    if (modules == NULL) {
261
0
        return NULL;
262
0
    }
263
264
9.43M
    PyObject *m;
265
9.43M
    Py_INCREF(modules);
266
9.43M
    (void)PyMapping_GetOptionalItem(modules, name, &m);
267
9.43M
    Py_DECREF(modules);
268
9.43M
    return m;
269
9.43M
}
270
271
PyObject *
272
_PyImport_InitLazyModules(PyInterpreterState *interp)
273
34
{
274
34
    assert(LAZY_MODULES(interp) == NULL);
275
34
    LAZY_MODULES(interp) = PyDict_New();
276
34
    return LAZY_MODULES(interp);
277
34
}
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
4.58M
{
288
4.58M
    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
4.58M
    int rc = PyObject_GetOptionalAttr(mod, &_Py_ID(__spec__), &spec);
296
4.58M
    if (rc > 0) {
297
4.58M
        rc = _PyModuleSpec_IsInitializing(spec);
298
4.58M
        Py_DECREF(spec);
299
4.58M
    }
300
4.58M
    if (rc == 0) {
301
4.58M
        goto done;
302
4.58M
    }
303
1.56k
    else if (rc < 0) {
304
0
        return rc;
305
0
    }
306
307
    /* Wait until module is done importing. */
308
1.56k
    PyObject *value = PyObject_CallMethodOneArg(
309
1.56k
        IMPORTLIB(interp), &_Py_ID(_lock_unlock_module), name);
310
1.56k
    if (value == NULL) {
311
0
        return -1;
312
0
    }
313
1.56k
    Py_DECREF(value);
314
315
4.58M
done:
316
    /* When -X importtime=2, print an import time entry even if an
317
       imported module has already been loaded.
318
     */
319
4.58M
    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
4.58M
    return 0;
328
1.56k
}
329
330
static void remove_importlib_frames(PyThreadState *tstate);
331
332
PyObject *
333
PyImport_GetModule(PyObject *name)
334
642k
{
335
642k
    PyThreadState *tstate = _PyThreadState_GET();
336
642k
    PyObject *mod;
337
338
642k
    mod = import_get_module(tstate, name);
339
642k
    if (mod != NULL && mod != Py_None) {
340
642k
        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
642k
        PyObject *mod_check = import_get_module(tstate, name);
347
642k
        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
642k
        Py_DECREF(mod_check);
360
642k
    }
361
642k
    return mod;
362
363
0
error:
364
0
    Py_DECREF(mod);
365
0
    remove_importlib_frames(tstate);
366
0
    return NULL;
367
642k
}
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
170
{
376
170
    PyObject *m;
377
170
    if (PyMapping_GetOptionalItem(modules, name, &m) < 0) {
378
0
        return NULL;
379
0
    }
380
170
    if (m != NULL && PyModule_Check(m)) {
381
102
        return m;
382
102
    }
383
68
    Py_XDECREF(m);
384
68
    m = PyModule_NewObject(name);
385
68
    if (m == NULL)
386
0
        return NULL;
387
68
    if (PyObject_SetItem(modules, name, m) != 0) {
388
0
        Py_DECREF(m);
389
0
        return NULL;
390
0
    }
391
392
68
    return m;
393
68
}
394
395
static PyObject *
396
import_add_module(PyThreadState *tstate, PyObject *name)
397
170
{
398
170
    PyObject *modules = get_modules_dict(tstate, false);
399
170
    if (modules == NULL) {
400
0
        return NULL;
401
0
    }
402
403
170
    PyObject *m;
404
170
    Py_BEGIN_CRITICAL_SECTION(modules);
405
170
    m = import_add_module_lock_held(modules, name);
406
170
    Py_END_CRITICAL_SECTION();
407
170
    return m;
408
170
}
409
410
PyObject *
411
PyImport_AddModuleRef(const char *name)
412
102
{
413
102
    PyObject *name_obj = PyUnicode_FromString(name);
414
102
    if (name_obj == NULL) {
415
0
        return NULL;
416
0
    }
417
102
    PyThreadState *tstate = _PyThreadState_GET();
418
102
    PyObject *module = import_add_module(tstate, name_obj);
419
102
    Py_DECREF(name_obj);
420
102
    return module;
421
102
}
422
423
424
PyObject *
425
PyImport_AddModuleObject(PyObject *name)
426
34
{
427
34
    PyThreadState *tstate = _PyThreadState_GET();
428
34
    PyObject *mod = import_add_module(tstate, name);
429
34
    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
34
    PyObject *ref = PyWeakref_NewRef(mod, NULL);
444
34
    Py_DECREF(mod);
445
34
    if (ref == NULL) {
446
0
        return NULL;
447
0
    }
448
34
    mod = _PyWeakref_GET_REF(ref);
449
34
    Py_DECREF(ref);
450
34
    Py_XDECREF(mod);
451
452
34
    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
34
    return mod; /* borrowed reference */
458
34
}
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
1.08k
{
506
1.08k
    return _Py_atomic_add_ssize(&LAST_MODULE_INDEX, 1) + 1;
507
1.08k
}
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
68
{
529
68
    assert(index > 0);
530
68
    if (index == def->m_base.m_index) {
531
        /* There's nothing to do. */
532
68
    }
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
68
}
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
68
{
576
68
    assert(index > 0);
577
578
68
    if (MODULES_BY_INDEX(interp) == NULL) {
579
34
        MODULES_BY_INDEX(interp) = PyList_New(0);
580
34
        if (MODULES_BY_INDEX(interp) == NULL) {
581
0
            return -1;
582
0
        }
583
34
    }
584
585
238
    while (PyList_GET_SIZE(MODULES_BY_INDEX(interp)) <= index) {
586
170
        if (PyList_Append(MODULES_BY_INDEX(interp), Py_None) < 0) {
587
0
            return -1;
588
0
        }
589
170
    }
590
591
68
    return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(module));
592
68
}
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.91k
# define PKGCONTEXT pkgcontext
882
883
const char *
884
_PyImport_ResolveNameWithPackageContext(const char *name)
885
136
{
886
136
    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
136
    return name;
894
136
}
895
896
const char *
897
_PyImport_SwapPackageContext(const char *newcontext)
898
1.88k
{
899
1.88k
    const char *oldcontext = PKGCONTEXT;
900
1.88k
    PKGCONTEXT = newcontext;
901
1.88k
    return oldcontext;
902
1.88k
}
903
904
#ifdef HAVE_DLOPEN
905
int
906
_PyImport_GetDLOpenFlags(PyInterpreterState *interp)
907
450
{
908
450
    return DLOPENFLAGS(interp);
909
450
}
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
944
exec_builtin_or_dynamic(PyObject *mod) {
922
944
    void *state;
923
924
944
    if (!PyModule_Check(mod)) {
925
0
        return 0;
926
0
    }
927
928
944
    state = PyModule_GetState(mod);
929
944
    if (state) {
930
        /* Already initialized; skip reload */
931
0
        return 0;
932
0
    }
933
934
944
    return PyModule_Exec(mod);
935
944
}
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
1.08k
{
1034
1.08k
    PyMutex_Lock(&_PyRuntime.imports.extensions.mutex);
1035
1.08k
}
1036
1037
static inline void
1038
extensions_lock_release(void)
1039
1.08k
{
1040
1.08k
    PyMutex_Unlock(&_PyRuntime.imports.extensions.mutex);
1041
1.08k
}
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
68
{
1102
68
    struct extensions_cache_value *value
1103
68
            = PyMem_RawMalloc(sizeof(struct extensions_cache_value));
1104
68
    if (value == NULL) {
1105
0
        PyErr_NoMemory();
1106
0
        return NULL;
1107
0
    }
1108
68
    *value = (struct extensions_cache_value){0};
1109
68
    return value;
1110
68
}
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
68
{
1121
68
    assert(cached->m_index > 0);
1122
68
    return cached->m_index;
1123
68
}
1124
1125
static void
1126
fixup_cached_def(struct extensions_cache_value *value)
1127
68
{
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
68
    PyModuleDef *def = value->def;
1138
68
    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
68
    _Py_SetImmortalUntracked((PyObject *)def);
1143
1144
68
    def->m_base.m_init = value->m_init;
1145
1146
68
    assert(value->m_index > 0);
1147
68
    _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
68
    assert(def->m_base.m_copy == NULL
1152
68
           || def->m_base.m_init == NULL
1153
68
           || value->m_dict != NULL);
1154
68
    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
68
}
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
68
{
1170
68
    Py_XDECREF(oldbase->m_copy);
1171
68
}
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
68
{
1189
68
    assert(value != NULL);
1190
    /* This should only have been called without an m_dict already set. */
1191
68
    assert(value->m_dict == NULL);
1192
68
    if (m_dict == NULL) {
1193
68
        return 0;
1194
68
    }
1195
68
    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
1.05k
{
1279
1.05k
    const char *str1_data = _PyUnicode_AsUTF8NoNUL(str1);
1280
1.05k
    const char *str2_data = _PyUnicode_AsUTF8NoNUL(str2);
1281
1.05k
    if (str1_data == NULL || str2_data == NULL) {
1282
0
        return NULL;
1283
0
    }
1284
1.05k
    Py_ssize_t str1_len = strlen(str1_data);
1285
1.05k
    Py_ssize_t str2_len = strlen(str2_data);
1286
1287
    /* Make sure sep and the NULL byte won't cause an overflow. */
1288
1.05k
    assert(SIZE_MAX - str1_len - str2_len > 2);
1289
1.05k
    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
1.05k
    char *key = PyMem_RawMalloc(size);
1293
1.05k
    if (key == NULL) {
1294
0
        PyErr_NoMemory();
1295
0
        return NULL;
1296
0
    }
1297
1298
1.05k
    memcpy(key, str1_data, str1_len);
1299
1.05k
    key[str1_len] = sep;
1300
1.05k
    memcpy(key + str1_len + 1, str2_data, str2_len);
1301
1.05k
    key[size - 1] = '\0';
1302
1.05k
    assert(strlen(key) == size - 1);
1303
1.05k
    return key;
1304
1.05k
}
1305
1306
static Py_uhash_t
1307
hashtable_hash_str(const void *key)
1308
1.11k
{
1309
1.11k
    return Py_HashBuffer(key, strlen((const char *)key));
1310
1.11k
}
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
982
{
1321
982
    PyMem_RawFree(ptr);
1322
982
}
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
1.05k
#define HTSEP ':'
1360
1361
static int
1362
_extensions_cache_init(void)
1363
34
{
1364
34
    _Py_hashtable_allocator_t alloc = {PyMem_RawMalloc, PyMem_RawFree};
1365
34
    EXTENSIONS.hashtable = _Py_hashtable_new_full(
1366
34
        hashtable_hash_str,
1367
34
        hashtable_compare_str,
1368
34
        hashtable_destroy_str,  // key
1369
34
        del_extensions_cache_value,  // value
1370
34
        &alloc
1371
34
    );
1372
34
    if (EXTENSIONS.hashtable == NULL) {
1373
0
        PyErr_NoMemory();
1374
0
        return -1;
1375
0
    }
1376
34
    return 0;
1377
34
}
1378
1379
static _Py_hashtable_entry_t *
1380
_extensions_cache_find_unlocked(PyObject *path, PyObject *name,
1381
                                void **p_key)
1382
1.08k
{
1383
1.08k
    if (EXTENSIONS.hashtable == NULL) {
1384
34
        return NULL;
1385
34
    }
1386
1.05k
    void *key = hashtable_key_from_2_strings(path, name, HTSEP);
1387
1.05k
    if (key == NULL) {
1388
0
        return NULL;
1389
0
    }
1390
1.05k
    _Py_hashtable_entry_t *entry =
1391
1.05k
            _Py_hashtable_get_entry(EXTENSIONS.hashtable, key);
1392
1.05k
    if (p_key != NULL) {
1393
68
        *p_key = key;
1394
68
    }
1395
982
    else {
1396
982
        hashtable_destroy_str(key);
1397
982
    }
1398
1.05k
    return entry;
1399
1.05k
}
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
1.01k
{
1405
1.01k
    struct extensions_cache_value *value = NULL;
1406
1.01k
    extensions_lock_acquire();
1407
1408
1.01k
    _Py_hashtable_entry_t *entry =
1409
1.01k
            _extensions_cache_find_unlocked(path, name, NULL);
1410
1.01k
    if (entry == NULL) {
1411
        /* It was never added. */
1412
1.01k
        goto finally;
1413
1.01k
    }
1414
0
    value = (struct extensions_cache_value *)entry->value;
1415
1416
1.01k
finally:
1417
1.01k
    extensions_lock_release();
1418
1.01k
    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
68
{
1428
68
    struct extensions_cache_value *value = NULL;
1429
68
    void *key = NULL;
1430
68
    struct extensions_cache_value *newvalue = NULL;
1431
68
    PyModuleDef_Base olddefbase = def->m_base;
1432
1433
68
    assert(def != NULL);
1434
68
    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
68
    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
68
    assert(def->m_base.m_copy == NULL || m_dict != NULL);
1440
68
    assert((origin == _Py_ext_module_origin_DYNAMIC) == (name != path));
1441
68
    assert(origin != _Py_ext_module_origin_CORE || m_dict == NULL);
1442
1443
68
    extensions_lock_acquire();
1444
1445
68
    if (EXTENSIONS.hashtable == NULL) {
1446
34
        if (_extensions_cache_init() < 0) {
1447
0
            goto finally;
1448
0
        }
1449
34
    }
1450
1451
    /* Create a cached value to populate for the module. */
1452
68
    _Py_hashtable_entry_t *entry =
1453
68
            _extensions_cache_find_unlocked(path, name, &key);
1454
68
    value = entry == NULL
1455
68
        ? NULL
1456
68
        : (struct extensions_cache_value *)entry->value;
1457
68
    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
68
    newvalue = alloc_extensions_cache_value();
1469
68
    if (newvalue == NULL) {
1470
0
        goto finally;
1471
0
    }
1472
1473
    /* Populate the new cache value data. */
1474
68
    *newvalue = (struct extensions_cache_value){
1475
68
        .def=def,
1476
68
        .m_init=m_init,
1477
68
        .m_index=m_index,
1478
        /* m_dict is set by set_cached_m_dict(). */
1479
68
        .origin=origin,
1480
#ifdef Py_GIL_DISABLED
1481
        .md_requires_gil=requires_gil,
1482
#endif
1483
68
    };
1484
68
#ifndef Py_GIL_DISABLED
1485
68
    (void)requires_gil;
1486
68
#endif
1487
68
    if (init_cached_m_dict(newvalue, m_dict) < 0) {
1488
0
        goto finally;
1489
0
    }
1490
68
    fixup_cached_def(newvalue);
1491
1492
68
    if (entry == NULL) {
1493
        /* It was never added. */
1494
68
        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
68
        key = NULL;
1500
68
    }
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
68
    value = newvalue;
1519
1520
68
finally:
1521
68
    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
68
    else {
1528
68
        cleanup_old_cached_def(&olddefbase);
1529
68
    }
1530
1531
68
finally_oldvalue:
1532
68
    extensions_lock_release();
1533
68
    if (key != NULL) {
1534
0
        hashtable_destroy_str(key);
1535
0
    }
1536
1537
68
    return value;
1538
68
}
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
944
{
1665
944
    if (_Py_IsMainInterpreter(tstate->interp)) {
1666
944
        return tstate;
1667
944
    }
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
68
{
1819
68
    struct extensions_cache_value *cached = NULL;
1820
68
    PyModInitFunction m_init = NULL;
1821
68
    PyObject *m_dict = NULL;
1822
1823
    /* Set up for _extensions_cache_set(). */
1824
68
    if (singlephase == NULL) {
1825
0
        assert(def->m_base.m_init == NULL);
1826
0
        assert(def->m_base.m_copy == NULL);
1827
0
    }
1828
68
    else {
1829
68
        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
68
        else if (singlephase->m_dict == NULL) {
1842
            /* It must be a core builtin module. */
1843
68
            assert(is_core_module(tstate->interp, name, path));
1844
68
            assert(def->m_size == -1);
1845
68
            assert(def->m_base.m_copy == NULL);
1846
68
            assert(def->m_base.m_init == NULL);
1847
68
        }
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
68
    }
1859
1860
    /* Add the module's def to the global cache. */
1861
    // XXX Why special-case the main interpreter?
1862
68
    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
68
        cached = _extensions_cache_set(
1868
68
                path, name, def, m_init, singlephase->m_index, m_dict,
1869
68
                singlephase->origin, singlephase->md_requires_gil);
1870
68
        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
68
    }
1876
1877
68
    return cached;
1878
68
}
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
68
{
1887
68
    assert(mod != NULL && PyModule_Check(mod));
1888
68
    assert(cached->def == _PyModule_GetDefOrNull(mod));
1889
1890
68
    Py_ssize_t index = _get_cached_module_index(cached);
1891
68
    if (_modules_by_index_set(tstate->interp, index, mod) < 0) {
1892
0
        return -1;
1893
0
    }
1894
1895
68
    if (modules != NULL) {
1896
68
        if (PyObject_SetItem(modules, name, mod) < 0) {
1897
0
            return -1;
1898
0
        }
1899
68
    }
1900
1901
68
    return 0;
1902
68
}
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
948
{
2021
    /* Only single-phase init modules will be in the cache. */
2022
948
    struct extensions_cache_value *cached
2023
948
            = _extensions_cache_get(info->path, info->name);
2024
948
    if (cached == NULL) {
2025
948
        return NULL;
2026
948
    }
2027
948
    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
944
{
2096
    /* Core modules go through _PyImport_FixupBuiltin(). */
2097
944
    assert(!is_core_module(tstate->interp, info->name, info->path));
2098
2099
944
    PyObject *mod = NULL;
2100
944
    PyModuleDef *def = NULL;
2101
944
    struct extensions_cache_value *cached = NULL;
2102
944
    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
944
    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
944
    PyThreadState *main_tstate = switch_to_main_interpreter(tstate);
2153
944
    if (main_tstate == NULL) {
2154
0
        return NULL;
2155
0
    }
2156
944
    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
944
    struct _Py_ext_module_loader_result res;
2164
944
    int rc = _PyImport_RunModInitFunc(p0, info, &res);
2165
944
    if (rc < 0) {
2166
        /* We discard res.def. */
2167
0
        assert(res.module == NULL);
2168
0
    }
2169
944
    else {
2170
944
        assert(!PyErr_Occurred());
2171
944
        assert(res.err == NULL);
2172
2173
944
        mod = res.module;
2174
944
        res.module = NULL;
2175
944
        def = res.def;
2176
944
        assert(def != NULL);
2177
2178
        /* Do anything else that should be done
2179
         * while still using the main interpreter. */
2180
944
        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
944
    }
2239
2240
944
main_finally:
2241
944
    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
944
    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
944
    if (rc < 0) {
2272
0
        goto error;
2273
0
    }
2274
2275
944
    if (res.kind == _Py_ext_module_kind_MULTIPHASE) {
2276
944
        assert_multiphase_def(def);
2277
944
        assert(mod == NULL);
2278
        /* Note that we cheat a little by not repeating the calls
2279
         * to _PyImport_GetModuleExportHooks() and _PyImport_RunModInitFunc(). */
2280
944
        mod = PyModule_FromDefAndSpec(def, spec);
2281
944
        if (mod == NULL) {
2282
0
            goto error;
2283
0
        }
2284
944
    }
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
944
    _Py_ext_module_loader_result_clear(&res);
2321
944
    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
944
}
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
68
{
2384
68
    int res = -1;
2385
68
    assert(mod != NULL && PyModule_Check(mod));
2386
2387
68
    PyObject *nameobj;
2388
68
    nameobj = PyUnicode_InternFromString(name);
2389
68
    if (nameobj == NULL) {
2390
0
        return -1;
2391
0
    }
2392
2393
68
    PyModuleDef *def = _PyModule_GetDefOrNull(mod);
2394
68
    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
68
    assert(is_core_module(tstate->interp, nameobj, nameobj));
2405
68
    assert_singlephase_def(def);
2406
68
    assert(def->m_size == -1);
2407
68
    assert(def->m_base.m_copy == NULL);
2408
68
    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
68
    struct extensions_cache_value *cached
2415
68
            = _extensions_cache_get(nameobj, nameobj);
2416
68
    if (cached == NULL) {
2417
68
        struct singlephase_global_update singlephase = {
2418
68
            .m_index=def->m_base.m_index,
2419
            /* We don't want def->m_base.m_copy populated. */
2420
68
            .m_dict=NULL,
2421
68
            .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
68
        };
2427
68
        cached = update_global_state_for_extension(
2428
68
                tstate, nameobj, nameobj, def, &singlephase);
2429
68
        if (cached == NULL) {
2430
0
            goto finally;
2431
0
        }
2432
68
    }
2433
2434
68
    if (finish_singlephase_extension(tstate, mod, cached, nameobj, modules) < 0) {
2435
0
        goto finally;
2436
0
    }
2437
2438
68
    res = 0;
2439
2440
68
finally:
2441
68
    Py_DECREF(nameobj);
2442
68
    return res;
2443
68
}
2444
2445
/* Helper to test for built-in module */
2446
2447
static int
2448
is_builtin(PyObject *name)
2449
15.7k
{
2450
15.7k
    int i;
2451
15.7k
    struct _inittab *inittab = INITTAB;
2452
599k
    for (i = 0; inittab[i].name != NULL; i++) {
2453
584k
        if (_PyUnicode_EqualToASCIIString(name, inittab[i].name)) {
2454
687
            if (inittab[i].initfunc == NULL)
2455
0
                return -1;
2456
687
            else
2457
687
                return 1;
2458
687
        }
2459
584k
    }
2460
15.0k
    return 0;
2461
15.7k
}
2462
2463
static struct _inittab*
2464
lookup_inittab_entry(const struct _Py_ext_module_loader_info* info)
2465
721
{
2466
13.5k
    for (struct _inittab *p = INITTAB; p->name != NULL; p++) {
2467
13.5k
        if (_PyUnicode_EqualToASCIIString(info->name, p->name)) {
2468
721
            return p;
2469
721
        }
2470
13.5k
    }
2471
    // not found
2472
0
    return NULL;
2473
721
}
2474
2475
static PyObject*
2476
create_builtin(
2477
    PyThreadState *tstate, PyObject *name,
2478
    PyObject *spec,
2479
    PyModInitFunction initfunc)
2480
721
{
2481
721
    struct _Py_ext_module_loader_info info;
2482
721
    if (_Py_ext_module_loader_info_init_for_builtin(&info, name) < 0) {
2483
0
        return NULL;
2484
0
    }
2485
2486
721
    struct extensions_cache_value *cached = NULL;
2487
721
    PyObject *mod = import_find_extension(tstate, &info, &cached);
2488
721
    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
721
    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
721
    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
721
    PyModInitFunction p0 = NULL;
2511
721
    if (initfunc == NULL) {
2512
721
        struct _inittab *entry = lookup_inittab_entry(&info);
2513
721
        if (entry == NULL) {
2514
0
            mod = NULL;
2515
0
            _PyErr_SetModuleNotFoundError(name);
2516
0
            goto finally;
2517
0
        }
2518
2519
721
        p0 = (PyModInitFunction)entry->initfunc;
2520
721
    }
2521
0
    else {
2522
0
        p0 = initfunc;
2523
0
    }
2524
2525
721
    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
721
    mod = import_run_extension(
2543
721
                    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
721
finally:
2552
721
    _Py_ext_module_loader_info_clear(&info);
2553
721
    return mod;
2554
721
}
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
34
{
2663
34
    size_t size;
2664
1.32k
    for (size = 0; PyImport_Inittab[size].name != NULL; size++)
2665
1.29k
        ;
2666
34
    size++;
2667
2668
    /* Make the copy. */
2669
34
    struct _inittab *copied = _PyMem_DefaultRawMalloc(size * sizeof(struct _inittab));
2670
34
    if (copied == NULL) {
2671
0
        return -1;
2672
0
    }
2673
34
    memcpy(copied, PyImport_Inittab, size * sizeof(struct _inittab));
2674
34
    INITTAB = copied;
2675
34
    return 0;
2676
34
}
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
34
{
2689
34
    PyObject *list = PyList_New(0);
2690
34
    if (list == NULL) {
2691
0
        return NULL;
2692
0
    }
2693
34
    struct _inittab *inittab = INITTAB;
2694
1.32k
    for (Py_ssize_t i = 0; inittab[i].name != NULL; i++) {
2695
1.29k
        PyObject *name = PyUnicode_FromString(inittab[i].name);
2696
1.29k
        if (name == NULL) {
2697
0
            Py_DECREF(list);
2698
0
            return NULL;
2699
0
        }
2700
1.29k
        if (PyList_Append(list, name) < 0) {
2701
0
            Py_DECREF(name);
2702
0
            Py_DECREF(list);
2703
0
            return NULL;
2704
0
        }
2705
1.29k
        Py_DECREF(name);
2706
1.29k
    }
2707
34
    return list;
2708
34
}
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
34
{
2816
34
    PyObject *m, *d;
2817
2818
34
    m = import_add_module(tstate, name);
2819
34
    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
34
    d = PyModule_GetDict(m);
2824
34
    int r = PyDict_Contains(d, &_Py_ID(__builtins__));
2825
34
    if (r == 0) {
2826
34
        r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins());
2827
34
    }
2828
34
    if (r < 0) {
2829
0
        remove_module(tstate, name);
2830
0
        Py_DECREF(m);
2831
0
        return NULL;
2832
0
    }
2833
2834
34
    Py_INCREF(d);
2835
34
    Py_DECREF(m);
2836
34
    return d;
2837
34
}
2838
2839
static PyObject *
2840
exec_code_in_module(PyThreadState *tstate, PyObject *name,
2841
                    PyObject *module_dict, PyObject *code_object)
2842
34
{
2843
34
    PyObject *v, *m;
2844
2845
34
    v = PyEval_EvalCode(code_object, module_dict, module_dict);
2846
34
    if (v == NULL) {
2847
0
        remove_module(tstate, name);
2848
0
        return NULL;
2849
0
    }
2850
34
    Py_DECREF(v);
2851
2852
34
    m = import_get_module(tstate, name);
2853
34
    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
34
    return m;
2860
34
}
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
7.32k
{
2919
7.32k
    PyObject *oldname;
2920
2921
7.32k
    if (PyUnicode_Compare(co->co_filename, newname) == 0)
2922
7.32k
        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
944
{
2942
944
    const struct _module_alias *entry;
2943
7.20k
    for (entry = aliases; ; entry++) {
2944
7.20k
        if (entry->name == NULL) {
2945
            /* It isn't an alias. */
2946
774
            return false;
2947
774
        }
2948
6.43k
        if (strcmp(name, entry->name) == 0) {
2949
170
            if (alias != NULL) {
2950
170
                *alias = entry->orig;
2951
170
            }
2952
170
            return true;
2953
170
        }
2954
6.43k
    }
2955
944
}
2956
2957
static bool
2958
use_frozen(void)
2959
15.3k
{
2960
15.3k
    PyInterpreterState *interp = _PyInterpreterState_GET();
2961
15.3k
    int override = OVERRIDE_FROZEN_MODULES(interp);
2962
15.3k
    if (override > 0) {
2963
0
        return true;
2964
0
    }
2965
15.3k
    else if (override < 0) {
2966
0
        return false;
2967
0
    }
2968
15.3k
    else {
2969
15.3k
        return interp->config.use_frozen_modules;
2970
15.3k
    }
2971
15.3k
}
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
15.5k
{
3101
15.5k
    const struct _frozen *p;
3102
    // We always use the bootstrap modules.
3103
61.7k
    for (p = _PyImport_FrozenBootstrap; ; p++) {
3104
61.7k
        if (p->name == NULL) {
3105
            // We hit the end-of-list sentinel value.
3106
15.3k
            break;
3107
15.3k
        }
3108
46.4k
        if (strcmp(name, p->name) == 0) {
3109
238
            return p;
3110
238
        }
3111
46.4k
    }
3112
    // Prefer custom modules, if any.  Frozen stdlib modules can be
3113
    // disabled here by setting "code" to NULL in the array entry.
3114
15.3k
    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
15.3k
    if (use_frozen()) {
3126
223k
        for (p = _PyImport_FrozenStdlib; ; p++) {
3127
223k
            if (p->name == NULL) {
3128
14.6k
                break;
3129
14.6k
            }
3130
209k
            if (strcmp(name, p->name) == 0) {
3131
706
                return p;
3132
706
            }
3133
209k
        }
3134
175k
        for (p = _PyImport_FrozenTest; ; p++) {
3135
175k
            if (p->name == NULL) {
3136
14.6k
                break;
3137
14.6k
            }
3138
160k
            if (strcmp(name, p->name) == 0) {
3139
0
                return p;
3140
0
            }
3141
160k
        }
3142
14.6k
    }
3143
14.6k
    return NULL;
3144
15.3k
}
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
15.5k
{
3158
15.5k
    if (info != NULL) {
3159
15.5k
        memset(info, 0, sizeof(*info));
3160
15.5k
    }
3161
3162
15.5k
    if (nameobj == NULL || nameobj == Py_None) {
3163
0
        return FROZEN_BAD_NAME;
3164
0
    }
3165
15.5k
    const char *name = PyUnicode_AsUTF8(nameobj);
3166
15.5k
    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
15.5k
    const struct _frozen *p = look_up_frozen(name);
3176
15.5k
    if (p == NULL) {
3177
14.6k
        return FROZEN_NOT_FOUND;
3178
14.6k
    }
3179
944
    if (info != NULL) {
3180
944
        info->nameobj = nameobj;  // borrowed
3181
944
        info->data = (const char *)p->code;
3182
944
        info->size = p->size;
3183
944
        info->is_package = p->is_package;
3184
944
        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
944
        info->origname = name;
3190
944
        info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
3191
944
                                              &info->origname);
3192
944
    }
3193
944
    if (p->code == NULL) {
3194
        /* It is frozen but marked as un-importable. */
3195
0
        return FROZEN_EXCLUDED;
3196
0
    }
3197
944
    if (p->code[0] == '\0' || p->size == 0) {
3198
        /* Does not contain executable code. */
3199
0
        return FROZEN_INVALID;
3200
0
    }
3201
944
    return FROZEN_OKAY;
3202
944
}
3203
3204
static PyObject *
3205
unmarshal_frozen_code(PyInterpreterState *interp, struct frozen_info *info)
3206
455
{
3207
455
    PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
3208
455
    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
455
    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
455
    return co;
3223
455
}
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
34
{
3234
34
    PyThreadState *tstate = _PyThreadState_GET();
3235
34
    PyObject *co, *m, *d = NULL;
3236
34
    int err;
3237
3238
34
    struct frozen_info info;
3239
34
    frozen_status status = find_frozen(name, &info);
3240
34
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
3241
0
        return 0;
3242
0
    }
3243
34
    else if (status == FROZEN_BAD_NAME) {
3244
0
        return 0;
3245
0
    }
3246
34
    else if (status != FROZEN_OKAY) {
3247
0
        set_frozen_error(status, name);
3248
0
        return -1;
3249
0
    }
3250
34
    co = unmarshal_frozen_code(tstate->interp, &info);
3251
34
    if (co == NULL) {
3252
0
        return -1;
3253
0
    }
3254
34
    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
34
    d = module_dict_for_exec(tstate, name);
3273
34
    if (d == NULL) {
3274
0
        goto err_return;
3275
0
    }
3276
34
    m = exec_code_in_module(tstate, name, d, co);
3277
34
    if (m == NULL) {
3278
0
        goto err_return;
3279
0
    }
3280
34
    Py_DECREF(m);
3281
    /* Set __origname__ (consumed in FrozenImporter._setup_module()). */
3282
34
    PyObject *origname;
3283
34
    if (info.origname) {
3284
34
        origname = PyUnicode_FromString(info.origname);
3285
34
        if (origname == NULL) {
3286
0
            goto err_return;
3287
0
        }
3288
34
    }
3289
0
    else {
3290
0
        origname = Py_NewRef(Py_None);
3291
0
    }
3292
34
    err = PyDict_SetItemString(d, "__origname__", origname);
3293
34
    Py_DECREF(origname);
3294
34
    if (err != 0) {
3295
0
        goto err_return;
3296
0
    }
3297
34
    Py_DECREF(d);
3298
34
    Py_DECREF(co);
3299
34
    return 1;
3300
3301
0
err_return:
3302
0
    Py_XDECREF(d);
3303
0
    Py_DECREF(co);
3304
0
    return -1;
3305
34
}
3306
3307
int
3308
PyImport_ImportFrozenModule(const char *name)
3309
34
{
3310
34
    PyObject *nameobj;
3311
34
    int ret;
3312
34
    nameobj = PyUnicode_InternFromString(name);
3313
34
    if (nameobj == NULL)
3314
0
        return -1;
3315
34
    ret = PyImport_ImportFrozenModuleObject(nameobj);
3316
34
    Py_DECREF(nameobj);
3317
34
    return ret;
3318
34
}
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
34
{
3332
34
    PyObject *name = PyUnicode_FromString("_imp");
3333
34
    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
34
    PyObject *attrs = Py_BuildValue("{sO}", "name", name);
3342
34
    if (attrs == NULL) {
3343
0
        goto error;
3344
0
    }
3345
34
    PyObject *spec = _PyNamespace_New(attrs);
3346
34
    Py_DECREF(attrs);
3347
34
    if (spec == NULL) {
3348
0
        goto error;
3349
0
    }
3350
3351
    // Create the _imp module from its definition.
3352
34
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
3353
34
    Py_CLEAR(name);
3354
34
    Py_DECREF(spec);
3355
34
    if (mod == NULL) {
3356
0
        goto error;
3357
0
    }
3358
34
    assert(mod != Py_None);  // not found
3359
3360
    // Execute the _imp module: call imp_module_exec().
3361
34
    if (exec_builtin_or_dynamic(mod) < 0) {
3362
0
        Py_DECREF(mod);
3363
0
        goto error;
3364
0
    }
3365
34
    return mod;
3366
3367
0
error:
3368
0
    Py_XDECREF(name);
3369
0
    return NULL;
3370
34
}
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
34
{
3386
34
    assert(!_PyErr_Occurred(tstate));
3387
3388
34
    PyInterpreterState *interp = tstate->interp;
3389
34
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
3390
3391
    // Import _importlib through its frozen version, _frozen_importlib.
3392
34
    if (verbose) {
3393
0
        PySys_FormatStderr("import _frozen_importlib # frozen\n");
3394
0
    }
3395
34
    if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
3396
0
        return -1;
3397
0
    }
3398
3399
34
    PyObject *importlib = PyImport_AddModuleRef("_frozen_importlib");
3400
34
    if (importlib == NULL) {
3401
0
        return -1;
3402
0
    }
3403
34
    IMPORTLIB(interp) = importlib;
3404
3405
    // Import the _imp module
3406
34
    if (verbose) {
3407
0
        PySys_FormatStderr("import _imp # builtin\n");
3408
0
    }
3409
34
    PyObject *imp_mod = bootstrap_imp(tstate);
3410
34
    if (imp_mod == NULL) {
3411
0
        return -1;
3412
0
    }
3413
34
    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
34
    PyObject *value = PyObject_CallMethod(importlib, "_install",
3420
34
                                          "OO", sysmod, imp_mod);
3421
34
    Py_DECREF(imp_mod);
3422
34
    if (value == NULL) {
3423
0
        return -1;
3424
0
    }
3425
34
    Py_DECREF(value);
3426
3427
34
    assert(!_PyErr_Occurred(tstate));
3428
34
    return 0;
3429
34
}
3430
3431
3432
static int
3433
init_importlib_external(PyInterpreterState *interp)
3434
34
{
3435
34
    PyObject *value;
3436
34
    value = PyObject_CallMethod(IMPORTLIB(interp),
3437
34
                                "_install_external_importers", "");
3438
34
    if (value == NULL) {
3439
0
        return -1;
3440
0
    }
3441
34
    Py_DECREF(value);
3442
34
    return 0;
3443
34
}
3444
3445
PyObject *
3446
_PyImport_GetImportlibLoader(PyInterpreterState *interp,
3447
                             const char *loader_name)
3448
34
{
3449
34
    return PyObject_GetAttrString(IMPORTLIB(interp), loader_name);
3450
34
}
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
34
{
3578
    // Get the __import__ function
3579
34
    PyObject *import_func;
3580
34
    if (PyDict_GetItemStringRef(interp->builtins, "__import__", &import_func) <= 0) {
3581
0
        return -1;
3582
0
    }
3583
34
    IMPORT_FUNC(interp) = import_func;
3584
3585
    // Get the __lazy_import__ function
3586
34
    if (PyDict_GetItemStringRef(interp->builtins, "__lazy_import__",
3587
34
                                &import_func) <= 0) {
3588
0
        return -1;
3589
0
    }
3590
34
    LAZY_IMPORT_FUNC(interp) = import_func;
3591
34
    return 0;
3592
34
}
3593
3594
int
3595
_PyImport_IsDefaultImportFunc(PyInterpreterState *interp, PyObject *func)
3596
3.71M
{
3597
3.71M
    return func == IMPORT_FUNC(interp);
3598
3.71M
}
3599
3600
int
3601
_PyImport_IsDefaultLazyImportFunc(PyInterpreterState *interp, PyObject *func)
3602
72
{
3603
72
    return func == LAZY_IMPORT_FUNC(interp);
3604
72
}
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
1.33k
{
3612
1.33k
    PyObject *pname;
3613
1.33k
    PyObject *result;
3614
3615
1.33k
    pname = PyUnicode_FromString(name);
3616
1.33k
    if (pname == NULL)
3617
0
        return NULL;
3618
1.33k
    result = PyImport_Import(pname);
3619
1.33k
    Py_DECREF(pname);
3620
1.33k
    return result;
3621
1.33k
}
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
12.2k
{
3653
12.2k
    const char *importlib_filename = "<frozen importlib._bootstrap>";
3654
12.2k
    const char *external_filename = "<frozen importlib._bootstrap_external>";
3655
12.2k
    const char *remove_frames = "_call_with_frames_removed";
3656
12.2k
    int always_trim = 0;
3657
12.2k
    int in_importlib = 0;
3658
12.2k
    PyObject **prev_link, **outer_link = NULL;
3659
12.2k
    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
12.2k
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3666
12.2k
    if (exc == NULL || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
3667
0
        goto done;
3668
0
    }
3669
3670
12.2k
    if (PyType_IsSubtype(Py_TYPE(exc), (PyTypeObject *) PyExc_ImportError)) {
3671
12.2k
        always_trim = 1;
3672
12.2k
    }
3673
3674
12.2k
    assert(PyExceptionInstance_Check(exc));
3675
12.2k
    base_tb = PyException_GetTraceback(exc);
3676
12.2k
    prev_link = &base_tb;
3677
12.2k
    PyObject *tb = base_tb;
3678
58.1k
    while (tb != NULL) {
3679
45.8k
        assert(PyTraceBack_Check(tb));
3680
45.8k
        PyTracebackObject *traceback = (PyTracebackObject *)tb;
3681
45.8k
        PyObject *next = (PyObject *) traceback->tb_next;
3682
45.8k
        PyFrameObject *frame = traceback->tb_frame;
3683
45.8k
        PyCodeObject *code = PyFrame_GetCode(frame);
3684
45.8k
        int now_in_importlib;
3685
3686
45.8k
        now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
3687
10.6k
                           _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
3688
45.8k
        if (now_in_importlib && !in_importlib) {
3689
            /* This is the link to this chunk of importlib tracebacks */
3690
12.2k
            outer_link = prev_link;
3691
12.2k
        }
3692
45.8k
        in_importlib = now_in_importlib;
3693
3694
45.8k
        if (in_importlib &&
3695
40.5k
            (always_trim ||
3696
40.5k
             _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
3697
40.5k
            Py_XSETREF(*outer_link, Py_XNewRef(next));
3698
40.5k
            prev_link = outer_link;
3699
40.5k
        }
3700
5.34k
        else {
3701
5.34k
            prev_link = (PyObject **) &traceback->tb_next;
3702
5.34k
        }
3703
45.8k
        Py_DECREF(code);
3704
45.8k
        tb = next;
3705
45.8k
    }
3706
12.2k
    if (base_tb == NULL) {
3707
6.91k
        base_tb = Py_None;
3708
6.91k
        Py_INCREF(Py_None);
3709
6.91k
    }
3710
12.2k
    PyException_SetTraceback(exc, base_tb);
3711
12.2k
done:
3712
12.2k
    Py_XDECREF(base_tb);
3713
12.2k
    _PyErr_SetRaisedException(tstate, exc);
3714
12.2k
}
3715
3716
3717
static PyObject *
3718
resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
3719
992
{
3720
992
    PyObject *abs_name;
3721
992
    PyObject *package = NULL;
3722
992
    PyObject *spec = NULL;
3723
992
    Py_ssize_t last_dot;
3724
992
    PyObject *base;
3725
992
    int level_up;
3726
3727
992
    if (globals == NULL) {
3728
0
        _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
3729
0
        goto error;
3730
0
    }
3731
992
    if (!PyAnyDict_Check(globals)) {
3732
0
        _PyErr_SetString(tstate, PyExc_TypeError,
3733
0
                         "globals must be a dict or a frozendict");
3734
0
        goto error;
3735
0
    }
3736
992
    if (PyDict_GetItemRef(globals, &_Py_ID(__package__), &package) < 0) {
3737
0
        goto error;
3738
0
    }
3739
992
    if (package == Py_None) {
3740
0
        Py_DECREF(package);
3741
0
        package = NULL;
3742
0
    }
3743
992
    if (PyDict_GetItemRef(globals, &_Py_ID(__spec__), &spec) < 0) {
3744
0
        goto error;
3745
0
    }
3746
3747
992
    if (package != NULL) {
3748
992
        if (!PyUnicode_Check(package)) {
3749
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3750
0
                             "package must be a string");
3751
0
            goto error;
3752
0
        }
3753
992
        else if (spec != NULL && spec != Py_None) {
3754
992
            int equal;
3755
992
            PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent));
3756
992
            if (parent == NULL) {
3757
0
                goto error;
3758
0
            }
3759
3760
992
            equal = PyObject_RichCompareBool(package, parent, Py_EQ);
3761
992
            Py_DECREF(parent);
3762
992
            if (equal < 0) {
3763
0
                goto error;
3764
0
            }
3765
992
            else if (equal == 0) {
3766
0
                if (PyErr_WarnEx(PyExc_DeprecationWarning,
3767
0
                        "__package__ != __spec__.parent", 1) < 0) {
3768
0
                    goto error;
3769
0
                }
3770
0
            }
3771
992
        }
3772
992
    }
3773
0
    else if (spec != NULL && spec != Py_None) {
3774
0
        package = PyObject_GetAttr(spec, &_Py_ID(parent));
3775
0
        if (package == NULL) {
3776
0
            goto error;
3777
0
        }
3778
0
        else if (!PyUnicode_Check(package)) {
3779
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3780
0
                             "__spec__.parent must be a string");
3781
0
            goto error;
3782
0
        }
3783
0
    }
3784
0
    else {
3785
0
        if (PyErr_WarnEx(PyExc_ImportWarning,
3786
0
                    "can't resolve package from __spec__ or __package__, "
3787
0
                    "falling back on __name__ and __path__", 1) < 0) {
3788
0
            goto error;
3789
0
        }
3790
3791
0
        if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &package) < 0) {
3792
0
            goto error;
3793
0
        }
3794
0
        if (package == NULL) {
3795
0
            _PyErr_SetString(tstate, PyExc_KeyError,
3796
0
                             "'__name__' not in globals");
3797
0
            goto error;
3798
0
        }
3799
3800
0
        if (!PyUnicode_Check(package)) {
3801
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3802
0
                             "__name__ must be a string");
3803
0
            goto error;
3804
0
        }
3805
3806
0
        int haspath = PyDict_Contains(globals, &_Py_ID(__path__));
3807
0
        if (haspath < 0) {
3808
0
            goto error;
3809
0
        }
3810
0
        if (!haspath) {
3811
0
            Py_ssize_t dot;
3812
3813
0
            dot = PyUnicode_FindChar(package, '.',
3814
0
                                        0, PyUnicode_GET_LENGTH(package), -1);
3815
0
            if (dot == -2) {
3816
0
                goto error;
3817
0
            }
3818
0
            else if (dot == -1) {
3819
0
                goto no_parent_error;
3820
0
            }
3821
0
            PyObject *substr = PyUnicode_Substring(package, 0, dot);
3822
0
            if (substr == NULL) {
3823
0
                goto error;
3824
0
            }
3825
0
            Py_SETREF(package, substr);
3826
0
        }
3827
0
    }
3828
3829
992
    last_dot = PyUnicode_GET_LENGTH(package);
3830
992
    if (last_dot == 0) {
3831
0
        goto no_parent_error;
3832
0
    }
3833
3834
992
    for (level_up = 1; level_up < level; level_up += 1) {
3835
0
        last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
3836
0
        if (last_dot == -2) {
3837
0
            goto error;
3838
0
        }
3839
0
        else if (last_dot == -1) {
3840
0
            _PyErr_SetString(tstate, PyExc_ImportError,
3841
0
                             "attempted relative import beyond top-level "
3842
0
                             "package");
3843
0
            goto error;
3844
0
        }
3845
0
    }
3846
3847
992
    Py_XDECREF(spec);
3848
992
    base = PyUnicode_Substring(package, 0, last_dot);
3849
992
    Py_DECREF(package);
3850
992
    if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
3851
494
        return base;
3852
494
    }
3853
3854
498
    abs_name = PyUnicode_FromFormat("%U.%U", base, name);
3855
498
    Py_DECREF(base);
3856
498
    return abs_name;
3857
3858
0
  no_parent_error:
3859
0
    _PyErr_SetString(tstate, PyExc_ImportError,
3860
0
                     "attempted relative import "
3861
0
                     "with no known parent package");
3862
3863
0
  error:
3864
0
    Py_XDECREF(spec);
3865
0
    Py_XDECREF(package);
3866
0
    return NULL;
3867
0
}
3868
3869
PyObject *
3870
_PyImport_ResolveName(PyThreadState *tstate, PyObject *name,
3871
                      PyObject *globals, int level)
3872
0
{
3873
0
  return resolve_name(tstate, name, globals, level);
3874
0
}
3875
3876
PyObject *
3877
_PyImport_LoadLazyImportTstate(PyThreadState *tstate, PyObject *lazy_import)
3878
8
{
3879
8
    PyObject *obj = NULL;
3880
8
    PyObject *fromlist = Py_None;
3881
8
    PyObject *import_func = NULL;
3882
8
    assert(lazy_import != NULL);
3883
8
    assert(PyLazyImport_CheckExact(lazy_import));
3884
3885
8
    PyLazyImportObject *lz = (PyLazyImportObject *)lazy_import;
3886
8
    PyInterpreterState *interp = tstate->interp;
3887
3888
    // Acquire the global import lock to serialize reification
3889
8
    _PyImport_AcquireLock(interp);
3890
3891
    // Check if we are already importing this module, if so, then we want to
3892
    // return an error that indicates we've hit a cycle which will indicate
3893
    // the value isn't yet available.
3894
8
    PyObject *importing = interp->imports.lazy_importing_modules;
3895
8
    if (importing == NULL) {
3896
4
        importing = interp->imports.lazy_importing_modules = PySet_New(NULL);
3897
4
        if (importing == NULL) {
3898
0
            _PyImport_ReleaseLock(interp);
3899
0
            return NULL;
3900
0
        }
3901
4
    }
3902
3903
8
    assert(PyAnySet_CheckExact(importing));
3904
8
    int is_loading = _PySet_Contains((PySetObject *)importing, lazy_import);
3905
8
    if (is_loading < 0) {
3906
0
        _PyImport_ReleaseLock(interp);
3907
0
        return NULL;
3908
0
    }
3909
8
    else if (is_loading == 1) {
3910
0
        PyObject *name = _PyLazyImport_GetName(lazy_import);
3911
0
        if (name == NULL) {
3912
0
            _PyImport_ReleaseLock(interp);
3913
0
            return NULL;
3914
0
        }
3915
0
        PyObject *errmsg = PyUnicode_FromFormat(
3916
0
            "cannot import name %R (most likely due to a circular import)",
3917
0
            name);
3918
0
        if (errmsg == NULL) {
3919
0
            Py_DECREF(name);
3920
0
            _PyImport_ReleaseLock(interp);
3921
0
            return NULL;
3922
0
        }
3923
0
        PyErr_SetImportErrorSubclass(PyExc_ImportCycleError, errmsg,
3924
0
                                     lz->lz_from, NULL);
3925
0
        Py_DECREF(errmsg);
3926
0
        Py_DECREF(name);
3927
0
        _PyImport_ReleaseLock(interp);
3928
0
        return NULL;
3929
0
    }
3930
8
    else if (PySet_Add(importing, lazy_import) < 0) {
3931
0
        _PyImport_ReleaseLock(interp);
3932
0
        goto error;
3933
0
    }
3934
3935
8
    Py_ssize_t dot = -1;
3936
8
    int full = 0;
3937
8
    if (lz->lz_attr != NULL) {
3938
0
        full = 1;
3939
0
    }
3940
8
    if (!full) {
3941
8
        dot = PyUnicode_FindChar(lz->lz_from, '.', 0,
3942
8
                                 PyUnicode_GET_LENGTH(lz->lz_from), 1);
3943
8
    }
3944
8
    if (dot < 0) {
3945
8
        full = 1;
3946
8
    }
3947
3948
8
    if (lz->lz_attr != NULL) {
3949
0
        if (PyUnicode_Check(lz->lz_attr)) {
3950
0
            fromlist = PyTuple_New(1);
3951
0
            if (fromlist == NULL) {
3952
0
                goto error;
3953
0
            }
3954
0
            Py_INCREF(lz->lz_attr);
3955
0
            PyTuple_SET_ITEM(fromlist, 0, lz->lz_attr);
3956
0
        }
3957
0
        else {
3958
0
            Py_INCREF(lz->lz_attr);
3959
0
            fromlist = lz->lz_attr;
3960
0
        }
3961
0
    }
3962
3963
8
    PyObject *globals = PyEval_GetGlobals();
3964
3965
8
    if (PyMapping_GetOptionalItem(lz->lz_builtins, &_Py_ID(__import__),
3966
8
                                  &import_func) < 0) {
3967
0
        goto error;
3968
0
    }
3969
8
    if (import_func == NULL) {
3970
0
        PyErr_SetString(PyExc_ImportError, "__import__ not found");
3971
0
        goto error;
3972
0
    }
3973
8
    if (full) {
3974
8
        obj = _PyEval_ImportNameWithImport(
3975
8
            tstate, import_func, globals, globals,
3976
8
            lz->lz_from, fromlist, _PyLong_GetZero()
3977
8
        );
3978
8
    }
3979
0
    else {
3980
0
        PyObject *name = PyUnicode_Substring(lz->lz_from, 0, dot);
3981
0
        if (name == NULL) {
3982
0
            goto error;
3983
0
        }
3984
0
        obj = _PyEval_ImportNameWithImport(
3985
0
            tstate, import_func, globals, globals,
3986
0
            name, fromlist, _PyLong_GetZero()
3987
0
        );
3988
0
        Py_DECREF(name);
3989
0
    }
3990
8
    if (obj == NULL) {
3991
0
        goto error;
3992
0
    }
3993
3994
8
    if (lz->lz_attr != NULL && PyUnicode_Check(lz->lz_attr)) {
3995
0
        PyObject *from = obj;
3996
0
        obj = _PyEval_ImportFrom(tstate, from, lz->lz_attr);
3997
0
        Py_DECREF(from);
3998
0
        if (obj == NULL) {
3999
0
            goto error;
4000
0
        }
4001
0
    }
4002
4003
8
    assert(!PyLazyImport_CheckExact(obj));
4004
4005
8
    goto ok;
4006
4007
0
error:
4008
0
    Py_CLEAR(obj);
4009
4010
    // If an error occurred and we have frame information, add it to the
4011
    // exception.
4012
0
    if (PyErr_Occurred() && lz->lz_code != NULL && lz->lz_instr_offset >= 0) {
4013
        // Get the current exception - this already has the full traceback
4014
        // from the access point.
4015
0
        PyObject *exc = _PyErr_GetRaisedException(tstate);
4016
4017
        // Get import name - this can fail and set an exception.
4018
0
        PyObject *import_name = _PyLazyImport_GetName(lazy_import);
4019
0
        if (!import_name) {
4020
            // Failed to get import name, just restore original exception.
4021
0
            _PyErr_SetRaisedException(tstate, exc);
4022
0
            goto ok;
4023
0
        }
4024
4025
        // Resolve line number from instruction offset on demand.
4026
0
        int lineno = PyCode_Addr2Line((PyCodeObject *)lz->lz_code,
4027
0
                                      lz->lz_instr_offset*2);
4028
4029
        // Get strings - these can return NULL on encoding errors.
4030
0
        const char *filename_str = PyUnicode_AsUTF8(lz->lz_code->co_filename);
4031
0
        if (!filename_str) {
4032
            // Unicode conversion failed - clear error and restore original
4033
            // exception.
4034
0
            PyErr_Clear();
4035
0
            Py_DECREF(import_name);
4036
0
            _PyErr_SetRaisedException(tstate, exc);
4037
0
            goto ok;
4038
0
        }
4039
4040
0
        const char *funcname_str = PyUnicode_AsUTF8(lz->lz_code->co_name);
4041
0
        if (!funcname_str) {
4042
            // Unicode conversion failed - clear error and restore original
4043
            // exception.
4044
0
            PyErr_Clear();
4045
0
            Py_DECREF(import_name);
4046
0
            _PyErr_SetRaisedException(tstate, exc);
4047
0
            goto ok;
4048
0
        }
4049
4050
        // Create a cause exception showing where the lazy import was declared.
4051
0
        PyObject *msg = PyUnicode_FromFormat(
4052
0
            "deferred import of '%U' raised an exception during resolution",
4053
0
            import_name
4054
0
        );
4055
0
        Py_DECREF(import_name); // Done with import_name.
4056
4057
0
        if (!msg) {
4058
            // Failed to create message - restore original exception.
4059
0
            _PyErr_SetRaisedException(tstate, exc);
4060
0
            goto ok;
4061
0
        }
4062
4063
0
        PyObject *cause_exc = PyObject_CallOneArg(PyExc_ImportError, msg);
4064
0
        Py_DECREF(msg);  // Done with msg.
4065
4066
0
        if (!cause_exc) {
4067
            // Failed to create exception - restore original.
4068
0
            _PyErr_SetRaisedException(tstate, exc);
4069
0
            goto ok;
4070
0
        }
4071
4072
        // Add traceback entry for the lazy import declaration.
4073
0
        _PyErr_SetRaisedException(tstate, cause_exc);
4074
0
        _PyTraceback_Add(funcname_str, filename_str, lineno);
4075
0
        PyObject *cause_with_tb = _PyErr_GetRaisedException(tstate);
4076
4077
        // Set the cause on the original exception.
4078
0
        PyException_SetCause(exc, cause_with_tb);  // Steals ref to cause_with_tb.
4079
4080
        // Restore the original exception with its full traceback.
4081
0
        _PyErr_SetRaisedException(tstate, exc);
4082
0
    }
4083
4084
8
ok:
4085
8
    if (PySet_Discard(importing, lazy_import) < 0) {
4086
0
        Py_CLEAR(obj);
4087
0
    }
4088
4089
    // Release the global import lock.
4090
8
    _PyImport_ReleaseLock(interp);
4091
4092
8
    Py_XDECREF(fromlist);
4093
8
    Py_XDECREF(import_func);
4094
8
    return obj;
4095
0
}
4096
4097
static PyObject *
4098
import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
4099
15.6k
{
4100
15.6k
    PyObject *mod = NULL;
4101
15.6k
    PyInterpreterState *interp = tstate->interp;
4102
15.6k
    int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
4103
15.6k
#define import_level FIND_AND_LOAD(interp).import_level
4104
15.6k
#define accumulated FIND_AND_LOAD(interp).accumulated
4105
4106
15.6k
    PyTime_t t1 = 0, accumulated_copy = accumulated;
4107
4108
    /* XOptions is initialized after first some imports.
4109
     * So we can't have negative cache before completed initialization.
4110
     * Anyway, importlib._find_and_load is much slower than
4111
     * _PyDict_GetItemIdWithError().
4112
     */
4113
15.6k
    if (import_time) {
4114
0
        _IMPORT_TIME_HEADER(interp);
4115
4116
0
        import_level++;
4117
        // ignore error: don't block import if reading the clock fails
4118
0
        (void)PyTime_PerfCounterRaw(&t1);
4119
0
        accumulated = 0;
4120
0
    }
4121
4122
15.6k
    if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
4123
0
        PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
4124
4125
15.6k
    mod = PyObject_CallMethodObjArgs(IMPORTLIB(interp), &_Py_ID(_find_and_load),
4126
15.6k
                                     abs_name, IMPORT_FUNC(interp), NULL);
4127
4128
15.6k
    if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
4129
0
        PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
4130
0
                                       mod != NULL);
4131
4132
15.6k
    if (import_time) {
4133
0
        PyTime_t t2;
4134
0
        (void)PyTime_PerfCounterRaw(&t2);
4135
0
        PyTime_t cum = t2 - t1;
4136
4137
0
        import_level--;
4138
0
        fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
4139
0
                (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
4140
0
                (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
4141
0
                import_level*2, "", PyUnicode_AsUTF8(abs_name));
4142
4143
0
        accumulated = accumulated_copy + cum;
4144
0
    }
4145
4146
15.6k
    return mod;
4147
15.6k
#undef import_level
4148
15.6k
#undef accumulated
4149
15.6k
}
4150
4151
static PyObject *
4152
get_abs_name(PyThreadState *tstate, PyObject *name, PyObject *globals,
4153
             int level)
4154
3.96M
{
4155
3.96M
    if (level > 0) {
4156
992
        return resolve_name(tstate, name, globals, level);
4157
992
    }
4158
3.95M
    if (PyUnicode_GET_LENGTH(name) == 0) {
4159
0
        _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
4160
0
        return NULL;
4161
0
    }
4162
3.95M
    return Py_NewRef(name);
4163
3.95M
}
4164
4165
PyObject *
4166
_PyImport_GetAbsName(PyThreadState *tstate, PyObject *name,
4167
                     PyObject *globals, int level)
4168
0
{
4169
0
    return get_abs_name(tstate, name, globals, level);
4170
0
}
4171
4172
4173
PyObject *
4174
PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
4175
                                 PyObject *locals, PyObject *fromlist,
4176
                                 int level)
4177
3.96M
{
4178
3.96M
    PyThreadState *tstate = _PyThreadState_GET();
4179
3.96M
    PyObject *abs_name = NULL;
4180
3.96M
    PyObject *final_mod = NULL;
4181
3.96M
    PyObject *mod = NULL;
4182
3.96M
    PyInterpreterState *interp = tstate->interp;
4183
3.96M
    int has_from;
4184
4185
3.96M
    if (name == NULL) {
4186
0
        _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
4187
0
        goto error;
4188
0
    }
4189
4190
    /* The below code is importlib.__import__() & _gcd_import(), ported to C
4191
       for added performance. */
4192
4193
3.96M
    if (!PyUnicode_Check(name)) {
4194
0
        _PyErr_SetString(tstate, PyExc_TypeError,
4195
0
                         "module name must be a string");
4196
0
        goto error;
4197
0
    }
4198
3.96M
    if (level < 0) {
4199
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
4200
0
        goto error;
4201
0
    }
4202
4203
3.96M
    abs_name = get_abs_name(tstate, name, globals, level);
4204
3.96M
    if (abs_name == NULL) {
4205
0
        goto error;
4206
0
    }
4207
4208
3.96M
    mod = import_get_module(tstate, abs_name);
4209
3.96M
    if (mod == NULL && _PyErr_Occurred(tstate)) {
4210
0
        goto error;
4211
0
    }
4212
4213
3.96M
    if (mod != NULL && mod != Py_None) {
4214
3.94M
        if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
4215
0
            goto error;
4216
0
        }
4217
        /* Verify the module is still in sys.modules. Another thread may have
4218
           removed it (due to import failure) between our import_get_module()
4219
           call and the _initializing check in import_ensure_initialized().
4220
           If removed, we retry the import to preserve normal semantics: the
4221
           caller gets the exception from the actual import failure rather
4222
           than a synthetic error. */
4223
3.94M
        PyObject *mod_check = import_get_module(tstate, abs_name);
4224
3.94M
        if (mod_check != mod) {
4225
0
            Py_XDECREF(mod_check);
4226
0
            if (_PyErr_Occurred(tstate)) {
4227
0
                goto error;
4228
0
            }
4229
0
            Py_DECREF(mod);
4230
0
            mod = import_find_and_load(tstate, abs_name);
4231
0
            if (mod == NULL) {
4232
0
                goto error;
4233
0
            }
4234
0
        }
4235
3.94M
        else {
4236
3.94M
            Py_DECREF(mod_check);
4237
3.94M
        }
4238
3.94M
    }
4239
15.6k
    else {
4240
15.6k
        Py_XDECREF(mod);
4241
15.6k
        mod = import_find_and_load(tstate, abs_name);
4242
15.6k
        if (mod == NULL) {
4243
12.2k
            goto error;
4244
12.2k
        }
4245
15.6k
    }
4246
4247
3.94M
    has_from = 0;
4248
3.94M
    if (fromlist != NULL && fromlist != Py_None) {
4249
1.71M
        has_from = PyObject_IsTrue(fromlist);
4250
1.71M
        if (has_from < 0)
4251
0
            goto error;
4252
1.71M
    }
4253
3.94M
    if (!has_from) {
4254
2.47M
        Py_ssize_t len = PyUnicode_GET_LENGTH(name);
4255
2.47M
        if (level == 0 || len > 0) {
4256
2.47M
            Py_ssize_t dot;
4257
4258
2.47M
            dot = PyUnicode_FindChar(name, '.', 0, len, 1);
4259
2.47M
            if (dot == -2) {
4260
0
                goto error;
4261
0
            }
4262
4263
2.47M
            if (dot == -1) {
4264
                /* No dot in module name, simple exit */
4265
2.46M
                final_mod = Py_NewRef(mod);
4266
2.46M
                goto error;
4267
2.46M
            }
4268
4269
2.74k
            if (level == 0) {
4270
2.74k
                PyObject *front = PyUnicode_Substring(name, 0, dot);
4271
2.74k
                if (front == NULL) {
4272
0
                    goto error;
4273
0
                }
4274
4275
2.74k
                final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
4276
2.74k
                Py_DECREF(front);
4277
2.74k
            }
4278
0
            else {
4279
0
                Py_ssize_t cut_off = len - dot;
4280
0
                Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
4281
0
                PyObject *to_return = PyUnicode_Substring(abs_name, 0,
4282
0
                                                        abs_name_len - cut_off);
4283
0
                if (to_return == NULL) {
4284
0
                    goto error;
4285
0
                }
4286
4287
0
                final_mod = import_get_module(tstate, to_return);
4288
0
                if (final_mod == NULL) {
4289
0
                    if (!_PyErr_Occurred(tstate)) {
4290
0
                        _PyErr_Format(tstate, PyExc_KeyError,
4291
0
                                      "%R not in sys.modules as expected",
4292
0
                                      to_return);
4293
0
                    }
4294
0
                    Py_DECREF(to_return);
4295
0
                    goto error;
4296
0
                }
4297
4298
0
                Py_DECREF(to_return);
4299
0
            }
4300
2.74k
        }
4301
0
        else {
4302
0
            final_mod = Py_NewRef(mod);
4303
0
        }
4304
2.47M
    }
4305
1.47M
    else {
4306
1.47M
        int has_path = PyObject_HasAttrWithError(mod, &_Py_ID(__path__));
4307
1.47M
        if (has_path < 0) {
4308
0
            goto error;
4309
0
        }
4310
1.47M
        if (has_path) {
4311
10.1k
            final_mod = PyObject_CallMethodObjArgs(
4312
10.1k
                        IMPORTLIB(interp), &_Py_ID(_handle_fromlist),
4313
10.1k
                        mod, fromlist, IMPORT_FUNC(interp), NULL);
4314
10.1k
        }
4315
1.46M
        else {
4316
1.46M
            final_mod = Py_NewRef(mod);
4317
1.46M
        }
4318
1.47M
    }
4319
4320
3.96M
  error:
4321
3.96M
    Py_XDECREF(abs_name);
4322
3.96M
    Py_XDECREF(mod);
4323
3.96M
    if (final_mod == NULL) {
4324
12.2k
        remove_importlib_frames(tstate);
4325
12.2k
    }
4326
3.96M
    return final_mod;
4327
3.94M
}
4328
4329
static PyObject *
4330
get_mod_dict(PyObject *module)
4331
16
{
4332
16
    if (PyModule_Check(module)) {
4333
16
        return Py_NewRef(_PyModule_GetDict(module));
4334
16
    }
4335
4336
0
    return PyObject_GetAttr(module, &_Py_ID(__dict__));
4337
16
}
4338
4339
// ensure we have the set for the parent module name in sys.lazy_modules.
4340
// Returns a new reference.
4341
static PyObject *
4342
ensure_lazy_submodules(PyDictObject *lazy_modules, PyObject *parent)
4343
60
{
4344
60
    PyObject *lazy_submodules;
4345
60
    Py_BEGIN_CRITICAL_SECTION(lazy_modules);
4346
60
    int err = _PyDict_GetItemRef_Unicode_LockHeld(lazy_modules, parent,
4347
60
                                                  &lazy_submodules);
4348
60
    if (err == 0) {
4349
        // value isn't present
4350
60
        lazy_submodules = PySet_New(NULL);
4351
60
        if (lazy_submodules != NULL &&
4352
60
            _PyDict_SetItem_LockHeld(lazy_modules, parent,
4353
60
                                     lazy_submodules) < 0) {
4354
0
            Py_CLEAR(lazy_submodules);
4355
0
        }
4356
60
    }
4357
60
    Py_END_CRITICAL_SECTION();
4358
60
    return lazy_submodules;
4359
60
}
4360
4361
static int
4362
register_lazy_on_parent(PyThreadState *tstate, PyObject *name,
4363
                        PyObject *builtins)
4364
72
{
4365
72
    int ret = -1;
4366
72
    PyObject *parent = NULL;
4367
72
    PyObject *child = NULL;
4368
72
    PyObject *parent_module = NULL;
4369
72
    PyObject *parent_dict = NULL;
4370
4371
72
    PyInterpreterState *interp = tstate->interp;
4372
72
    PyObject *lazy_modules = LAZY_MODULES(interp);
4373
72
    assert(lazy_modules != NULL);
4374
4375
72
    Py_INCREF(name);
4376
132
    while (true) {
4377
132
        Py_ssize_t dot = PyUnicode_FindChar(name, '.', 0,
4378
132
                                            PyUnicode_GET_LENGTH(name), -1);
4379
132
        if (dot < 0) {
4380
72
            ret = 0;
4381
72
            goto done;
4382
72
        }
4383
60
        parent = PyUnicode_Substring(name, 0, dot);
4384
        // If `parent` is NULL then this has hit the end of the import, no
4385
        // more "parent.child" in the import name. The entire import will be
4386
        // resolved lazily.
4387
60
        if (parent == NULL) {
4388
0
            goto done;
4389
0
        }
4390
60
        Py_XDECREF(child);
4391
60
        child = PyUnicode_Substring(name, dot + 1, PyUnicode_GET_LENGTH(name));
4392
60
        if (child == NULL) {
4393
0
            goto done;
4394
0
        }
4395
4396
        // Record the child as being lazily imported from the parent.
4397
60
        PyObject *lazy_submodules = ensure_lazy_submodules(
4398
60
            (PyDictObject *)lazy_modules, parent);
4399
60
        if (lazy_submodules == NULL) {
4400
0
            goto done;
4401
0
        }
4402
4403
60
        if (PySet_Add(lazy_submodules, child) < 0) {
4404
0
            Py_DECREF(lazy_submodules);
4405
0
            goto done;
4406
0
        }
4407
60
        Py_DECREF(lazy_submodules);
4408
4409
        // Add the lazy import for the child to the parent.
4410
60
        Py_XSETREF(parent_module, PyImport_GetModule(parent));
4411
60
        if (parent_module != NULL) {
4412
0
            Py_XSETREF(parent_dict, get_mod_dict(parent_module));
4413
0
            if (parent_dict == NULL) {
4414
0
                goto done;
4415
0
            }
4416
0
            if (PyDict_CheckExact(parent_dict)) {
4417
0
                int contains = PyDict_Contains(parent_dict, child);
4418
0
                if (contains < 0) {
4419
0
                    goto done;
4420
0
                }
4421
0
                if (!contains) {
4422
0
                    PyObject *lazy_module_attr = _PyLazyImport_New(
4423
0
                        tstate->current_frame, builtins, parent, child
4424
0
                    );
4425
0
                    if (lazy_module_attr == NULL) {
4426
0
                        goto done;
4427
0
                    }
4428
0
                    if (PyDict_SetItem(parent_dict, child,
4429
0
                                       lazy_module_attr) < 0) {
4430
0
                        Py_DECREF(lazy_module_attr);
4431
0
                        goto done;
4432
0
                    }
4433
0
                    Py_DECREF(lazy_module_attr);
4434
0
                }
4435
0
            }
4436
0
            ret = 0;
4437
0
            goto done;
4438
0
        }
4439
4440
60
        Py_SETREF(name, parent);
4441
60
        parent = NULL;
4442
60
    }
4443
4444
72
done:
4445
72
    Py_XDECREF(parent_dict);
4446
72
    Py_XDECREF(parent_module);
4447
72
    Py_XDECREF(child);
4448
72
    Py_XDECREF(parent);
4449
72
    Py_XDECREF(name);
4450
72
    return ret;
4451
72
}
4452
4453
static int
4454
register_from_lazy_on_parent(PyThreadState *tstate, PyObject *abs_name,
4455
                             PyObject *from, PyObject *builtins)
4456
60
{
4457
60
    PyObject *fromname = PyUnicode_FromFormat("%U.%U", abs_name, from);
4458
60
    if (fromname == NULL) {
4459
0
        return -1;
4460
0
    }
4461
60
    int res = register_lazy_on_parent(tstate, fromname, builtins);
4462
60
    Py_DECREF(fromname);
4463
60
    return res;
4464
60
}
4465
4466
PyObject *
4467
_PyImport_LazyImportModuleLevelObject(PyThreadState *tstate,
4468
                                      PyObject *name, PyObject *builtins,
4469
                                      PyObject *globals, PyObject *locals,
4470
                                      PyObject *fromlist, int level)
4471
72
{
4472
72
    assert(name != NULL);
4473
72
    if (!PyUnicode_Check(name)) {
4474
0
        _PyErr_Format(tstate, PyExc_TypeError,
4475
0
                      "module name must be a string, got %T", name);
4476
0
        return NULL;
4477
0
    }
4478
72
    if (level < 0) {
4479
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
4480
0
        return NULL;
4481
0
    }
4482
4483
72
    PyObject *abs_name = get_abs_name(tstate, name, globals, level);
4484
72
    if (abs_name == NULL) {
4485
0
        return NULL;
4486
0
    }
4487
4488
72
    PyInterpreterState *interp = tstate->interp;
4489
72
    _PyInterpreterFrame *frame = _PyEval_GetFrame();
4490
72
    if (frame == NULL || frame->f_globals != frame->f_locals) {
4491
0
        Py_DECREF(abs_name);
4492
0
        PyErr_SetString(PyExc_SyntaxError,
4493
0
                        "'lazy import' is only allowed at module level");
4494
0
        return NULL;
4495
0
    }
4496
4497
    // Check if the filter disables the lazy import.
4498
    // We must hold a reference to the filter while calling it to prevent
4499
    // use-after-free if another thread replaces it via
4500
    // PyImport_SetLazyImportsFilter.
4501
72
    LAZY_IMPORTS_LOCK(interp);
4502
72
    PyObject *filter = Py_XNewRef(LAZY_IMPORTS_FILTER(interp));
4503
72
    LAZY_IMPORTS_UNLOCK(interp);
4504
4505
72
    if (filter != NULL) {
4506
0
        PyObject *modname;
4507
0
        if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &modname) < 0) {
4508
0
            Py_DECREF(filter);
4509
0
            Py_DECREF(abs_name);
4510
0
            return NULL;
4511
0
        }
4512
0
        if (modname == NULL) {
4513
0
            assert(!PyErr_Occurred());
4514
0
            modname = Py_NewRef(Py_None);
4515
0
        }
4516
0
        if (fromlist == NULL) {
4517
0
            assert(!PyErr_Occurred());
4518
0
            fromlist = Py_NewRef(Py_None);
4519
0
        }
4520
0
        PyObject *args[] = {modname, name, fromlist};
4521
0
        PyObject *res = PyObject_Vectorcall(filter, args, 3, NULL);
4522
4523
0
        Py_DECREF(modname);
4524
0
        Py_DECREF(filter);
4525
4526
0
        if (res == NULL) {
4527
0
            Py_DECREF(abs_name);
4528
0
            return NULL;
4529
0
        }
4530
4531
0
        int is_true = PyObject_IsTrue(res);
4532
0
        Py_DECREF(res);
4533
4534
0
        if (is_true < 0) {
4535
0
            Py_DECREF(abs_name);
4536
0
            return NULL;
4537
0
        }
4538
0
        if (!is_true) {
4539
0
            Py_DECREF(abs_name);
4540
0
            return PyImport_ImportModuleLevelObject(
4541
0
                name, globals, locals, fromlist, level
4542
0
            );
4543
0
        }
4544
0
    }
4545
4546
    // here, 'filter' is either NULL or is equivalent to a borrowed reference
4547
72
    PyObject *res = _PyLazyImport_New(frame, builtins, abs_name, fromlist);
4548
72
    if (res == NULL) {
4549
0
        Py_DECREF(abs_name);
4550
0
        return NULL;
4551
0
    }
4552
72
    if (fromlist && PyUnicode_Check(fromlist)) {
4553
0
        if (register_from_lazy_on_parent(tstate, abs_name, fromlist,
4554
0
                                         builtins) < 0) {
4555
0
            goto error;
4556
0
        }
4557
0
    }
4558
72
    else if (fromlist && PyTuple_Check(fromlist) &&
4559
60
             PyTuple_GET_SIZE(fromlist)) {
4560
120
        for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(fromlist); i++) {
4561
60
            if (register_from_lazy_on_parent(tstate, abs_name,
4562
60
                                             PyTuple_GET_ITEM(fromlist, i),
4563
60
                                             builtins) < 0)
4564
0
            {
4565
0
                goto error;
4566
0
            }
4567
60
        }
4568
60
    }
4569
12
    else if (register_lazy_on_parent(tstate, abs_name, builtins) < 0) {
4570
0
        goto error;
4571
0
    }
4572
4573
72
    Py_DECREF(abs_name);
4574
72
    return res;
4575
0
error:
4576
0
    Py_DECREF(abs_name);
4577
0
    Py_DECREF(res);
4578
0
    return NULL;
4579
72
}
4580
4581
PyObject *
4582
PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
4583
                           PyObject *fromlist, int level)
4584
272
{
4585
272
    PyObject *nameobj, *mod;
4586
272
    nameobj = PyUnicode_FromString(name);
4587
272
    if (nameobj == NULL)
4588
0
        return NULL;
4589
272
    mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
4590
272
                                           fromlist, level);
4591
272
    Py_DECREF(nameobj);
4592
272
    return mod;
4593
272
}
4594
4595
4596
/* Re-import a module of any kind and return its module object, WITH
4597
   INCREMENTED REFERENCE COUNT */
4598
4599
PyObject *
4600
PyImport_ReloadModule(PyObject *m)
4601
0
{
4602
0
    PyObject *reloaded_module = NULL;
4603
0
    PyObject *importlib = PyImport_GetModule(&_Py_ID(importlib));
4604
0
    if (importlib == NULL) {
4605
0
        if (PyErr_Occurred()) {
4606
0
            return NULL;
4607
0
        }
4608
4609
0
        importlib = PyImport_ImportModule("importlib");
4610
0
        if (importlib == NULL) {
4611
0
            return NULL;
4612
0
        }
4613
0
    }
4614
4615
0
    reloaded_module = PyObject_CallMethodOneArg(importlib, &_Py_ID(reload), m);
4616
0
    Py_DECREF(importlib);
4617
0
    return reloaded_module;
4618
0
}
4619
4620
4621
/* Higher-level import emulator which emulates the "import" statement
4622
   more accurately -- it invokes the __import__() function from the
4623
   builtins of the current globals.  This means that the import is
4624
   done using whatever import hooks are installed in the current
4625
   environment.
4626
   A dummy list ["__doc__"] is passed as the 4th argument so that
4627
   e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
4628
   will return <module "gencache"> instead of <module "win32com">. */
4629
4630
PyObject *
4631
PyImport_Import(PyObject *module_name)
4632
239k
{
4633
239k
    PyThreadState *tstate = _PyThreadState_GET();
4634
239k
    PyObject *globals = NULL;
4635
239k
    PyObject *import = NULL;
4636
239k
    PyObject *builtins = NULL;
4637
239k
    PyObject *r = NULL;
4638
4639
239k
    PyObject *from_list = PyList_New(0);
4640
239k
    if (from_list == NULL) {
4641
0
        goto err;
4642
0
    }
4643
4644
    /* Get the builtins from current globals */
4645
239k
    globals = PyEval_GetGlobals();  // borrowed
4646
239k
    if (globals != NULL) {
4647
239k
        Py_INCREF(globals);
4648
        // XXX Use _PyEval_EnsureBuiltins()?
4649
239k
        builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
4650
239k
        if (builtins == NULL) {
4651
            // XXX Fall back to interp->builtins or sys.modules['builtins']?
4652
0
            goto err;
4653
0
        }
4654
239k
    }
4655
272
    else if (_PyErr_Occurred(tstate)) {
4656
0
        goto err;
4657
0
    }
4658
272
    else {
4659
        /* No globals -- use standard builtins, and fake globals */
4660
272
        globals = PyDict_New();
4661
272
        if (globals == NULL) {
4662
0
            goto err;
4663
0
        }
4664
272
        if (_PyEval_EnsureBuiltinsWithModule(tstate, globals, &builtins) < 0) {
4665
0
            goto err;
4666
0
        }
4667
272
    }
4668
4669
    /* Get the __import__ function from the builtins */
4670
239k
    if (PyDict_Check(builtins)) {
4671
239k
        import = PyObject_GetItem(builtins, &_Py_ID(__import__));
4672
239k
        if (import == NULL) {
4673
0
            _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
4674
0
        }
4675
239k
    }
4676
272
    else
4677
272
        import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
4678
239k
    if (import == NULL)
4679
0
        goto err;
4680
4681
    /* Call the __import__ function with the proper argument list
4682
       Always use absolute import here.
4683
       Calling for side-effect of import. */
4684
239k
    r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
4685
239k
                              globals, from_list, 0, NULL);
4686
239k
    if (r == NULL)
4687
0
        goto err;
4688
239k
    Py_DECREF(r);
4689
4690
239k
    r = import_get_module(tstate, module_name);
4691
239k
    if (r == NULL && !_PyErr_Occurred(tstate)) {
4692
0
        _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
4693
0
    }
4694
4695
239k
  err:
4696
239k
    Py_XDECREF(globals);
4697
239k
    Py_XDECREF(builtins);
4698
239k
    Py_XDECREF(import);
4699
239k
    Py_XDECREF(from_list);
4700
4701
239k
    return r;
4702
239k
}
4703
4704
4705
/*********************/
4706
/* runtime lifecycle */
4707
/*********************/
4708
4709
PyStatus
4710
_PyImport_Init(void)
4711
34
{
4712
34
    if (INITTAB != NULL) {
4713
0
        return _PyStatus_ERR("global import state already initialized");
4714
0
    }
4715
34
    if (init_builtin_modules_table() != 0) {
4716
0
        return PyStatus_NoMemory();
4717
0
    }
4718
34
    return _PyStatus_OK();
4719
34
}
4720
4721
void
4722
_PyImport_Fini(void)
4723
0
{
4724
    /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
4725
    // XXX Should we actually leave them (mostly) intact, since we don't
4726
    // ever dlclose() the module files?
4727
0
    _extensions_cache_clear_all();
4728
4729
    /* Free memory allocated by _PyImport_Init() */
4730
0
    fini_builtin_modules_table();
4731
0
}
4732
4733
void
4734
_PyImport_Fini2(void)
4735
0
{
4736
    // Reset PyImport_Inittab
4737
0
    PyImport_Inittab = _PyImport_Inittab;
4738
4739
    /* Free memory allocated by PyImport_ExtendInittab() */
4740
0
    _PyMem_DefaultRawFree(inittab_copy);
4741
0
    inittab_copy = NULL;
4742
0
}
4743
4744
4745
/*************************/
4746
/* interpreter lifecycle */
4747
/*************************/
4748
4749
PyStatus
4750
_PyImport_InitCore(PyThreadState *tstate, PyObject *sysmod, int importlib)
4751
34
{
4752
    // XXX Initialize here: interp->modules and interp->import_func.
4753
    // XXX Initialize here: sys.modules and sys.meta_path.
4754
4755
34
    if (importlib) {
4756
        /* This call sets up builtin and frozen import support */
4757
34
        if (init_importlib(tstate, sysmod) < 0) {
4758
0
            return _PyStatus_ERR("failed to initialize importlib");
4759
0
        }
4760
34
    }
4761
4762
34
    return _PyStatus_OK();
4763
34
}
4764
4765
/* In some corner cases it is important to be sure that the import
4766
   machinery has been initialized (or not cleaned up yet).  For
4767
   example, see issue #4236 and PyModule_Create2(). */
4768
4769
int
4770
_PyImport_IsInitialized(PyInterpreterState *interp)
4771
0
{
4772
0
    if (MODULES(interp) == NULL)
4773
0
        return 0;
4774
0
    return 1;
4775
0
}
4776
4777
/* Clear the direct per-interpreter import state, if not cleared already. */
4778
void
4779
_PyImport_ClearCore(PyInterpreterState *interp)
4780
0
{
4781
    /* interp->modules should have been cleaned up and cleared already
4782
       by _PyImport_FiniCore(). */
4783
0
    Py_CLEAR(MODULES(interp));
4784
0
    Py_CLEAR(MODULES_BY_INDEX(interp));
4785
0
    Py_CLEAR(IMPORTLIB(interp));
4786
0
    Py_CLEAR(IMPORT_FUNC(interp));
4787
0
    Py_CLEAR(LAZY_IMPORT_FUNC(interp));
4788
0
    Py_CLEAR(interp->imports.lazy_modules);
4789
0
    Py_CLEAR(interp->imports.lazy_importing_modules);
4790
0
    Py_CLEAR(interp->imports.lazy_imports_filter);
4791
0
}
4792
4793
void
4794
_PyImport_FiniCore(PyInterpreterState *interp)
4795
0
{
4796
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4797
4798
0
    if (_PySys_ClearAttrString(interp, "meta_path", verbose) < 0) {
4799
0
        PyErr_FormatUnraisable("Exception ignored while "
4800
0
                               "clearing sys.meta_path");
4801
0
    }
4802
4803
    // XXX Pull in most of finalize_modules() in pylifecycle.c.
4804
4805
0
    if (_PySys_ClearAttrString(interp, "modules", verbose) < 0) {
4806
0
        PyErr_FormatUnraisable("Exception ignored while "
4807
0
                               "clearing sys.modules");
4808
0
    }
4809
4810
0
    _PyImport_ClearCore(interp);
4811
0
}
4812
4813
// XXX Add something like _PyImport_Disable() for use early in interp fini?
4814
4815
4816
/* "external" imports */
4817
4818
static int
4819
init_zipimport(PyThreadState *tstate, int verbose)
4820
34
{
4821
34
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
4822
34
    if (path_hooks == NULL) {
4823
0
        return -1;
4824
0
    }
4825
4826
34
    if (verbose) {
4827
0
        PySys_WriteStderr("# installing zipimport hook\n");
4828
0
    }
4829
4830
34
    PyObject *zipimporter = PyImport_ImportModuleAttrString("zipimport", "zipimporter");
4831
34
    if (zipimporter == NULL) {
4832
0
        _PyErr_Clear(tstate); /* No zipimporter object -- okay */
4833
0
        if (verbose) {
4834
0
            PySys_WriteStderr("# can't import zipimport.zipimporter\n");
4835
0
        }
4836
0
    }
4837
34
    else {
4838
        /* sys.path_hooks.insert(0, zipimporter) */
4839
34
        int err = PyList_Insert(path_hooks, 0, zipimporter);
4840
34
        Py_DECREF(zipimporter);
4841
34
        if (err < 0) {
4842
0
            Py_DECREF(path_hooks);
4843
0
            return -1;
4844
0
        }
4845
34
        if (verbose) {
4846
0
            PySys_WriteStderr("# installed zipimport hook\n");
4847
0
        }
4848
34
    }
4849
34
    Py_DECREF(path_hooks);
4850
4851
34
    return 0;
4852
34
}
4853
4854
PyStatus
4855
_PyImport_InitExternal(PyThreadState *tstate)
4856
34
{
4857
34
    int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
4858
4859
    // XXX Initialize here: sys.path_hooks and sys.path_importer_cache.
4860
4861
34
    if (init_importlib_external(tstate->interp) != 0) {
4862
0
        _PyErr_Print(tstate);
4863
0
        return _PyStatus_ERR("external importer setup failed");
4864
0
    }
4865
4866
34
    if (init_zipimport(tstate, verbose) != 0) {
4867
0
        PyErr_Print();
4868
0
        return _PyStatus_ERR("initializing zipimport failed");
4869
0
    }
4870
4871
34
    return _PyStatus_OK();
4872
34
}
4873
4874
void
4875
_PyImport_FiniExternal(PyInterpreterState *interp)
4876
0
{
4877
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4878
4879
    // XXX Uninstall importlib metapath importers here?
4880
4881
0
    if (_PySys_ClearAttrString(interp, "path_importer_cache", verbose) < 0) {
4882
0
        PyErr_FormatUnraisable("Exception ignored while "
4883
0
                               "clearing sys.path_importer_cache");
4884
0
    }
4885
0
    if (_PySys_ClearAttrString(interp, "path_hooks", verbose) < 0) {
4886
0
        PyErr_FormatUnraisable("Exception ignored while "
4887
0
                               "clearing sys.path_hooks");
4888
0
    }
4889
0
}
4890
4891
4892
/******************/
4893
/* module helpers */
4894
/******************/
4895
4896
PyObject *
4897
PyImport_ImportModuleAttr(PyObject *modname, PyObject *attrname)
4898
32.1k
{
4899
32.1k
    PyObject *mod = PyImport_Import(modname);
4900
32.1k
    if (mod == NULL) {
4901
0
        return NULL;
4902
0
    }
4903
32.1k
    PyObject *result = PyObject_GetAttr(mod, attrname);
4904
32.1k
    Py_DECREF(mod);
4905
32.1k
    return result;
4906
32.1k
}
4907
4908
PyObject *
4909
PyImport_ImportModuleAttrString(const char *modname, const char *attrname)
4910
29.9k
{
4911
29.9k
    PyObject *pmodname = PyUnicode_FromString(modname);
4912
29.9k
    if (pmodname == NULL) {
4913
0
        return NULL;
4914
0
    }
4915
29.9k
    PyObject *pattrname = PyUnicode_FromString(attrname);
4916
29.9k
    if (pattrname == NULL) {
4917
0
        Py_DECREF(pmodname);
4918
0
        return NULL;
4919
0
    }
4920
29.9k
    PyObject *result = PyImport_ImportModuleAttr(pmodname, pattrname);
4921
29.9k
    Py_DECREF(pattrname);
4922
29.9k
    Py_DECREF(pmodname);
4923
29.9k
    return result;
4924
29.9k
}
4925
4926
int
4927
PyImport_SetLazyImportsFilter(PyObject *filter)
4928
0
{
4929
0
    if (filter == Py_None) {
4930
0
        filter = NULL;
4931
0
    }
4932
0
    if (filter != NULL && !PyCallable_Check(filter)) {
4933
0
        PyErr_SetString(PyExc_ValueError,
4934
0
                        "filter provided but is not callable");
4935
0
        return -1;
4936
0
    }
4937
4938
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4939
    // Exchange the filter w/ the lock held. We can't use Py_XSETREF
4940
    // because we need to release the lock before the decref.
4941
0
    LAZY_IMPORTS_LOCK(interp);
4942
0
    PyObject *old = LAZY_IMPORTS_FILTER(interp);
4943
0
    LAZY_IMPORTS_FILTER(interp) = Py_XNewRef(filter);
4944
0
    LAZY_IMPORTS_UNLOCK(interp);
4945
0
    Py_XDECREF(old);
4946
0
    return 0;
4947
0
}
4948
4949
/* Return a strong reference to the current lazy imports filter
4950
 * or NULL if none exists. This function always succeeds.
4951
 */
4952
PyObject *
4953
PyImport_GetLazyImportsFilter(void)
4954
0
{
4955
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4956
0
    LAZY_IMPORTS_LOCK(interp);
4957
0
    PyObject *res = Py_XNewRef(LAZY_IMPORTS_FILTER(interp));
4958
0
    LAZY_IMPORTS_UNLOCK(interp);
4959
0
    return res;
4960
0
}
4961
4962
int
4963
PyImport_SetLazyImportsMode(PyImport_LazyImportsMode mode)
4964
0
{
4965
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4966
0
    FT_ATOMIC_STORE_INT_RELAXED(LAZY_IMPORTS_MODE(interp), mode);
4967
0
    return 0;
4968
0
}
4969
4970
/* Checks if lazy imports is globally enabled or disabled. Return 1 when
4971
 * globally forced on, 0 when globally forced off, or -1 when not set.*/
4972
PyImport_LazyImportsMode
4973
PyImport_GetLazyImportsMode(void)
4974
17.0k
{
4975
17.0k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4976
17.0k
    return FT_ATOMIC_LOAD_INT_RELAXED(LAZY_IMPORTS_MODE(interp));
4977
17.0k
}
4978
4979
/**************/
4980
/* the module */
4981
/**************/
4982
4983
/*[clinic input]
4984
_imp.lock_held
4985
4986
Return True if the import lock is currently held, else False.
4987
4988
On platforms without threads, return False.
4989
[clinic start generated code]*/
4990
4991
static PyObject *
4992
_imp_lock_held_impl(PyObject *module)
4993
/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
4994
0
{
4995
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4996
0
    return PyBool_FromLong(PyMutex_IsLocked(&IMPORT_LOCK(interp).mutex));
4997
0
}
4998
4999
/*[clinic input]
5000
@permit_long_docstring_body
5001
_imp.acquire_lock
5002
5003
Acquires the interpreter's import lock for the current thread.
5004
5005
This lock should be used by import hooks to ensure thread-safety when importing
5006
modules. On platforms without threads, this function does nothing.
5007
[clinic start generated code]*/
5008
5009
static PyObject *
5010
_imp_acquire_lock_impl(PyObject *module)
5011
/*[clinic end generated code: output=1aff58cb0ee1b026 input=e1a4ef049d34e7dd]*/
5012
78.1k
{
5013
78.1k
    PyInterpreterState *interp = _PyInterpreterState_GET();
5014
78.1k
    _PyImport_AcquireLock(interp);
5015
78.1k
    Py_RETURN_NONE;
5016
78.1k
}
5017
5018
/*[clinic input]
5019
_imp.release_lock
5020
5021
Release the interpreter's import lock.
5022
5023
On platforms without threads, this function does nothing.
5024
[clinic start generated code]*/
5025
5026
static PyObject *
5027
_imp_release_lock_impl(PyObject *module)
5028
/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
5029
78.1k
{
5030
78.1k
    PyInterpreterState *interp = _PyInterpreterState_GET();
5031
78.1k
    if (!_PyRecursiveMutex_IsLockedByCurrentThread(&IMPORT_LOCK(interp))) {
5032
0
        PyErr_SetString(PyExc_RuntimeError,
5033
0
                        "not holding the import lock");
5034
0
        return NULL;
5035
0
    }
5036
78.1k
    _PyImport_ReleaseLock(interp);
5037
78.1k
    Py_RETURN_NONE;
5038
78.1k
}
5039
5040
5041
/*[clinic input]
5042
_imp._fix_co_filename
5043
5044
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
5045
        Code object to change.
5046
5047
    path: unicode
5048
        File path to use.
5049
    /
5050
5051
Changes code.co_filename to specify the passed-in file path.
5052
[clinic start generated code]*/
5053
5054
static PyObject *
5055
_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
5056
                           PyObject *path)
5057
/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
5058
5059
7.32k
{
5060
7.32k
    update_compiled_module(code, path);
5061
5062
7.32k
    Py_RETURN_NONE;
5063
7.32k
}
5064
5065
5066
/*[clinic input]
5067
_imp.create_builtin
5068
5069
    spec: object
5070
    /
5071
5072
Create an extension module.
5073
[clinic start generated code]*/
5074
5075
static PyObject *
5076
_imp_create_builtin(PyObject *module, PyObject *spec)
5077
/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
5078
687
{
5079
687
    PyThreadState *tstate = _PyThreadState_GET();
5080
5081
687
    PyObject *name = PyObject_GetAttrString(spec, "name");
5082
687
    if (name == NULL) {
5083
0
        return NULL;
5084
0
    }
5085
5086
687
    if (!PyUnicode_Check(name)) {
5087
0
        PyErr_Format(PyExc_TypeError,
5088
0
                     "name must be string, not %.200s",
5089
0
                     Py_TYPE(name)->tp_name);
5090
0
        Py_DECREF(name);
5091
0
        return NULL;
5092
0
    }
5093
5094
687
    if (PyUnicode_GetLength(name) == 0) {
5095
0
        PyErr_Format(PyExc_ValueError, "name must not be empty");
5096
0
        Py_DECREF(name);
5097
0
        return NULL;
5098
0
    }
5099
5100
687
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
5101
687
    Py_DECREF(name);
5102
687
    return mod;
5103
687
}
5104
5105
5106
/*[clinic input]
5107
_imp.extension_suffixes
5108
5109
Returns the list of file suffixes used to identify extension modules.
5110
[clinic start generated code]*/
5111
5112
static PyObject *
5113
_imp_extension_suffixes_impl(PyObject *module)
5114
/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
5115
68
{
5116
68
    PyObject *list;
5117
5118
68
    list = PyList_New(0);
5119
68
    if (list == NULL)
5120
0
        return NULL;
5121
68
#ifdef HAVE_DYNAMIC_LOADING
5122
68
    const char *suffix;
5123
68
    unsigned int index = 0;
5124
5125
272
    while ((suffix = _PyImport_DynLoadFiletab[index])) {
5126
204
        PyObject *item = PyUnicode_FromString(suffix);
5127
204
        if (item == NULL) {
5128
0
            Py_DECREF(list);
5129
0
            return NULL;
5130
0
        }
5131
204
        if (PyList_Append(list, item) < 0) {
5132
0
            Py_DECREF(list);
5133
0
            Py_DECREF(item);
5134
0
            return NULL;
5135
0
        }
5136
204
        Py_DECREF(item);
5137
204
        index += 1;
5138
204
    }
5139
68
#endif
5140
68
    return list;
5141
68
}
5142
5143
/*[clinic input]
5144
_imp.init_frozen
5145
5146
    name: unicode
5147
    /
5148
5149
Initializes a frozen module.
5150
[clinic start generated code]*/
5151
5152
static PyObject *
5153
_imp_init_frozen_impl(PyObject *module, PyObject *name)
5154
/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
5155
0
{
5156
0
    PyThreadState *tstate = _PyThreadState_GET();
5157
0
    int ret;
5158
5159
0
    ret = PyImport_ImportFrozenModuleObject(name);
5160
0
    if (ret < 0)
5161
0
        return NULL;
5162
0
    if (ret == 0) {
5163
0
        Py_RETURN_NONE;
5164
0
    }
5165
0
    return import_add_module(tstate, name);
5166
0
}
5167
5168
/*[clinic input]
5169
_imp.find_frozen
5170
5171
    name: unicode
5172
    /
5173
    *
5174
    withdata: bool = False
5175
5176
Return info about the corresponding frozen module (if there is one) or None.
5177
5178
The returned info (a 2-tuple):
5179
5180
 * data         the raw marshalled bytes
5181
 * is_package   whether or not it is a package
5182
 * origname     the originally frozen module's name, or None if not
5183
                a stdlib module (this will usually be the same as
5184
                the module's current name)
5185
[clinic start generated code]*/
5186
5187
static PyObject *
5188
_imp_find_frozen_impl(PyObject *module, PyObject *name, int withdata)
5189
/*[clinic end generated code: output=8c1c3c7f925397a5 input=22a8847c201542fd]*/
5190
15.0k
{
5191
15.0k
    struct frozen_info info;
5192
15.0k
    frozen_status status = find_frozen(name, &info);
5193
15.0k
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
5194
14.6k
        Py_RETURN_NONE;
5195
14.6k
    }
5196
421
    else if (status == FROZEN_BAD_NAME) {
5197
0
        Py_RETURN_NONE;
5198
0
    }
5199
421
    else if (status != FROZEN_OKAY) {
5200
0
        set_frozen_error(status, name);
5201
0
        return NULL;
5202
0
    }
5203
5204
421
    PyObject *data = NULL;
5205
421
    if (withdata) {
5206
0
        data = PyMemoryView_FromMemory((char *)info.data, info.size, PyBUF_READ);
5207
0
        if (data == NULL) {
5208
0
            return NULL;
5209
0
        }
5210
0
    }
5211
5212
421
    PyObject *origname = NULL;
5213
421
    if (info.origname != NULL && info.origname[0] != '\0') {
5214
421
        origname = PyUnicode_FromString(info.origname);
5215
421
        if (origname == NULL) {
5216
0
            Py_XDECREF(data);
5217
0
            return NULL;
5218
0
        }
5219
421
    }
5220
5221
421
    PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
5222
421
                                    info.is_package ? Py_True : Py_False,
5223
421
                                    origname ? origname : Py_None);
5224
421
    Py_XDECREF(origname);
5225
421
    Py_XDECREF(data);
5226
421
    return result;
5227
421
}
5228
5229
/*[clinic input]
5230
_imp.get_frozen_object
5231
5232
    name: unicode
5233
    data as dataobj: object = None
5234
    /
5235
5236
Create a code object for a frozen module.
5237
[clinic start generated code]*/
5238
5239
static PyObject *
5240
_imp_get_frozen_object_impl(PyObject *module, PyObject *name,
5241
                            PyObject *dataobj)
5242
/*[clinic end generated code: output=54368a673a35e745 input=034bdb88f6460b7b]*/
5243
421
{
5244
421
    struct frozen_info info = {0};
5245
421
    Py_buffer buf = {0};
5246
421
    if (PyObject_CheckBuffer(dataobj)) {
5247
0
        if (PyObject_GetBuffer(dataobj, &buf, PyBUF_SIMPLE) != 0) {
5248
0
            return NULL;
5249
0
        }
5250
0
        info.data = (const char *)buf.buf;
5251
0
        info.size = buf.len;
5252
0
    }
5253
421
    else if (dataobj != Py_None) {
5254
0
        _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
5255
0
        return NULL;
5256
0
    }
5257
421
    else {
5258
421
        frozen_status status = find_frozen(name, &info);
5259
421
        if (status != FROZEN_OKAY) {
5260
0
            set_frozen_error(status, name);
5261
0
            return NULL;
5262
0
        }
5263
421
    }
5264
5265
421
    if (info.nameobj == NULL) {
5266
0
        info.nameobj = name;
5267
0
    }
5268
421
    if (info.size == 0) {
5269
        /* Does not contain executable code. */
5270
0
        set_frozen_error(FROZEN_INVALID, name);
5271
0
        return NULL;
5272
0
    }
5273
5274
421
    PyInterpreterState *interp = _PyInterpreterState_GET();
5275
421
    PyObject *codeobj = unmarshal_frozen_code(interp, &info);
5276
421
    if (dataobj != Py_None) {
5277
0
        PyBuffer_Release(&buf);
5278
0
    }
5279
421
    return codeobj;
5280
421
}
5281
5282
/*[clinic input]
5283
_imp.is_frozen_package
5284
5285
    name: unicode
5286
    /
5287
5288
Returns True if the module name is of a frozen package.
5289
[clinic start generated code]*/
5290
5291
static PyObject *
5292
_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
5293
/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
5294
34
{
5295
34
    struct frozen_info info;
5296
34
    frozen_status status = find_frozen(name, &info);
5297
34
    if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
5298
0
        set_frozen_error(status, name);
5299
0
        return NULL;
5300
0
    }
5301
34
    return PyBool_FromLong(info.is_package);
5302
34
}
5303
5304
/*[clinic input]
5305
_imp.is_builtin
5306
5307
    name: unicode
5308
    /
5309
5310
Returns True if the module name corresponds to a built-in module.
5311
[clinic start generated code]*/
5312
5313
static PyObject *
5314
_imp_is_builtin_impl(PyObject *module, PyObject *name)
5315
/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
5316
15.7k
{
5317
15.7k
    return PyLong_FromLong(is_builtin(name));
5318
15.7k
}
5319
5320
/*[clinic input]
5321
_imp.is_frozen
5322
5323
    name: unicode
5324
    /
5325
5326
Returns True if the module name corresponds to a frozen module.
5327
[clinic start generated code]*/
5328
5329
static PyObject *
5330
_imp_is_frozen_impl(PyObject *module, PyObject *name)
5331
/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
5332
34
{
5333
34
    struct frozen_info info;
5334
34
    frozen_status status = find_frozen(name, &info);
5335
34
    if (status != FROZEN_OKAY) {
5336
0
        Py_RETURN_FALSE;
5337
0
    }
5338
34
    Py_RETURN_TRUE;
5339
34
}
5340
5341
/*[clinic input]
5342
_imp._frozen_module_names
5343
5344
Returns the list of available frozen modules.
5345
[clinic start generated code]*/
5346
5347
static PyObject *
5348
_imp__frozen_module_names_impl(PyObject *module)
5349
/*[clinic end generated code: output=80609ef6256310a8 input=76237fbfa94460d2]*/
5350
0
{
5351
0
    return list_frozen_module_names();
5352
0
}
5353
5354
/*[clinic input]
5355
_imp._override_frozen_modules_for_tests
5356
5357
    override: int
5358
    /
5359
5360
(internal-only) Override PyConfig.use_frozen_modules.
5361
5362
(-1: "off", 1: "on", 0: no override)
5363
See frozen_modules() in Lib/test/support/import_helper.py.
5364
[clinic start generated code]*/
5365
5366
static PyObject *
5367
_imp__override_frozen_modules_for_tests_impl(PyObject *module, int override)
5368
/*[clinic end generated code: output=36d5cb1594160811 input=8f1f95a3ef21aec3]*/
5369
0
{
5370
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
5371
0
    OVERRIDE_FROZEN_MODULES(interp) = override;
5372
0
    Py_RETURN_NONE;
5373
0
}
5374
5375
/*[clinic input]
5376
_imp._override_multi_interp_extensions_check
5377
5378
    override: int
5379
    /
5380
5381
(internal-only) Override PyInterpreterConfig.check_multi_interp_extensions.
5382
5383
(-1: "never", 1: "always", 0: no override)
5384
[clinic start generated code]*/
5385
5386
static PyObject *
5387
_imp__override_multi_interp_extensions_check_impl(PyObject *module,
5388
                                                  int override)
5389
/*[clinic end generated code: output=3ff043af52bbf280 input=e086a2ea181f92ae]*/
5390
0
{
5391
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
5392
0
    if (_Py_IsMainInterpreter(interp)) {
5393
0
        PyErr_SetString(PyExc_RuntimeError,
5394
0
                        "_imp._override_multi_interp_extensions_check() "
5395
0
                        "cannot be used in the main interpreter");
5396
0
        return NULL;
5397
0
    }
5398
#ifdef Py_GIL_DISABLED
5399
    PyErr_SetString(PyExc_RuntimeError,
5400
                    "_imp._override_multi_interp_extensions_check() "
5401
                    "cannot be used in the free-threaded build");
5402
    return NULL;
5403
#else
5404
0
    int oldvalue = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
5405
0
    OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) = override;
5406
0
    return PyLong_FromLong(oldvalue);
5407
0
#endif
5408
0
}
5409
5410
#ifdef HAVE_DYNAMIC_LOADING
5411
5412
/*[clinic input]
5413
_imp.create_dynamic
5414
5415
    spec: object
5416
    file: object = NULL
5417
    /
5418
5419
Create an extension module.
5420
[clinic start generated code]*/
5421
5422
static PyObject *
5423
_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
5424
/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
5425
227
{
5426
227
    FILE *fp = NULL;
5427
227
    PyObject *mod = NULL;
5428
227
    PyThreadState *tstate = _PyThreadState_GET();
5429
5430
227
    struct _Py_ext_module_loader_info info;
5431
227
    if (_Py_ext_module_loader_info_init_from_spec(&info, spec) < 0) {
5432
0
        return NULL;
5433
0
    }
5434
5435
227
    struct extensions_cache_value *cached = NULL;
5436
227
    mod = import_find_extension(tstate, &info, &cached);
5437
227
    if (mod != NULL) {
5438
0
        assert(!_PyErr_Occurred(tstate));
5439
0
        assert(cached != NULL);
5440
        /* The module might not have md_def set in certain reload cases. */
5441
0
        assert(_PyModule_GetDefOrNull(mod) == NULL
5442
0
                || cached->def == _PyModule_GetDefOrNull(mod));
5443
0
        assert_singlephase(cached);
5444
0
        goto finally;
5445
0
    }
5446
227
    else if (_PyErr_Occurred(tstate)) {
5447
0
        goto finally;
5448
0
    }
5449
    /* Otherwise it must be multi-phase init or the first time it's loaded. */
5450
5451
    /* If the module was added to the global cache
5452
     * but def->m_base.m_copy was cleared (e.g. subinterp fini)
5453
     * then we have to do a little dance here. */
5454
227
    if (cached != NULL) {
5455
0
        assert(cached->def->m_base.m_copy == NULL);
5456
        /* For now we clear the cache and move on. */
5457
0
        _extensions_cache_delete(info.path, info.name);
5458
0
    }
5459
5460
227
    if (PySys_Audit("import", "OOOOO", info.name, info.filename,
5461
227
                    Py_None, Py_None, Py_None) < 0)
5462
0
    {
5463
0
        goto finally;
5464
0
    }
5465
5466
    /* We would move this (and the fclose() below) into
5467
     * _PyImport_GetModuleExportHooks(), but it isn't clear if the intervening
5468
     * code relies on fp still being open. */
5469
227
    if (file != NULL) {
5470
0
        fp = Py_fopen(info.filename, "r");
5471
0
        if (fp == NULL) {
5472
0
            goto finally;
5473
0
        }
5474
0
    }
5475
5476
227
    PyModInitFunction p0 = NULL;
5477
227
    PyModExportFunction ex0 = NULL;
5478
227
    _PyImport_GetModuleExportHooks(&info, fp, &p0, &ex0);
5479
227
    if (ex0) {
5480
0
        mod = import_run_modexport(tstate, ex0, &info, spec);
5481
        // Modules created from slots handle GIL enablement (Py_mod_gil slot)
5482
        // when they're created.
5483
0
        goto finally;
5484
0
    }
5485
227
    if (p0 == NULL) {
5486
4
        goto finally;
5487
4
    }
5488
5489
#ifdef Py_GIL_DISABLED
5490
    // This call (and the corresponding call to _PyImport_CheckGILForModule())
5491
    // would ideally be inside import_run_extension(). They are kept in the
5492
    // callers for now because that would complicate the control flow inside
5493
    // import_run_extension(). It should be possible to restructure
5494
    // import_run_extension() to address this.
5495
    _PyEval_EnableGILTransient(tstate);
5496
#endif
5497
223
    mod = import_run_extension(
5498
223
                    tstate, p0, &info, spec, get_modules_dict(tstate, true));
5499
#ifdef Py_GIL_DISABLED
5500
    if (_PyImport_CheckGILForModule(mod, info.name) < 0) {
5501
        Py_CLEAR(mod);
5502
        goto finally;
5503
    }
5504
#endif
5505
5506
227
finally:
5507
227
    if (fp != NULL) {
5508
0
        fclose(fp);
5509
0
    }
5510
227
    _Py_ext_module_loader_info_clear(&info);
5511
227
    return mod;
5512
223
}
5513
5514
/*[clinic input]
5515
_imp.exec_dynamic -> int
5516
5517
    mod: object
5518
    /
5519
5520
Initialize an extension module.
5521
[clinic start generated code]*/
5522
5523
static int
5524
_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
5525
/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
5526
223
{
5527
223
    return exec_builtin_or_dynamic(mod);
5528
223
}
5529
5530
5531
#endif /* HAVE_DYNAMIC_LOADING */
5532
5533
/*[clinic input]
5534
_imp.exec_builtin -> int
5535
5536
    mod: object
5537
    /
5538
5539
Initialize a built-in module.
5540
[clinic start generated code]*/
5541
5542
static int
5543
_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
5544
/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
5545
687
{
5546
687
    return exec_builtin_or_dynamic(mod);
5547
687
}
5548
5549
/*[clinic input]
5550
_imp.source_hash
5551
5552
    key: long
5553
    source: Py_buffer
5554
[clinic start generated code]*/
5555
5556
static PyObject *
5557
_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
5558
/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
5559
0
{
5560
0
    union {
5561
0
        uint64_t x;
5562
0
        char data[sizeof(uint64_t)];
5563
0
    } hash;
5564
0
    hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
5565
#if !PY_LITTLE_ENDIAN
5566
    // Force to little-endian. There really ought to be a succinct standard way
5567
    // to do this.
5568
    for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
5569
        char tmp = hash.data[i];
5570
        hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
5571
        hash.data[sizeof(hash.data) - i - 1] = tmp;
5572
    }
5573
#endif
5574
0
    return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
5575
0
}
5576
5577
static int
5578
publish_lazy_imports_on_module(PyThreadState *tstate,
5579
                               PyObject *lazy_submodules,
5580
                               PyObject *name,
5581
                               PyObject *module_dict)
5582
16
{
5583
16
    PyObject *builtins = _PyEval_GetBuiltins(tstate);
5584
16
    PyObject *attr_name;
5585
16
    Py_ssize_t pos = 0;
5586
16
    Py_hash_t hash;
5587
5588
    // Enumerate the set of lazy submodules which have been imported from the
5589
    // parent module.
5590
32
    while (_PySet_NextEntryRef(lazy_submodules, &pos, &attr_name, &hash)) {
5591
16
        if (_PyDict_Contains_KnownHash(module_dict, attr_name, hash)) {
5592
16
            Py_DECREF(attr_name);
5593
16
            continue;
5594
16
        }
5595
        // Create a new lazy module attr for the subpackage which was
5596
        // previously lazily imported.
5597
0
        PyObject *lazy_module_attr = _PyLazyImport_New(tstate->current_frame, builtins,
5598
0
                                                       name, attr_name);
5599
0
        if (lazy_module_attr == NULL) {
5600
0
            Py_DECREF(attr_name);
5601
0
            return -1;
5602
0
        }
5603
5604
        // Publish on the module that was just imported.
5605
0
        if (PyDict_SetItem(module_dict, attr_name,
5606
0
                           lazy_module_attr) < 0) {
5607
0
            Py_DECREF(lazy_module_attr);
5608
0
            Py_DECREF(attr_name);
5609
0
            return -1;
5610
0
        }
5611
0
        Py_DECREF(lazy_module_attr);
5612
0
        Py_DECREF(attr_name);
5613
0
    }
5614
16
    return 0;
5615
16
}
5616
5617
/*[clinic input]
5618
_imp._set_lazy_attributes
5619
    modobj: object
5620
    name: unicode
5621
    /
5622
Sets attributes to lazy submodules on the module, as side effects.
5623
[clinic start generated code]*/
5624
5625
static PyObject *
5626
_imp__set_lazy_attributes_impl(PyObject *module, PyObject *modobj,
5627
                               PyObject *name)
5628
/*[clinic end generated code: output=3369bb3242b1f043 input=38ea6f30956dd7d6]*/
5629
3.39k
{
5630
3.39k
    PyThreadState *tstate = _PyThreadState_GET();
5631
3.39k
    PyObject *module_dict = NULL;
5632
3.39k
    PyObject *ret = NULL;
5633
3.39k
    PyObject *lazy_modules = LAZY_MODULES(tstate->interp);
5634
3.39k
    assert(lazy_modules != NULL);
5635
5636
3.39k
    PyObject *lazy_submodules;
5637
3.39k
    if (PyDict_GetItemRef(lazy_modules, name, &lazy_submodules) < 0) {
5638
0
        return NULL;
5639
0
    }
5640
3.39k
    else if (lazy_submodules == NULL) {
5641
3.37k
        Py_RETURN_NONE;
5642
3.37k
    }
5643
5644
16
    module_dict = get_mod_dict(modobj);
5645
16
    if (module_dict == NULL || !PyDict_CheckExact(module_dict)) {
5646
0
        Py_DECREF(lazy_submodules);
5647
0
        goto done;
5648
0
    }
5649
5650
16
    assert(PyAnySet_CheckExact(lazy_submodules));
5651
16
    Py_BEGIN_CRITICAL_SECTION(lazy_submodules);
5652
16
    publish_lazy_imports_on_module(tstate, lazy_submodules, name, module_dict);
5653
16
    Py_END_CRITICAL_SECTION();
5654
16
    Py_DECREF(lazy_submodules);
5655
5656
    // once a module is imported it is removed from sys.lazy_modules
5657
16
    if (PyDict_DelItem(lazy_modules, name) < 0) {
5658
0
        goto error;
5659
0
    }
5660
5661
16
done:
5662
16
    ret = Py_NewRef(Py_None);
5663
5664
16
error:
5665
16
    Py_XDECREF(module_dict);
5666
16
    return ret;
5667
16
}
5668
5669
PyDoc_STRVAR(doc_imp,
5670
"(Extremely) low-level import machinery bits as used by importlib.");
5671
5672
static PyMethodDef imp_methods[] = {
5673
    _IMP_EXTENSION_SUFFIXES_METHODDEF
5674
    _IMP_LOCK_HELD_METHODDEF
5675
    _IMP_ACQUIRE_LOCK_METHODDEF
5676
    _IMP_RELEASE_LOCK_METHODDEF
5677
    _IMP_FIND_FROZEN_METHODDEF
5678
    _IMP_GET_FROZEN_OBJECT_METHODDEF
5679
    _IMP_IS_FROZEN_PACKAGE_METHODDEF
5680
    _IMP_CREATE_BUILTIN_METHODDEF
5681
    _IMP_INIT_FROZEN_METHODDEF
5682
    _IMP_IS_BUILTIN_METHODDEF
5683
    _IMP_IS_FROZEN_METHODDEF
5684
    _IMP__FROZEN_MODULE_NAMES_METHODDEF
5685
    _IMP__OVERRIDE_FROZEN_MODULES_FOR_TESTS_METHODDEF
5686
    _IMP__OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK_METHODDEF
5687
    _IMP_CREATE_DYNAMIC_METHODDEF
5688
    _IMP_EXEC_DYNAMIC_METHODDEF
5689
    _IMP_EXEC_BUILTIN_METHODDEF
5690
    _IMP__FIX_CO_FILENAME_METHODDEF
5691
    _IMP_SOURCE_HASH_METHODDEF
5692
    _IMP__SET_LAZY_ATTRIBUTES_METHODDEF
5693
    {NULL, NULL}  /* sentinel */
5694
};
5695
5696
5697
static int
5698
imp_module_exec(PyObject *module)
5699
34
{
5700
34
    const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
5701
34
    PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
5702
34
    if (PyModule_Add(module, "check_hash_based_pycs", pyc_mode) < 0) {
5703
0
        return -1;
5704
0
    }
5705
5706
34
    if (PyModule_AddIntConstant(
5707
34
            module, "pyc_magic_number_token", PYC_MAGIC_NUMBER_TOKEN) < 0)
5708
0
    {
5709
0
        return -1;
5710
0
    }
5711
5712
34
    return 0;
5713
34
}
5714
5715
5716
static PyModuleDef_Slot imp_slots[] = {
5717
    {Py_mod_exec, imp_module_exec},
5718
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
5719
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
5720
    {0, NULL}
5721
};
5722
5723
static struct PyModuleDef imp_module = {
5724
    PyModuleDef_HEAD_INIT,
5725
    .m_name = "_imp",
5726
    .m_doc = doc_imp,
5727
    .m_size = 0,
5728
    .m_methods = imp_methods,
5729
    .m_slots = imp_slots,
5730
};
5731
5732
PyMODINIT_FUNC
5733
PyInit__imp(void)
5734
34
{
5735
34
    return PyModuleDef_Init(&imp_module);
5736
34
}