Coverage Report

Created: 2025-11-30 06:38

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