Coverage Report

Created: 2026-01-17 06:16

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
13.7k
#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
4.25M
    (interp)->imports.modules
86
#define MODULES_BY_INDEX(interp) \
87
308
    (interp)->imports.modules_by_index
88
#define IMPORTLIB(interp) \
89
16.1k
    (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
12.7k
    (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
2.37M
    (interp)->imports.import_func
100
101
#define IMPORT_LOCK(interp) \
102
192k
    (interp)->imports.lock
103
104
#define FIND_AND_LOAD(interp) \
105
13.0k
    (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
64.2k
{
128
64.2k
    _PyRecursiveMutex_Lock(&IMPORT_LOCK(interp));
129
64.2k
}
130
131
void
132
_PyImport_ReleaseLock(PyInterpreterState *interp)
133
64.2k
{
134
64.2k
    _PyRecursiveMutex_Unlock(&IMPORT_LOCK(interp));
135
64.2k
}
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
701k
{
163
701k
    return MODULES(interp);
164
701k
}
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
3.54M
{
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
3.54M
    PyObject *modules = MODULES(tstate->interp);
195
3.54M
    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
3.54M
    return modules;
204
3.54M
}
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
3.54M
{
232
3.54M
    PyObject *modules = get_modules_dict(tstate, false);
233
3.54M
    if (modules == NULL) {
234
0
        return NULL;
235
0
    }
236
237
3.54M
    PyObject *m;
238
3.54M
    Py_INCREF(modules);
239
3.54M
    (void)PyMapping_GetOptionalItem(modules, name, &m);
240
3.54M
    Py_DECREF(modules);
241
3.54M
    return m;
242
3.54M
}
243
244
static int
245
import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
246
3.29M
{
247
3.29M
    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
3.29M
    int rc = PyObject_GetOptionalAttr(mod, &_Py_ID(__spec__), &spec);
255
3.29M
    if (rc > 0) {
256
3.29M
        rc = _PyModuleSpec_IsInitializing(spec);
257
3.29M
        Py_DECREF(spec);
258
3.29M
    }
259
3.29M
    if (rc == 0) {
260
3.29M
        goto done;
261
3.29M
    }
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
3.29M
done:
275
    /* When -X importtime=2, print an import time entry even if an
276
       imported module has already been loaded.
277
     */
278
3.29M
    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
3.29M
    return 0;
287
436
}
288
289
static void remove_importlib_frames(PyThreadState *tstate);
290
291
PyObject *
292
PyImport_GetModule(PyObject *name)
293
701k
{
294
701k
    PyThreadState *tstate = _PyThreadState_GET();
295
701k
    PyObject *mod;
296
297
701k
    mod = import_get_module(tstate, name);
298
701k
    if (mod != NULL && mod != Py_None) {
299
701k
        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
701k
    }
305
701k
    return mod;
306
701k
}
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
                "module export hook for module %R 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
            "module export hook for module %R 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
13.0k
{
2373
13.0k
    int i;
2374
13.0k
    struct _inittab *inittab = INITTAB;
2375
499k
    for (i = 0; inittab[i].name != NULL; i++) {
2376
487k
        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
487k
    }
2383
12.5k
    return 0;
2384
13.0k
}
2385
2386
static struct _inittab*
2387
lookup_inittab_entry(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 p;
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 = NULL;
2434
560
    if (initfunc == NULL) {
2435
560
        struct _inittab *entry = lookup_inittab_entry(&info);
2436
560
        if (entry == NULL) {
2437
0
            mod = NULL;
2438
0
            _PyErr_SetModuleNotFoundError(name);
2439
0
            goto finally;
2440
0
        }
2441
2442
560
        p0 = (PyModInitFunction)entry->initfunc;
2443
560
    }
2444
0
    else {
2445
0
        p0 = initfunc;
2446
0
    }
2447
2448
560
    if (p0 == NULL) {
2449
        /* Cannot re-init internal module ("sys" or "builtins") */
2450
0
        assert(is_core_module(tstate->interp, info.name, info.path));
2451
0
        mod = import_add_module(tstate, info.name);
2452
0
        goto finally;
2453
0
    }
2454
2455
2456
#ifdef Py_GIL_DISABLED
2457
    // This call (and the corresponding call to _PyImport_CheckGILForModule())
2458
    // would ideally be inside import_run_extension(). They are kept in the
2459
    // callers for now because that would complicate the control flow inside
2460
    // import_run_extension(). It should be possible to restructure
2461
    // import_run_extension() to address this.
2462
    _PyEval_EnableGILTransient(tstate);
2463
#endif
2464
    /* Now load it. */
2465
560
    mod = import_run_extension(
2466
560
                    tstate, p0, &info, spec, get_modules_dict(tstate, true));
2467
#ifdef Py_GIL_DISABLED
2468
    if (_PyImport_CheckGILForModule(mod, info.name) < 0) {
2469
        Py_CLEAR(mod);
2470
        goto finally;
2471
    }
2472
#endif
2473
2474
560
finally:
2475
560
    _Py_ext_module_loader_info_clear(&info);
2476
560
    return mod;
2477
560
}
2478
2479
PyObject*
2480
PyImport_CreateModuleFromInitfunc(
2481
    PyObject *spec, PyObject *(*initfunc)(void))
2482
0
{
2483
0
    if (initfunc == NULL) {
2484
0
        PyErr_BadInternalCall();
2485
0
        return NULL;
2486
0
    }
2487
2488
0
    PyThreadState *tstate = _PyThreadState_GET();
2489
2490
0
    PyObject *name = PyObject_GetAttr(spec, &_Py_ID(name));
2491
0
    if (name == NULL) {
2492
0
        return NULL;
2493
0
    }
2494
2495
0
    if (!PyUnicode_Check(name)) {
2496
0
        PyErr_Format(PyExc_TypeError,
2497
0
                     "spec name must be string, not %T", name);
2498
0
        Py_DECREF(name);
2499
0
        return NULL;
2500
0
    }
2501
2502
0
    PyObject *mod = create_builtin(tstate, name, spec, initfunc);
2503
0
    Py_DECREF(name);
2504
0
    return mod;
2505
0
}
2506
2507
/*****************************/
2508
/* the builtin modules table */
2509
/*****************************/
2510
2511
/* API for embedding applications that want to add their own entries
2512
   to the table of built-in modules.  This should normally be called
2513
   *before* Py_Initialize().  When the table resize fails, -1 is
2514
   returned and the existing table is unchanged.
2515
2516
   After a similar function by Just van Rossum. */
2517
2518
int
2519
PyImport_ExtendInittab(struct _inittab *newtab)
2520
0
{
2521
0
    struct _inittab *p;
2522
0
    size_t i, n;
2523
0
    int res = 0;
2524
2525
0
    if (INITTAB != NULL) {
2526
0
        Py_FatalError("PyImport_ExtendInittab() may not be called after Py_Initialize()");
2527
0
    }
2528
2529
    /* Count the number of entries in both tables */
2530
0
    for (n = 0; newtab[n].name != NULL; n++)
2531
0
        ;
2532
0
    if (n == 0)
2533
0
        return 0; /* Nothing to do */
2534
0
    for (i = 0; PyImport_Inittab[i].name != NULL; i++)
2535
0
        ;
2536
2537
    /* Force default raw memory allocator to get a known allocator to be able
2538
       to release the memory in _PyImport_Fini2() */
2539
    /* Allocate new memory for the combined table */
2540
0
    p = NULL;
2541
0
    if (i + n <= SIZE_MAX / sizeof(struct _inittab) - 1) {
2542
0
        size_t size = sizeof(struct _inittab) * (i + n + 1);
2543
0
        p = _PyMem_DefaultRawRealloc(inittab_copy, size);
2544
0
    }
2545
0
    if (p == NULL) {
2546
0
        res = -1;
2547
0
        goto done;
2548
0
    }
2549
2550
    /* Copy the tables into the new memory at the first call
2551
       to PyImport_ExtendInittab(). */
2552
0
    if (inittab_copy != PyImport_Inittab) {
2553
0
        memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
2554
0
    }
2555
0
    memcpy(p + i, newtab, (n + 1) * sizeof(struct _inittab));
2556
0
    PyImport_Inittab = inittab_copy = p;
2557
0
done:
2558
0
    return res;
2559
0
}
2560
2561
/* Shorthand to add a single entry given a name and a function */
2562
2563
int
2564
PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void))
2565
0
{
2566
0
    struct _inittab newtab[2];
2567
2568
0
    if (INITTAB != NULL) {
2569
0
        Py_FatalError("PyImport_AppendInittab() may not be called after Py_Initialize()");
2570
0
    }
2571
2572
0
    memset(newtab, '\0', sizeof newtab);
2573
2574
0
    newtab[0].name = name;
2575
0
    newtab[0].initfunc = initfunc;
2576
2577
0
    return PyImport_ExtendInittab(newtab);
2578
0
}
2579
2580
2581
/* the internal table */
2582
2583
static int
2584
init_builtin_modules_table(void)
2585
28
{
2586
28
    size_t size;
2587
1.09k
    for (size = 0; PyImport_Inittab[size].name != NULL; size++)
2588
1.06k
        ;
2589
28
    size++;
2590
2591
    /* Make the copy. */
2592
28
    struct _inittab *copied = _PyMem_DefaultRawMalloc(size * sizeof(struct _inittab));
2593
28
    if (copied == NULL) {
2594
0
        return -1;
2595
0
    }
2596
28
    memcpy(copied, PyImport_Inittab, size * sizeof(struct _inittab));
2597
28
    INITTAB = copied;
2598
28
    return 0;
2599
28
}
2600
2601
static void
2602
fini_builtin_modules_table(void)
2603
0
{
2604
0
    struct _inittab *inittab = INITTAB;
2605
0
    INITTAB = NULL;
2606
0
    _PyMem_DefaultRawFree(inittab);
2607
0
}
2608
2609
PyObject *
2610
_PyImport_GetBuiltinModuleNames(void)
2611
28
{
2612
28
    PyObject *list = PyList_New(0);
2613
28
    if (list == NULL) {
2614
0
        return NULL;
2615
0
    }
2616
28
    struct _inittab *inittab = INITTAB;
2617
1.09k
    for (Py_ssize_t i = 0; inittab[i].name != NULL; i++) {
2618
1.06k
        PyObject *name = PyUnicode_FromString(inittab[i].name);
2619
1.06k
        if (name == NULL) {
2620
0
            Py_DECREF(list);
2621
0
            return NULL;
2622
0
        }
2623
1.06k
        if (PyList_Append(list, name) < 0) {
2624
0
            Py_DECREF(name);
2625
0
            Py_DECREF(list);
2626
0
            return NULL;
2627
0
        }
2628
1.06k
        Py_DECREF(name);
2629
1.06k
    }
2630
28
    return list;
2631
28
}
2632
2633
2634
/********************/
2635
/* the magic number */
2636
/********************/
2637
2638
/* Helper for pythonrun.c -- return magic number and tag. */
2639
2640
long
2641
PyImport_GetMagicNumber(void)
2642
0
{
2643
0
    return PYC_MAGIC_NUMBER_TOKEN;
2644
0
}
2645
2646
extern const char * _PySys_ImplCacheTag;
2647
2648
const char *
2649
PyImport_GetMagicTag(void)
2650
0
{
2651
0
    return _PySys_ImplCacheTag;
2652
0
}
2653
2654
2655
/*********************************/
2656
/* a Python module's code object */
2657
/*********************************/
2658
2659
/* Execute a code object in a module and return the module object
2660
 * WITH INCREMENTED REFERENCE COUNT.  If an error occurs, name is
2661
 * removed from sys.modules, to avoid leaving damaged module objects
2662
 * in sys.modules.  The caller may wish to restore the original
2663
 * module object (if any) in this case; PyImport_ReloadModule is an
2664
 * example.
2665
 *
2666
 * Note that PyImport_ExecCodeModuleWithPathnames() is the preferred, richer
2667
 * interface.  The other two exist primarily for backward compatibility.
2668
 */
2669
PyObject *
2670
PyImport_ExecCodeModule(const char *name, PyObject *co)
2671
0
{
2672
0
    return PyImport_ExecCodeModuleWithPathnames(
2673
0
        name, co, (char *)NULL, (char *)NULL);
2674
0
}
2675
2676
PyObject *
2677
PyImport_ExecCodeModuleEx(const char *name, PyObject *co, const char *pathname)
2678
0
{
2679
0
    return PyImport_ExecCodeModuleWithPathnames(
2680
0
        name, co, pathname, (char *)NULL);
2681
0
}
2682
2683
PyObject *
2684
PyImport_ExecCodeModuleWithPathnames(const char *name, PyObject *co,
2685
                                     const char *pathname,
2686
                                     const char *cpathname)
2687
0
{
2688
0
    PyObject *m = NULL;
2689
0
    PyObject *nameobj, *pathobj = NULL, *cpathobj = NULL, *external= NULL;
2690
2691
0
    nameobj = PyUnicode_FromString(name);
2692
0
    if (nameobj == NULL)
2693
0
        return NULL;
2694
2695
0
    if (cpathname != NULL) {
2696
0
        cpathobj = PyUnicode_DecodeFSDefault(cpathname);
2697
0
        if (cpathobj == NULL)
2698
0
            goto error;
2699
0
    }
2700
0
    else
2701
0
        cpathobj = NULL;
2702
2703
0
    if (pathname != NULL) {
2704
0
        pathobj = PyUnicode_DecodeFSDefault(pathname);
2705
0
        if (pathobj == NULL)
2706
0
            goto error;
2707
0
    }
2708
0
    else if (cpathobj != NULL) {
2709
0
        PyInterpreterState *interp = _PyInterpreterState_GET();
2710
2711
0
        if (interp == NULL) {
2712
0
            Py_FatalError("no current interpreter");
2713
0
        }
2714
2715
0
        external= PyObject_GetAttrString(IMPORTLIB(interp),
2716
0
                                         "_bootstrap_external");
2717
0
        if (external != NULL) {
2718
0
            pathobj = PyObject_CallMethodOneArg(
2719
0
                external, &_Py_ID(_get_sourcefile), cpathobj);
2720
0
            Py_DECREF(external);
2721
0
        }
2722
0
        if (pathobj == NULL)
2723
0
            PyErr_Clear();
2724
0
    }
2725
0
    else
2726
0
        pathobj = NULL;
2727
2728
0
    m = PyImport_ExecCodeModuleObject(nameobj, co, pathobj, cpathobj);
2729
0
error:
2730
0
    Py_DECREF(nameobj);
2731
0
    Py_XDECREF(pathobj);
2732
0
    Py_XDECREF(cpathobj);
2733
0
    return m;
2734
0
}
2735
2736
static PyObject *
2737
module_dict_for_exec(PyThreadState *tstate, PyObject *name)
2738
28
{
2739
28
    PyObject *m, *d;
2740
2741
28
    m = import_add_module(tstate, name);
2742
28
    if (m == NULL)
2743
0
        return NULL;
2744
    /* If the module is being reloaded, we get the old module back
2745
       and re-use its dict to exec the new code. */
2746
28
    d = PyModule_GetDict(m);
2747
28
    int r = PyDict_Contains(d, &_Py_ID(__builtins__));
2748
28
    if (r == 0) {
2749
28
        r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins());
2750
28
    }
2751
28
    if (r < 0) {
2752
0
        remove_module(tstate, name);
2753
0
        Py_DECREF(m);
2754
0
        return NULL;
2755
0
    }
2756
2757
28
    Py_INCREF(d);
2758
28
    Py_DECREF(m);
2759
28
    return d;
2760
28
}
2761
2762
static PyObject *
2763
exec_code_in_module(PyThreadState *tstate, PyObject *name,
2764
                    PyObject *module_dict, PyObject *code_object)
2765
28
{
2766
28
    PyObject *v, *m;
2767
2768
28
    v = PyEval_EvalCode(code_object, module_dict, module_dict);
2769
28
    if (v == NULL) {
2770
0
        remove_module(tstate, name);
2771
0
        return NULL;
2772
0
    }
2773
28
    Py_DECREF(v);
2774
2775
28
    m = import_get_module(tstate, name);
2776
28
    if (m == NULL && !_PyErr_Occurred(tstate)) {
2777
0
        _PyErr_Format(tstate, PyExc_ImportError,
2778
0
                      "Loaded module %R not found in sys.modules",
2779
0
                      name);
2780
0
    }
2781
2782
28
    return m;
2783
28
}
2784
2785
PyObject*
2786
PyImport_ExecCodeModuleObject(PyObject *name, PyObject *co, PyObject *pathname,
2787
                              PyObject *cpathname)
2788
0
{
2789
0
    PyThreadState *tstate = _PyThreadState_GET();
2790
0
    PyObject *d, *external, *res;
2791
2792
0
    d = module_dict_for_exec(tstate, name);
2793
0
    if (d == NULL) {
2794
0
        return NULL;
2795
0
    }
2796
2797
0
    if (pathname == NULL) {
2798
0
        pathname = ((PyCodeObject *)co)->co_filename;
2799
0
    }
2800
0
    external = PyObject_GetAttrString(IMPORTLIB(tstate->interp),
2801
0
                                      "_bootstrap_external");
2802
0
    if (external == NULL) {
2803
0
        Py_DECREF(d);
2804
0
        return NULL;
2805
0
    }
2806
0
    res = PyObject_CallMethodObjArgs(external, &_Py_ID(_fix_up_module),
2807
0
                                     d, name, pathname, cpathname, NULL);
2808
0
    Py_DECREF(external);
2809
0
    if (res != NULL) {
2810
0
        Py_DECREF(res);
2811
0
        res = exec_code_in_module(tstate, name, d, co);
2812
0
    }
2813
0
    Py_DECREF(d);
2814
0
    return res;
2815
0
}
2816
2817
2818
static void
2819
update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
2820
0
{
2821
0
    PyObject *constants, *tmp;
2822
0
    Py_ssize_t i, n;
2823
2824
0
    if (PyUnicode_Compare(co->co_filename, oldname))
2825
0
        return;
2826
2827
0
    Py_XSETREF(co->co_filename, Py_NewRef(newname));
2828
2829
0
    constants = co->co_consts;
2830
0
    n = PyTuple_GET_SIZE(constants);
2831
0
    for (i = 0; i < n; i++) {
2832
0
        tmp = PyTuple_GET_ITEM(constants, i);
2833
0
        if (PyCode_Check(tmp))
2834
0
            update_code_filenames((PyCodeObject *)tmp,
2835
0
                                  oldname, newname);
2836
0
    }
2837
0
}
2838
2839
static void
2840
update_compiled_module(PyCodeObject *co, PyObject *newname)
2841
5.59k
{
2842
5.59k
    PyObject *oldname;
2843
2844
5.59k
    if (PyUnicode_Compare(co->co_filename, newname) == 0)
2845
5.59k
        return;
2846
2847
0
    oldname = co->co_filename;
2848
0
    Py_INCREF(oldname);
2849
0
    update_code_filenames(co, oldname, newname);
2850
0
    Py_DECREF(oldname);
2851
0
}
2852
2853
2854
/******************/
2855
/* frozen modules */
2856
/******************/
2857
2858
/* Return true if the name is an alias.  In that case, "alias" is set
2859
   to the original module name.  If it is an alias but the original
2860
   module isn't known then "alias" is set to NULL while true is returned. */
2861
static bool
2862
resolve_module_alias(const char *name, const struct _module_alias *aliases,
2863
                     const char **alias)
2864
758
{
2865
758
    const struct _module_alias *entry;
2866
5.75k
    for (entry = aliases; ; entry++) {
2867
5.75k
        if (entry->name == NULL) {
2868
            /* It isn't an alias. */
2869
618
            return false;
2870
618
        }
2871
5.14k
        if (strcmp(name, entry->name) == 0) {
2872
140
            if (alias != NULL) {
2873
140
                *alias = entry->orig;
2874
140
            }
2875
140
            return true;
2876
140
        }
2877
5.14k
    }
2878
758
}
2879
2880
static bool
2881
use_frozen(void)
2882
12.7k
{
2883
12.7k
    PyInterpreterState *interp = _PyInterpreterState_GET();
2884
12.7k
    int override = OVERRIDE_FROZEN_MODULES(interp);
2885
12.7k
    if (override > 0) {
2886
0
        return true;
2887
0
    }
2888
12.7k
    else if (override < 0) {
2889
0
        return false;
2890
0
    }
2891
12.7k
    else {
2892
12.7k
        return interp->config.use_frozen_modules;
2893
12.7k
    }
2894
12.7k
}
2895
2896
static PyObject *
2897
list_frozen_module_names(void)
2898
0
{
2899
0
    PyObject *names = PyList_New(0);
2900
0
    if (names == NULL) {
2901
0
        return NULL;
2902
0
    }
2903
0
    bool enabled = use_frozen();
2904
0
    const struct _frozen *p;
2905
0
#define ADD_MODULE(name) \
2906
0
    do { \
2907
0
        PyObject *nameobj = PyUnicode_FromString(name); \
2908
0
        if (nameobj == NULL) { \
2909
0
            goto error; \
2910
0
        } \
2911
0
        int res = PyList_Append(names, nameobj); \
2912
0
        Py_DECREF(nameobj); \
2913
0
        if (res != 0) { \
2914
0
            goto error; \
2915
0
        } \
2916
0
    } while(0)
2917
    // We always use the bootstrap modules.
2918
0
    for (p = _PyImport_FrozenBootstrap; ; p++) {
2919
0
        if (p->name == NULL) {
2920
0
            break;
2921
0
        }
2922
0
        ADD_MODULE(p->name);
2923
0
    }
2924
    // Frozen stdlib modules may be disabled.
2925
0
    for (p = _PyImport_FrozenStdlib; ; p++) {
2926
0
        if (p->name == NULL) {
2927
0
            break;
2928
0
        }
2929
0
        if (enabled) {
2930
0
            ADD_MODULE(p->name);
2931
0
        }
2932
0
    }
2933
0
    for (p = _PyImport_FrozenTest; ; p++) {
2934
0
        if (p->name == NULL) {
2935
0
            break;
2936
0
        }
2937
0
        if (enabled) {
2938
0
            ADD_MODULE(p->name);
2939
0
        }
2940
0
    }
2941
0
#undef ADD_MODULE
2942
    // Add any custom modules.
2943
0
    if (PyImport_FrozenModules != NULL) {
2944
0
        for (p = PyImport_FrozenModules; ; p++) {
2945
0
            if (p->name == NULL) {
2946
0
                break;
2947
0
            }
2948
0
            PyObject *nameobj = PyUnicode_FromString(p->name);
2949
0
            if (nameobj == NULL) {
2950
0
                goto error;
2951
0
            }
2952
0
            int found = PySequence_Contains(names, nameobj);
2953
0
            if (found < 0) {
2954
0
                Py_DECREF(nameobj);
2955
0
                goto error;
2956
0
            }
2957
0
            else if (found) {
2958
0
                Py_DECREF(nameobj);
2959
0
            }
2960
0
            else {
2961
0
                int res = PyList_Append(names, nameobj);
2962
0
                Py_DECREF(nameobj);
2963
0
                if (res != 0) {
2964
0
                    goto error;
2965
0
                }
2966
0
            }
2967
0
        }
2968
0
    }
2969
0
    return names;
2970
2971
0
error:
2972
0
    Py_DECREF(names);
2973
0
    return NULL;
2974
0
}
2975
2976
typedef enum {
2977
    FROZEN_OKAY,
2978
    FROZEN_BAD_NAME,    // The given module name wasn't valid.
2979
    FROZEN_NOT_FOUND,   // It wasn't in PyImport_FrozenModules.
2980
    FROZEN_DISABLED,    // -X frozen_modules=off (and not essential)
2981
    FROZEN_EXCLUDED,    /* The PyImport_FrozenModules entry has NULL "code"
2982
                           (module is present but marked as unimportable, stops search). */
2983
    FROZEN_INVALID,     /* The PyImport_FrozenModules entry is bogus
2984
                           (eg. does not contain executable code). */
2985
} frozen_status;
2986
2987
static inline void
2988
set_frozen_error(frozen_status status, PyObject *modname)
2989
0
{
2990
0
    const char *err = NULL;
2991
0
    switch (status) {
2992
0
        case FROZEN_BAD_NAME:
2993
0
        case FROZEN_NOT_FOUND:
2994
0
            err = "No such frozen object named %R";
2995
0
            break;
2996
0
        case FROZEN_DISABLED:
2997
0
            err = "Frozen modules are disabled and the frozen object named %R is not essential";
2998
0
            break;
2999
0
        case FROZEN_EXCLUDED:
3000
0
            err = "Excluded frozen object named %R";
3001
0
            break;
3002
0
        case FROZEN_INVALID:
3003
0
            err = "Frozen object named %R is invalid";
3004
0
            break;
3005
0
        case FROZEN_OKAY:
3006
            // There was no error.
3007
0
            break;
3008
0
        default:
3009
0
            Py_UNREACHABLE();
3010
0
    }
3011
0
    if (err != NULL) {
3012
0
        PyObject *msg = PyUnicode_FromFormat(err, modname);
3013
0
        if (msg == NULL) {
3014
0
            PyErr_Clear();
3015
0
        }
3016
0
        PyErr_SetImportError(msg, modname, NULL);
3017
0
        Py_XDECREF(msg);
3018
0
    }
3019
0
}
3020
3021
static const struct _frozen *
3022
look_up_frozen(const char *name)
3023
12.9k
{
3024
12.9k
    const struct _frozen *p;
3025
    // We always use the bootstrap modules.
3026
51.5k
    for (p = _PyImport_FrozenBootstrap; ; p++) {
3027
51.5k
        if (p->name == NULL) {
3028
            // We hit the end-of-list sentinel value.
3029
12.7k
            break;
3030
12.7k
        }
3031
38.7k
        if (strcmp(name, p->name) == 0) {
3032
196
            return p;
3033
196
        }
3034
38.7k
    }
3035
    // Prefer custom modules, if any.  Frozen stdlib modules can be
3036
    // disabled here by setting "code" to NULL in the array entry.
3037
12.7k
    if (PyImport_FrozenModules != NULL) {
3038
0
        for (p = PyImport_FrozenModules; ; p++) {
3039
0
            if (p->name == NULL) {
3040
0
                break;
3041
0
            }
3042
0
            if (strcmp(name, p->name) == 0) {
3043
0
                return p;
3044
0
            }
3045
0
        }
3046
0
    }
3047
    // Frozen stdlib modules may be disabled.
3048
12.7k
    if (use_frozen()) {
3049
186k
        for (p = _PyImport_FrozenStdlib; ; p++) {
3050
186k
            if (p->name == NULL) {
3051
12.2k
                break;
3052
12.2k
            }
3053
174k
            if (strcmp(name, p->name) == 0) {
3054
562
                return p;
3055
562
            }
3056
174k
        }
3057
146k
        for (p = _PyImport_FrozenTest; ; p++) {
3058
146k
            if (p->name == NULL) {
3059
12.2k
                break;
3060
12.2k
            }
3061
134k
            if (strcmp(name, p->name) == 0) {
3062
0
                return p;
3063
0
            }
3064
134k
        }
3065
12.2k
    }
3066
12.2k
    return NULL;
3067
12.7k
}
3068
3069
struct frozen_info {
3070
    PyObject *nameobj;
3071
    const char *data;
3072
    Py_ssize_t size;
3073
    bool is_package;
3074
    bool is_alias;
3075
    const char *origname;
3076
};
3077
3078
static frozen_status
3079
find_frozen(PyObject *nameobj, struct frozen_info *info)
3080
12.9k
{
3081
12.9k
    if (info != NULL) {
3082
12.9k
        memset(info, 0, sizeof(*info));
3083
12.9k
    }
3084
3085
12.9k
    if (nameobj == NULL || nameobj == Py_None) {
3086
0
        return FROZEN_BAD_NAME;
3087
0
    }
3088
12.9k
    const char *name = PyUnicode_AsUTF8(nameobj);
3089
12.9k
    if (name == NULL) {
3090
        // Note that this function previously used
3091
        // _PyUnicode_EqualToASCIIString().  We clear the error here
3092
        // (instead of propagating it) to match the earlier behavior
3093
        // more closely.
3094
0
        PyErr_Clear();
3095
0
        return FROZEN_BAD_NAME;
3096
0
    }
3097
3098
12.9k
    const struct _frozen *p = look_up_frozen(name);
3099
12.9k
    if (p == NULL) {
3100
12.2k
        return FROZEN_NOT_FOUND;
3101
12.2k
    }
3102
758
    if (info != NULL) {
3103
758
        info->nameobj = nameobj;  // borrowed
3104
758
        info->data = (const char *)p->code;
3105
758
        info->size = p->size;
3106
758
        info->is_package = p->is_package;
3107
758
        if (p->size < 0) {
3108
            // backward compatibility with negative size values
3109
0
            info->size = -(p->size);
3110
0
            info->is_package = true;
3111
0
        }
3112
758
        info->origname = name;
3113
758
        info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
3114
758
                                              &info->origname);
3115
758
    }
3116
758
    if (p->code == NULL) {
3117
        /* It is frozen but marked as un-importable. */
3118
0
        return FROZEN_EXCLUDED;
3119
0
    }
3120
758
    if (p->code[0] == '\0' || p->size == 0) {
3121
        /* Does not contain executable code. */
3122
0
        return FROZEN_INVALID;
3123
0
    }
3124
758
    return FROZEN_OKAY;
3125
758
}
3126
3127
static PyObject *
3128
unmarshal_frozen_code(PyInterpreterState *interp, struct frozen_info *info)
3129
365
{
3130
365
    PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
3131
365
    if (co == NULL) {
3132
        /* Does not contain executable code. */
3133
0
        PyErr_Clear();
3134
0
        set_frozen_error(FROZEN_INVALID, info->nameobj);
3135
0
        return NULL;
3136
0
    }
3137
365
    if (!PyCode_Check(co)) {
3138
        // We stick with TypeError for backward compatibility.
3139
0
        PyErr_Format(PyExc_TypeError,
3140
0
                     "frozen object %R is not a code object",
3141
0
                     info->nameobj);
3142
0
        Py_DECREF(co);
3143
0
        return NULL;
3144
0
    }
3145
365
    return co;
3146
365
}
3147
3148
3149
/* Initialize a frozen module.
3150
   Return 1 for success, 0 if the module is not found, and -1 with
3151
   an exception set if the initialization failed.
3152
   This function is also used from frozenmain.c */
3153
3154
int
3155
PyImport_ImportFrozenModuleObject(PyObject *name)
3156
28
{
3157
28
    PyThreadState *tstate = _PyThreadState_GET();
3158
28
    PyObject *co, *m, *d = NULL;
3159
28
    int err;
3160
3161
28
    struct frozen_info info;
3162
28
    frozen_status status = find_frozen(name, &info);
3163
28
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
3164
0
        return 0;
3165
0
    }
3166
28
    else if (status == FROZEN_BAD_NAME) {
3167
0
        return 0;
3168
0
    }
3169
28
    else if (status != FROZEN_OKAY) {
3170
0
        set_frozen_error(status, name);
3171
0
        return -1;
3172
0
    }
3173
28
    co = unmarshal_frozen_code(tstate->interp, &info);
3174
28
    if (co == NULL) {
3175
0
        return -1;
3176
0
    }
3177
28
    if (info.is_package) {
3178
        /* Set __path__ to the empty list */
3179
0
        PyObject *l;
3180
0
        m = import_add_module(tstate, name);
3181
0
        if (m == NULL)
3182
0
            goto err_return;
3183
0
        d = PyModule_GetDict(m);
3184
0
        l = PyList_New(0);
3185
0
        if (l == NULL) {
3186
0
            Py_DECREF(m);
3187
0
            goto err_return;
3188
0
        }
3189
0
        err = PyDict_SetItemString(d, "__path__", l);
3190
0
        Py_DECREF(l);
3191
0
        Py_DECREF(m);
3192
0
        if (err != 0)
3193
0
            goto err_return;
3194
0
    }
3195
28
    d = module_dict_for_exec(tstate, name);
3196
28
    if (d == NULL) {
3197
0
        goto err_return;
3198
0
    }
3199
28
    m = exec_code_in_module(tstate, name, d, co);
3200
28
    if (m == NULL) {
3201
0
        goto err_return;
3202
0
    }
3203
28
    Py_DECREF(m);
3204
    /* Set __origname__ (consumed in FrozenImporter._setup_module()). */
3205
28
    PyObject *origname;
3206
28
    if (info.origname) {
3207
28
        origname = PyUnicode_FromString(info.origname);
3208
28
        if (origname == NULL) {
3209
0
            goto err_return;
3210
0
        }
3211
28
    }
3212
0
    else {
3213
0
        origname = Py_NewRef(Py_None);
3214
0
    }
3215
28
    err = PyDict_SetItemString(d, "__origname__", origname);
3216
28
    Py_DECREF(origname);
3217
28
    if (err != 0) {
3218
0
        goto err_return;
3219
0
    }
3220
28
    Py_DECREF(d);
3221
28
    Py_DECREF(co);
3222
28
    return 1;
3223
3224
0
err_return:
3225
0
    Py_XDECREF(d);
3226
0
    Py_DECREF(co);
3227
0
    return -1;
3228
28
}
3229
3230
int
3231
PyImport_ImportFrozenModule(const char *name)
3232
28
{
3233
28
    PyObject *nameobj;
3234
28
    int ret;
3235
28
    nameobj = PyUnicode_InternFromString(name);
3236
28
    if (nameobj == NULL)
3237
0
        return -1;
3238
28
    ret = PyImport_ImportFrozenModuleObject(nameobj);
3239
28
    Py_DECREF(nameobj);
3240
28
    return ret;
3241
28
}
3242
3243
3244
/*************/
3245
/* importlib */
3246
/*************/
3247
3248
/* Import the _imp extension by calling manually _imp.create_builtin() and
3249
   _imp.exec_builtin() since importlib is not initialized yet. Initializing
3250
   importlib requires the _imp module: this function fix the bootstrap issue.
3251
 */
3252
static PyObject*
3253
bootstrap_imp(PyThreadState *tstate)
3254
28
{
3255
28
    PyObject *name = PyUnicode_FromString("_imp");
3256
28
    if (name == NULL) {
3257
0
        return NULL;
3258
0
    }
3259
3260
    // Mock a ModuleSpec object just good enough for PyModule_FromDefAndSpec():
3261
    // an object with just a name attribute.
3262
    //
3263
    // _imp.__spec__ is overridden by importlib._bootstrap._instal() anyway.
3264
28
    PyObject *attrs = Py_BuildValue("{sO}", "name", name);
3265
28
    if (attrs == NULL) {
3266
0
        goto error;
3267
0
    }
3268
28
    PyObject *spec = _PyNamespace_New(attrs);
3269
28
    Py_DECREF(attrs);
3270
28
    if (spec == NULL) {
3271
0
        goto error;
3272
0
    }
3273
3274
    // Create the _imp module from its definition.
3275
28
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
3276
28
    Py_CLEAR(name);
3277
28
    Py_DECREF(spec);
3278
28
    if (mod == NULL) {
3279
0
        goto error;
3280
0
    }
3281
28
    assert(mod != Py_None);  // not found
3282
3283
    // Execute the _imp module: call imp_module_exec().
3284
28
    if (exec_builtin_or_dynamic(mod) < 0) {
3285
0
        Py_DECREF(mod);
3286
0
        goto error;
3287
0
    }
3288
28
    return mod;
3289
3290
0
error:
3291
0
    Py_XDECREF(name);
3292
0
    return NULL;
3293
28
}
3294
3295
/* Global initializations.  Can be undone by Py_FinalizeEx().  Don't
3296
   call this twice without an intervening Py_FinalizeEx() call.  When
3297
   initializations fail, a fatal error is issued and the function does
3298
   not return.  On return, the first thread and interpreter state have
3299
   been created.
3300
3301
   Locking: you must hold the interpreter lock while calling this.
3302
   (If the lock has not yet been initialized, that's equivalent to
3303
   having the lock, but you cannot use multiple threads.)
3304
3305
*/
3306
static int
3307
init_importlib(PyThreadState *tstate, PyObject *sysmod)
3308
28
{
3309
28
    assert(!_PyErr_Occurred(tstate));
3310
3311
28
    PyInterpreterState *interp = tstate->interp;
3312
28
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
3313
3314
    // Import _importlib through its frozen version, _frozen_importlib.
3315
28
    if (verbose) {
3316
0
        PySys_FormatStderr("import _frozen_importlib # frozen\n");
3317
0
    }
3318
28
    if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
3319
0
        return -1;
3320
0
    }
3321
3322
28
    PyObject *importlib = PyImport_AddModuleRef("_frozen_importlib");
3323
28
    if (importlib == NULL) {
3324
0
        return -1;
3325
0
    }
3326
28
    IMPORTLIB(interp) = importlib;
3327
3328
    // Import the _imp module
3329
28
    if (verbose) {
3330
0
        PySys_FormatStderr("import _imp # builtin\n");
3331
0
    }
3332
28
    PyObject *imp_mod = bootstrap_imp(tstate);
3333
28
    if (imp_mod == NULL) {
3334
0
        return -1;
3335
0
    }
3336
28
    if (_PyImport_SetModuleString("_imp", imp_mod) < 0) {
3337
0
        Py_DECREF(imp_mod);
3338
0
        return -1;
3339
0
    }
3340
3341
    // Install importlib as the implementation of import
3342
28
    PyObject *value = PyObject_CallMethod(importlib, "_install",
3343
28
                                          "OO", sysmod, imp_mod);
3344
28
    Py_DECREF(imp_mod);
3345
28
    if (value == NULL) {
3346
0
        return -1;
3347
0
    }
3348
28
    Py_DECREF(value);
3349
3350
28
    assert(!_PyErr_Occurred(tstate));
3351
28
    return 0;
3352
28
}
3353
3354
3355
static int
3356
init_importlib_external(PyInterpreterState *interp)
3357
28
{
3358
28
    PyObject *value;
3359
28
    value = PyObject_CallMethod(IMPORTLIB(interp),
3360
28
                                "_install_external_importers", "");
3361
28
    if (value == NULL) {
3362
0
        return -1;
3363
0
    }
3364
28
    Py_DECREF(value);
3365
28
    return 0;
3366
28
}
3367
3368
PyObject *
3369
_PyImport_GetImportlibLoader(PyInterpreterState *interp,
3370
                             const char *loader_name)
3371
28
{
3372
28
    return PyObject_GetAttrString(IMPORTLIB(interp), loader_name);
3373
28
}
3374
3375
PyObject *
3376
_PyImport_GetImportlibExternalLoader(PyInterpreterState *interp,
3377
                                     const char *loader_name)
3378
0
{
3379
0
    PyObject *bootstrap = PyObject_GetAttrString(IMPORTLIB(interp),
3380
0
                                                 "_bootstrap_external");
3381
0
    if (bootstrap == NULL) {
3382
0
        return NULL;
3383
0
    }
3384
3385
0
    PyObject *loader_type = PyObject_GetAttrString(bootstrap, loader_name);
3386
0
    Py_DECREF(bootstrap);
3387
0
    return loader_type;
3388
0
}
3389
3390
PyObject *
3391
_PyImport_BlessMyLoader(PyInterpreterState *interp, PyObject *module_globals)
3392
0
{
3393
0
    PyObject *external = PyObject_GetAttrString(IMPORTLIB(interp),
3394
0
                                                "_bootstrap_external");
3395
0
    if (external == NULL) {
3396
0
        return NULL;
3397
0
    }
3398
3399
0
    PyObject *loader = PyObject_CallMethod(external, "_bless_my_loader",
3400
0
                                           "O", module_globals, NULL);
3401
0
    Py_DECREF(external);
3402
0
    return loader;
3403
0
}
3404
3405
PyObject *
3406
_PyImport_ImportlibModuleRepr(PyInterpreterState *interp, PyObject *m)
3407
0
{
3408
0
    return PyObject_CallMethod(IMPORTLIB(interp), "_module_repr", "O", m);
3409
0
}
3410
3411
3412
/*******************/
3413
3414
/* Return a finder object for a sys.path/pkg.__path__ item 'p',
3415
   possibly by fetching it from the path_importer_cache dict. If it
3416
   wasn't yet cached, traverse path_hooks until a hook is found
3417
   that can handle the path item. Return None if no hook could;
3418
   this tells our caller that the path based finder could not find
3419
   a finder for this path item. Cache the result in
3420
   path_importer_cache. */
3421
3422
static PyObject *
3423
get_path_importer(PyThreadState *tstate, PyObject *path_importer_cache,
3424
                  PyObject *path_hooks, PyObject *p)
3425
0
{
3426
0
    PyObject *importer;
3427
0
    Py_ssize_t j, nhooks;
3428
3429
0
    if (!PyList_Check(path_hooks)) {
3430
0
        PyErr_SetString(PyExc_RuntimeError, "sys.path_hooks is not a list");
3431
0
        return NULL;
3432
0
    }
3433
0
    if (!PyDict_Check(path_importer_cache)) {
3434
0
        PyErr_SetString(PyExc_RuntimeError, "sys.path_importer_cache is not a dict");
3435
0
        return NULL;
3436
0
    }
3437
3438
0
    nhooks = PyList_Size(path_hooks);
3439
0
    if (nhooks < 0)
3440
0
        return NULL; /* Shouldn't happen */
3441
3442
0
    if (PyDict_GetItemRef(path_importer_cache, p, &importer) != 0) {
3443
        // found or error
3444
0
        return importer;
3445
0
    }
3446
    // not found
3447
    /* set path_importer_cache[p] to None to avoid recursion */
3448
0
    if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
3449
0
        return NULL;
3450
3451
0
    for (j = 0; j < nhooks; j++) {
3452
0
        PyObject *hook = PyList_GetItem(path_hooks, j);
3453
0
        if (hook == NULL)
3454
0
            return NULL;
3455
0
        importer = PyObject_CallOneArg(hook, p);
3456
0
        if (importer != NULL)
3457
0
            break;
3458
3459
0
        if (!_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
3460
0
            return NULL;
3461
0
        }
3462
0
        _PyErr_Clear(tstate);
3463
0
    }
3464
0
    if (importer == NULL) {
3465
0
        Py_RETURN_NONE;
3466
0
    }
3467
0
    if (PyDict_SetItem(path_importer_cache, p, importer) < 0) {
3468
0
        Py_DECREF(importer);
3469
0
        return NULL;
3470
0
    }
3471
0
    return importer;
3472
0
}
3473
3474
PyObject *
3475
PyImport_GetImporter(PyObject *path)
3476
0
{
3477
0
    PyThreadState *tstate = _PyThreadState_GET();
3478
0
    PyObject *path_importer_cache = PySys_GetAttrString("path_importer_cache");
3479
0
    if (path_importer_cache == NULL) {
3480
0
        return NULL;
3481
0
    }
3482
0
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
3483
0
    if (path_hooks == NULL) {
3484
0
        Py_DECREF(path_importer_cache);
3485
0
        return NULL;
3486
0
    }
3487
0
    PyObject *importer = get_path_importer(tstate, path_importer_cache, path_hooks, path);
3488
0
    Py_DECREF(path_hooks);
3489
0
    Py_DECREF(path_importer_cache);
3490
0
    return importer;
3491
0
}
3492
3493
3494
/*********************/
3495
/* importing modules */
3496
/*********************/
3497
3498
int
3499
_PyImport_InitDefaultImportFunc(PyInterpreterState *interp)
3500
28
{
3501
    // Get the __import__ function
3502
28
    PyObject *import_func;
3503
28
    if (PyDict_GetItemStringRef(interp->builtins, "__import__", &import_func) <= 0) {
3504
0
        return -1;
3505
0
    }
3506
28
    IMPORT_FUNC(interp) = import_func;
3507
28
    return 0;
3508
28
}
3509
3510
int
3511
_PyImport_IsDefaultImportFunc(PyInterpreterState *interp, PyObject *func)
3512
2.36M
{
3513
2.36M
    return func == IMPORT_FUNC(interp);
3514
2.36M
}
3515
3516
3517
/* Import a module, either built-in, frozen, or external, and return
3518
   its module object WITH INCREMENTED REFERENCE COUNT */
3519
3520
PyObject *
3521
PyImport_ImportModule(const char *name)
3522
422
{
3523
422
    PyObject *pname;
3524
422
    PyObject *result;
3525
3526
422
    pname = PyUnicode_FromString(name);
3527
422
    if (pname == NULL)
3528
0
        return NULL;
3529
422
    result = PyImport_Import(pname);
3530
422
    Py_DECREF(pname);
3531
422
    return result;
3532
422
}
3533
3534
3535
/* Import a module without blocking
3536
 *
3537
 * At first it tries to fetch the module from sys.modules. If the module was
3538
 * never loaded before it loads it with PyImport_ImportModule() unless another
3539
 * thread holds the import lock. In the latter case the function raises an
3540
 * ImportError instead of blocking.
3541
 *
3542
 * Returns the module object with incremented ref count.
3543
 *
3544
 * Removed in 3.15, but kept for stable ABI compatibility.
3545
 */
3546
PyAPI_FUNC(PyObject *)
3547
PyImport_ImportModuleNoBlock(const char *name)
3548
0
{
3549
0
    if (PyErr_WarnEx(PyExc_DeprecationWarning,
3550
0
        "PyImport_ImportModuleNoBlock() is deprecated and scheduled for "
3551
0
        "removal in Python 3.15. Use PyImport_ImportModule() instead.", 1))
3552
0
    {
3553
0
        return NULL;
3554
0
    }
3555
0
    return PyImport_ImportModule(name);
3556
0
}
3557
3558
3559
/* Remove importlib frames from the traceback,
3560
 * except in Verbose mode. */
3561
static void
3562
remove_importlib_frames(PyThreadState *tstate)
3563
11.0k
{
3564
11.0k
    const char *importlib_filename = "<frozen importlib._bootstrap>";
3565
11.0k
    const char *external_filename = "<frozen importlib._bootstrap_external>";
3566
11.0k
    const char *remove_frames = "_call_with_frames_removed";
3567
11.0k
    int always_trim = 0;
3568
11.0k
    int in_importlib = 0;
3569
11.0k
    PyObject **prev_link, **outer_link = NULL;
3570
11.0k
    PyObject *base_tb = NULL;
3571
3572
    /* Synopsis: if it's an ImportError, we trim all importlib chunks
3573
       from the traceback. We always trim chunks
3574
       which end with a call to "_call_with_frames_removed". */
3575
3576
11.0k
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3577
11.0k
    if (exc == NULL || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
3578
0
        goto done;
3579
0
    }
3580
3581
11.0k
    if (PyType_IsSubtype(Py_TYPE(exc), (PyTypeObject *) PyExc_ImportError)) {
3582
11.0k
        always_trim = 1;
3583
11.0k
    }
3584
3585
11.0k
    assert(PyExceptionInstance_Check(exc));
3586
11.0k
    base_tb = PyException_GetTraceback(exc);
3587
11.0k
    prev_link = &base_tb;
3588
11.0k
    PyObject *tb = base_tb;
3589
52.0k
    while (tb != NULL) {
3590
41.0k
        assert(PyTraceBack_Check(tb));
3591
41.0k
        PyTracebackObject *traceback = (PyTracebackObject *)tb;
3592
41.0k
        PyObject *next = (PyObject *) traceback->tb_next;
3593
41.0k
        PyFrameObject *frame = traceback->tb_frame;
3594
41.0k
        PyCodeObject *code = PyFrame_GetCode(frame);
3595
41.0k
        int now_in_importlib;
3596
3597
41.0k
        now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
3598
9.51k
                           _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
3599
41.0k
        if (now_in_importlib && !in_importlib) {
3600
            /* This is the link to this chunk of importlib tracebacks */
3601
11.0k
            outer_link = prev_link;
3602
11.0k
        }
3603
41.0k
        in_importlib = now_in_importlib;
3604
3605
41.0k
        if (in_importlib &&
3606
36.2k
            (always_trim ||
3607
36.2k
             _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
3608
36.2k
            Py_XSETREF(*outer_link, Py_XNewRef(next));
3609
36.2k
            prev_link = outer_link;
3610
36.2k
        }
3611
4.76k
        else {
3612
4.76k
            prev_link = (PyObject **) &traceback->tb_next;
3613
4.76k
        }
3614
41.0k
        Py_DECREF(code);
3615
41.0k
        tb = next;
3616
41.0k
    }
3617
11.0k
    if (base_tb == NULL) {
3618
6.25k
        base_tb = Py_None;
3619
6.25k
        Py_INCREF(Py_None);
3620
6.25k
    }
3621
11.0k
    PyException_SetTraceback(exc, base_tb);
3622
11.0k
done:
3623
11.0k
    Py_XDECREF(base_tb);
3624
11.0k
    _PyErr_SetRaisedException(tstate, exc);
3625
11.0k
}
3626
3627
3628
static PyObject *
3629
resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
3630
214
{
3631
214
    PyObject *abs_name;
3632
214
    PyObject *package = NULL;
3633
214
    PyObject *spec = NULL;
3634
214
    Py_ssize_t last_dot;
3635
214
    PyObject *base;
3636
214
    int level_up;
3637
3638
214
    if (globals == NULL) {
3639
0
        _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
3640
0
        goto error;
3641
0
    }
3642
214
    if (!PyDict_Check(globals)) {
3643
0
        _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
3644
0
        goto error;
3645
0
    }
3646
214
    if (PyDict_GetItemRef(globals, &_Py_ID(__package__), &package) < 0) {
3647
0
        goto error;
3648
0
    }
3649
214
    if (package == Py_None) {
3650
0
        Py_DECREF(package);
3651
0
        package = NULL;
3652
0
    }
3653
214
    if (PyDict_GetItemRef(globals, &_Py_ID(__spec__), &spec) < 0) {
3654
0
        goto error;
3655
0
    }
3656
3657
214
    if (package != NULL) {
3658
214
        if (!PyUnicode_Check(package)) {
3659
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3660
0
                             "package must be a string");
3661
0
            goto error;
3662
0
        }
3663
214
        else if (spec != NULL && spec != Py_None) {
3664
214
            int equal;
3665
214
            PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent));
3666
214
            if (parent == NULL) {
3667
0
                goto error;
3668
0
            }
3669
3670
214
            equal = PyObject_RichCompareBool(package, parent, Py_EQ);
3671
214
            Py_DECREF(parent);
3672
214
            if (equal < 0) {
3673
0
                goto error;
3674
0
            }
3675
214
            else if (equal == 0) {
3676
0
                if (PyErr_WarnEx(PyExc_DeprecationWarning,
3677
0
                        "__package__ != __spec__.parent", 1) < 0) {
3678
0
                    goto error;
3679
0
                }
3680
0
            }
3681
214
        }
3682
214
    }
3683
0
    else if (spec != NULL && spec != Py_None) {
3684
0
        package = PyObject_GetAttr(spec, &_Py_ID(parent));
3685
0
        if (package == NULL) {
3686
0
            goto error;
3687
0
        }
3688
0
        else if (!PyUnicode_Check(package)) {
3689
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3690
0
                             "__spec__.parent must be a string");
3691
0
            goto error;
3692
0
        }
3693
0
    }
3694
0
    else {
3695
0
        if (PyErr_WarnEx(PyExc_ImportWarning,
3696
0
                    "can't resolve package from __spec__ or __package__, "
3697
0
                    "falling back on __name__ and __path__", 1) < 0) {
3698
0
            goto error;
3699
0
        }
3700
3701
0
        if (PyDict_GetItemRef(globals, &_Py_ID(__name__), &package) < 0) {
3702
0
            goto error;
3703
0
        }
3704
0
        if (package == NULL) {
3705
0
            _PyErr_SetString(tstate, PyExc_KeyError,
3706
0
                             "'__name__' not in globals");
3707
0
            goto error;
3708
0
        }
3709
3710
0
        if (!PyUnicode_Check(package)) {
3711
0
            _PyErr_SetString(tstate, PyExc_TypeError,
3712
0
                             "__name__ must be a string");
3713
0
            goto error;
3714
0
        }
3715
3716
0
        int haspath = PyDict_Contains(globals, &_Py_ID(__path__));
3717
0
        if (haspath < 0) {
3718
0
            goto error;
3719
0
        }
3720
0
        if (!haspath) {
3721
0
            Py_ssize_t dot;
3722
3723
0
            dot = PyUnicode_FindChar(package, '.',
3724
0
                                        0, PyUnicode_GET_LENGTH(package), -1);
3725
0
            if (dot == -2) {
3726
0
                goto error;
3727
0
            }
3728
0
            else if (dot == -1) {
3729
0
                goto no_parent_error;
3730
0
            }
3731
0
            PyObject *substr = PyUnicode_Substring(package, 0, dot);
3732
0
            if (substr == NULL) {
3733
0
                goto error;
3734
0
            }
3735
0
            Py_SETREF(package, substr);
3736
0
        }
3737
0
    }
3738
3739
214
    last_dot = PyUnicode_GET_LENGTH(package);
3740
214
    if (last_dot == 0) {
3741
0
        goto no_parent_error;
3742
0
    }
3743
3744
214
    for (level_up = 1; level_up < level; level_up += 1) {
3745
0
        last_dot = PyUnicode_FindChar(package, '.', 0, last_dot, -1);
3746
0
        if (last_dot == -2) {
3747
0
            goto error;
3748
0
        }
3749
0
        else if (last_dot == -1) {
3750
0
            _PyErr_SetString(tstate, PyExc_ImportError,
3751
0
                             "attempted relative import beyond top-level "
3752
0
                             "package");
3753
0
            goto error;
3754
0
        }
3755
0
    }
3756
3757
214
    Py_XDECREF(spec);
3758
214
    base = PyUnicode_Substring(package, 0, last_dot);
3759
214
    Py_DECREF(package);
3760
214
    if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
3761
78
        return base;
3762
78
    }
3763
3764
136
    abs_name = PyUnicode_FromFormat("%U.%U", base, name);
3765
136
    Py_DECREF(base);
3766
136
    return abs_name;
3767
3768
0
  no_parent_error:
3769
0
    _PyErr_SetString(tstate, PyExc_ImportError,
3770
0
                     "attempted relative import "
3771
0
                     "with no known parent package");
3772
3773
0
  error:
3774
0
    Py_XDECREF(spec);
3775
0
    Py_XDECREF(package);
3776
0
    return NULL;
3777
0
}
3778
3779
static PyObject *
3780
import_find_and_load(PyThreadState *tstate, PyObject *abs_name)
3781
13.0k
{
3782
13.0k
    PyObject *mod = NULL;
3783
13.0k
    PyInterpreterState *interp = tstate->interp;
3784
13.0k
    int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
3785
13.0k
#define import_level FIND_AND_LOAD(interp).import_level
3786
13.0k
#define accumulated FIND_AND_LOAD(interp).accumulated
3787
3788
13.0k
    PyTime_t t1 = 0, accumulated_copy = accumulated;
3789
3790
    /* XOptions is initialized after first some imports.
3791
     * So we can't have negative cache before completed initialization.
3792
     * Anyway, importlib._find_and_load is much slower than
3793
     * _PyDict_GetItemIdWithError().
3794
     */
3795
13.0k
    if (import_time) {
3796
0
        _IMPORT_TIME_HEADER(interp);
3797
3798
0
        import_level++;
3799
        // ignore error: don't block import if reading the clock fails
3800
0
        (void)PyTime_PerfCounterRaw(&t1);
3801
0
        accumulated = 0;
3802
0
    }
3803
3804
13.0k
    if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
3805
0
        PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
3806
3807
13.0k
    mod = PyObject_CallMethodObjArgs(IMPORTLIB(interp), &_Py_ID(_find_and_load),
3808
13.0k
                                     abs_name, IMPORT_FUNC(interp), NULL);
3809
3810
13.0k
    if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
3811
0
        PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
3812
0
                                       mod != NULL);
3813
3814
13.0k
    if (import_time) {
3815
0
        PyTime_t t2;
3816
0
        (void)PyTime_PerfCounterRaw(&t2);
3817
0
        PyTime_t cum = t2 - t1;
3818
3819
0
        import_level--;
3820
0
        fprintf(stderr, "import time: %9ld | %10ld | %*s%s\n",
3821
0
                (long)_PyTime_AsMicroseconds(cum - accumulated, _PyTime_ROUND_CEILING),
3822
0
                (long)_PyTime_AsMicroseconds(cum, _PyTime_ROUND_CEILING),
3823
0
                import_level*2, "", PyUnicode_AsUTF8(abs_name));
3824
3825
0
        accumulated = accumulated_copy + cum;
3826
0
    }
3827
3828
13.0k
    return mod;
3829
13.0k
#undef import_level
3830
13.0k
#undef accumulated
3831
13.0k
}
3832
3833
PyObject *
3834
PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
3835
                                 PyObject *locals, PyObject *fromlist,
3836
                                 int level)
3837
2.60M
{
3838
2.60M
    PyThreadState *tstate = _PyThreadState_GET();
3839
2.60M
    PyObject *abs_name = NULL;
3840
2.60M
    PyObject *final_mod = NULL;
3841
2.60M
    PyObject *mod = NULL;
3842
2.60M
    PyInterpreterState *interp = tstate->interp;
3843
2.60M
    int has_from;
3844
3845
2.60M
    if (name == NULL) {
3846
0
        _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
3847
0
        goto error;
3848
0
    }
3849
3850
    /* The below code is importlib.__import__() & _gcd_import(), ported to C
3851
       for added performance. */
3852
3853
2.60M
    if (!PyUnicode_Check(name)) {
3854
0
        _PyErr_SetString(tstate, PyExc_TypeError,
3855
0
                         "module name must be a string");
3856
0
        goto error;
3857
0
    }
3858
2.60M
    if (level < 0) {
3859
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
3860
0
        goto error;
3861
0
    }
3862
3863
2.60M
    if (level > 0) {
3864
214
        abs_name = resolve_name(tstate, name, globals, level);
3865
214
        if (abs_name == NULL)
3866
0
            goto error;
3867
214
    }
3868
2.60M
    else {  /* level == 0 */
3869
2.60M
        if (PyUnicode_GET_LENGTH(name) == 0) {
3870
0
            _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
3871
0
            goto error;
3872
0
        }
3873
2.60M
        abs_name = Py_NewRef(name);
3874
2.60M
    }
3875
3876
2.60M
    mod = import_get_module(tstate, abs_name);
3877
2.60M
    if (mod == NULL && _PyErr_Occurred(tstate)) {
3878
0
        goto error;
3879
0
    }
3880
3881
2.60M
    if (mod != NULL && mod != Py_None) {
3882
2.59M
        if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
3883
0
            goto error;
3884
0
        }
3885
2.59M
    }
3886
13.0k
    else {
3887
13.0k
        Py_XDECREF(mod);
3888
13.0k
        mod = import_find_and_load(tstate, abs_name);
3889
13.0k
        if (mod == NULL) {
3890
11.0k
            goto error;
3891
11.0k
        }
3892
13.0k
    }
3893
3894
2.59M
    has_from = 0;
3895
2.59M
    if (fromlist != NULL && fromlist != Py_None) {
3896
254k
        has_from = PyObject_IsTrue(fromlist);
3897
254k
        if (has_from < 0)
3898
0
            goto error;
3899
254k
    }
3900
2.59M
    if (!has_from) {
3901
2.58M
        Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3902
2.58M
        if (level == 0 || len > 0) {
3903
2.58M
            Py_ssize_t dot;
3904
3905
2.58M
            dot = PyUnicode_FindChar(name, '.', 0, len, 1);
3906
2.58M
            if (dot == -2) {
3907
0
                goto error;
3908
0
            }
3909
3910
2.58M
            if (dot == -1) {
3911
                /* No dot in module name, simple exit */
3912
2.57M
                final_mod = Py_NewRef(mod);
3913
2.57M
                goto error;
3914
2.57M
            }
3915
3916
2.47k
            if (level == 0) {
3917
2.47k
                PyObject *front = PyUnicode_Substring(name, 0, dot);
3918
2.47k
                if (front == NULL) {
3919
0
                    goto error;
3920
0
                }
3921
3922
2.47k
                final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
3923
2.47k
                Py_DECREF(front);
3924
2.47k
            }
3925
0
            else {
3926
0
                Py_ssize_t cut_off = len - dot;
3927
0
                Py_ssize_t abs_name_len = PyUnicode_GET_LENGTH(abs_name);
3928
0
                PyObject *to_return = PyUnicode_Substring(abs_name, 0,
3929
0
                                                        abs_name_len - cut_off);
3930
0
                if (to_return == NULL) {
3931
0
                    goto error;
3932
0
                }
3933
3934
0
                final_mod = import_get_module(tstate, to_return);
3935
0
                if (final_mod == NULL) {
3936
0
                    if (!_PyErr_Occurred(tstate)) {
3937
0
                        _PyErr_Format(tstate, PyExc_KeyError,
3938
0
                                      "%R not in sys.modules as expected",
3939
0
                                      to_return);
3940
0
                    }
3941
0
                    Py_DECREF(to_return);
3942
0
                    goto error;
3943
0
                }
3944
3945
0
                Py_DECREF(to_return);
3946
0
            }
3947
2.47k
        }
3948
0
        else {
3949
0
            final_mod = Py_NewRef(mod);
3950
0
        }
3951
2.58M
    }
3952
16.7k
    else {
3953
16.7k
        int has_path = PyObject_HasAttrWithError(mod, &_Py_ID(__path__));
3954
16.7k
        if (has_path < 0) {
3955
0
            goto error;
3956
0
        }
3957
16.7k
        if (has_path) {
3958
2.60k
            final_mod = PyObject_CallMethodObjArgs(
3959
2.60k
                        IMPORTLIB(interp), &_Py_ID(_handle_fromlist),
3960
2.60k
                        mod, fromlist, IMPORT_FUNC(interp), NULL);
3961
2.60k
        }
3962
14.1k
        else {
3963
14.1k
            final_mod = Py_NewRef(mod);
3964
14.1k
        }
3965
16.7k
    }
3966
3967
2.60M
  error:
3968
2.60M
    Py_XDECREF(abs_name);
3969
2.60M
    Py_XDECREF(mod);
3970
2.60M
    if (final_mod == NULL) {
3971
11.0k
        remove_importlib_frames(tstate);
3972
11.0k
    }
3973
2.60M
    return final_mod;
3974
2.59M
}
3975
3976
PyObject *
3977
PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
3978
                           PyObject *fromlist, int level)
3979
224
{
3980
224
    PyObject *nameobj, *mod;
3981
224
    nameobj = PyUnicode_FromString(name);
3982
224
    if (nameobj == NULL)
3983
0
        return NULL;
3984
224
    mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
3985
224
                                           fromlist, level);
3986
224
    Py_DECREF(nameobj);
3987
224
    return mod;
3988
224
}
3989
3990
3991
/* Re-import a module of any kind and return its module object, WITH
3992
   INCREMENTED REFERENCE COUNT */
3993
3994
PyObject *
3995
PyImport_ReloadModule(PyObject *m)
3996
0
{
3997
0
    PyObject *reloaded_module = NULL;
3998
0
    PyObject *importlib = PyImport_GetModule(&_Py_ID(importlib));
3999
0
    if (importlib == NULL) {
4000
0
        if (PyErr_Occurred()) {
4001
0
            return NULL;
4002
0
        }
4003
4004
0
        importlib = PyImport_ImportModule("importlib");
4005
0
        if (importlib == NULL) {
4006
0
            return NULL;
4007
0
        }
4008
0
    }
4009
4010
0
    reloaded_module = PyObject_CallMethodOneArg(importlib, &_Py_ID(reload), m);
4011
0
    Py_DECREF(importlib);
4012
0
    return reloaded_module;
4013
0
}
4014
4015
4016
/* Higher-level import emulator which emulates the "import" statement
4017
   more accurately -- it invokes the __import__() function from the
4018
   builtins of the current globals.  This means that the import is
4019
   done using whatever import hooks are installed in the current
4020
   environment.
4021
   A dummy list ["__doc__"] is passed as the 4th argument so that
4022
   e.g. PyImport_Import(PyUnicode_FromString("win32com.client.gencache"))
4023
   will return <module "gencache"> instead of <module "win32com">. */
4024
4025
PyObject *
4026
PyImport_Import(PyObject *module_name)
4027
237k
{
4028
237k
    PyThreadState *tstate = _PyThreadState_GET();
4029
237k
    PyObject *globals = NULL;
4030
237k
    PyObject *import = NULL;
4031
237k
    PyObject *builtins = NULL;
4032
237k
    PyObject *r = NULL;
4033
4034
237k
    PyObject *from_list = PyList_New(0);
4035
237k
    if (from_list == NULL) {
4036
0
        goto err;
4037
0
    }
4038
4039
    /* Get the builtins from current globals */
4040
237k
    globals = PyEval_GetGlobals();  // borrowed
4041
237k
    if (globals != NULL) {
4042
237k
        Py_INCREF(globals);
4043
        // XXX Use _PyEval_EnsureBuiltins()?
4044
237k
        builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
4045
237k
        if (builtins == NULL) {
4046
            // XXX Fall back to interp->builtins or sys.modules['builtins']?
4047
0
            goto err;
4048
0
        }
4049
237k
    }
4050
224
    else if (_PyErr_Occurred(tstate)) {
4051
0
        goto err;
4052
0
    }
4053
224
    else {
4054
        /* No globals -- use standard builtins, and fake globals */
4055
224
        globals = PyDict_New();
4056
224
        if (globals == NULL) {
4057
0
            goto err;
4058
0
        }
4059
224
        if (_PyEval_EnsureBuiltinsWithModule(tstate, globals, &builtins) < 0) {
4060
0
            goto err;
4061
0
        }
4062
224
    }
4063
4064
    /* Get the __import__ function from the builtins */
4065
237k
    if (PyDict_Check(builtins)) {
4066
237k
        import = PyObject_GetItem(builtins, &_Py_ID(__import__));
4067
237k
        if (import == NULL) {
4068
0
            _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
4069
0
        }
4070
237k
    }
4071
224
    else
4072
224
        import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
4073
237k
    if (import == NULL)
4074
0
        goto err;
4075
4076
    /* Call the __import__ function with the proper argument list
4077
       Always use absolute import here.
4078
       Calling for side-effect of import. */
4079
237k
    r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
4080
237k
                              globals, from_list, 0, NULL);
4081
237k
    if (r == NULL)
4082
0
        goto err;
4083
237k
    Py_DECREF(r);
4084
4085
237k
    r = import_get_module(tstate, module_name);
4086
237k
    if (r == NULL && !_PyErr_Occurred(tstate)) {
4087
0
        _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
4088
0
    }
4089
4090
237k
  err:
4091
237k
    Py_XDECREF(globals);
4092
237k
    Py_XDECREF(builtins);
4093
237k
    Py_XDECREF(import);
4094
237k
    Py_XDECREF(from_list);
4095
4096
237k
    return r;
4097
237k
}
4098
4099
4100
/*********************/
4101
/* runtime lifecycle */
4102
/*********************/
4103
4104
PyStatus
4105
_PyImport_Init(void)
4106
28
{
4107
28
    if (INITTAB != NULL) {
4108
0
        return _PyStatus_ERR("global import state already initialized");
4109
0
    }
4110
28
    if (init_builtin_modules_table() != 0) {
4111
0
        return PyStatus_NoMemory();
4112
0
    }
4113
28
    return _PyStatus_OK();
4114
28
}
4115
4116
void
4117
_PyImport_Fini(void)
4118
0
{
4119
    /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
4120
    // XXX Should we actually leave them (mostly) intact, since we don't
4121
    // ever dlclose() the module files?
4122
0
    _extensions_cache_clear_all();
4123
4124
    /* Free memory allocated by _PyImport_Init() */
4125
0
    fini_builtin_modules_table();
4126
0
}
4127
4128
void
4129
_PyImport_Fini2(void)
4130
0
{
4131
    // Reset PyImport_Inittab
4132
0
    PyImport_Inittab = _PyImport_Inittab;
4133
4134
    /* Free memory allocated by PyImport_ExtendInittab() */
4135
0
    _PyMem_DefaultRawFree(inittab_copy);
4136
0
    inittab_copy = NULL;
4137
0
}
4138
4139
4140
/*************************/
4141
/* interpreter lifecycle */
4142
/*************************/
4143
4144
PyStatus
4145
_PyImport_InitCore(PyThreadState *tstate, PyObject *sysmod, int importlib)
4146
28
{
4147
    // XXX Initialize here: interp->modules and interp->import_func.
4148
    // XXX Initialize here: sys.modules and sys.meta_path.
4149
4150
28
    if (importlib) {
4151
        /* This call sets up builtin and frozen import support */
4152
28
        if (init_importlib(tstate, sysmod) < 0) {
4153
0
            return _PyStatus_ERR("failed to initialize importlib");
4154
0
        }
4155
28
    }
4156
4157
28
    return _PyStatus_OK();
4158
28
}
4159
4160
/* In some corner cases it is important to be sure that the import
4161
   machinery has been initialized (or not cleaned up yet).  For
4162
   example, see issue #4236 and PyModule_Create2(). */
4163
4164
int
4165
_PyImport_IsInitialized(PyInterpreterState *interp)
4166
0
{
4167
0
    if (MODULES(interp) == NULL)
4168
0
        return 0;
4169
0
    return 1;
4170
0
}
4171
4172
/* Clear the direct per-interpreter import state, if not cleared already. */
4173
void
4174
_PyImport_ClearCore(PyInterpreterState *interp)
4175
0
{
4176
    /* interp->modules should have been cleaned up and cleared already
4177
       by _PyImport_FiniCore(). */
4178
0
    Py_CLEAR(MODULES(interp));
4179
0
    Py_CLEAR(MODULES_BY_INDEX(interp));
4180
0
    Py_CLEAR(IMPORTLIB(interp));
4181
0
    Py_CLEAR(IMPORT_FUNC(interp));
4182
0
}
4183
4184
void
4185
_PyImport_FiniCore(PyInterpreterState *interp)
4186
0
{
4187
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4188
4189
0
    if (_PySys_ClearAttrString(interp, "meta_path", verbose) < 0) {
4190
0
        PyErr_FormatUnraisable("Exception ignored while "
4191
0
                               "clearing sys.meta_path");
4192
0
    }
4193
4194
    // XXX Pull in most of finalize_modules() in pylifecycle.c.
4195
4196
0
    if (_PySys_ClearAttrString(interp, "modules", verbose) < 0) {
4197
0
        PyErr_FormatUnraisable("Exception ignored while "
4198
0
                               "clearing sys.modules");
4199
0
    }
4200
4201
0
    _PyImport_ClearCore(interp);
4202
0
}
4203
4204
// XXX Add something like _PyImport_Disable() for use early in interp fini?
4205
4206
4207
/* "external" imports */
4208
4209
static int
4210
init_zipimport(PyThreadState *tstate, int verbose)
4211
28
{
4212
28
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
4213
28
    if (path_hooks == NULL) {
4214
0
        return -1;
4215
0
    }
4216
4217
28
    if (verbose) {
4218
0
        PySys_WriteStderr("# installing zipimport hook\n");
4219
0
    }
4220
4221
28
    PyObject *zipimporter = PyImport_ImportModuleAttrString("zipimport", "zipimporter");
4222
28
    if (zipimporter == NULL) {
4223
0
        _PyErr_Clear(tstate); /* No zipimporter object -- okay */
4224
0
        if (verbose) {
4225
0
            PySys_WriteStderr("# can't import zipimport.zipimporter\n");
4226
0
        }
4227
0
    }
4228
28
    else {
4229
        /* sys.path_hooks.insert(0, zipimporter) */
4230
28
        int err = PyList_Insert(path_hooks, 0, zipimporter);
4231
28
        Py_DECREF(zipimporter);
4232
28
        if (err < 0) {
4233
0
            Py_DECREF(path_hooks);
4234
0
            return -1;
4235
0
        }
4236
28
        if (verbose) {
4237
0
            PySys_WriteStderr("# installed zipimport hook\n");
4238
0
        }
4239
28
    }
4240
28
    Py_DECREF(path_hooks);
4241
4242
28
    return 0;
4243
28
}
4244
4245
PyStatus
4246
_PyImport_InitExternal(PyThreadState *tstate)
4247
28
{
4248
28
    int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
4249
4250
    // XXX Initialize here: sys.path_hooks and sys.path_importer_cache.
4251
4252
28
    if (init_importlib_external(tstate->interp) != 0) {
4253
0
        _PyErr_Print(tstate);
4254
0
        return _PyStatus_ERR("external importer setup failed");
4255
0
    }
4256
4257
28
    if (init_zipimport(tstate, verbose) != 0) {
4258
0
        PyErr_Print();
4259
0
        return _PyStatus_ERR("initializing zipimport failed");
4260
0
    }
4261
4262
28
    return _PyStatus_OK();
4263
28
}
4264
4265
void
4266
_PyImport_FiniExternal(PyInterpreterState *interp)
4267
0
{
4268
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
4269
4270
    // XXX Uninstall importlib metapath importers here?
4271
4272
0
    if (_PySys_ClearAttrString(interp, "path_importer_cache", verbose) < 0) {
4273
0
        PyErr_FormatUnraisable("Exception ignored while "
4274
0
                               "clearing sys.path_importer_cache");
4275
0
    }
4276
0
    if (_PySys_ClearAttrString(interp, "path_hooks", verbose) < 0) {
4277
0
        PyErr_FormatUnraisable("Exception ignored while "
4278
0
                               "clearing sys.path_hooks");
4279
0
    }
4280
0
}
4281
4282
4283
/******************/
4284
/* module helpers */
4285
/******************/
4286
4287
PyObject *
4288
PyImport_ImportModuleAttr(PyObject *modname, PyObject *attrname)
4289
10.0k
{
4290
10.0k
    PyObject *mod = PyImport_Import(modname);
4291
10.0k
    if (mod == NULL) {
4292
0
        return NULL;
4293
0
    }
4294
10.0k
    PyObject *result = PyObject_GetAttr(mod, attrname);
4295
10.0k
    Py_DECREF(mod);
4296
10.0k
    return result;
4297
10.0k
}
4298
4299
PyObject *
4300
PyImport_ImportModuleAttrString(const char *modname, const char *attrname)
4301
7.74k
{
4302
7.74k
    PyObject *pmodname = PyUnicode_FromString(modname);
4303
7.74k
    if (pmodname == NULL) {
4304
0
        return NULL;
4305
0
    }
4306
7.74k
    PyObject *pattrname = PyUnicode_FromString(attrname);
4307
7.74k
    if (pattrname == NULL) {
4308
0
        Py_DECREF(pmodname);
4309
0
        return NULL;
4310
0
    }
4311
7.74k
    PyObject *result = PyImport_ImportModuleAttr(pmodname, pattrname);
4312
7.74k
    Py_DECREF(pattrname);
4313
7.74k
    Py_DECREF(pmodname);
4314
7.74k
    return result;
4315
7.74k
}
4316
4317
4318
/**************/
4319
/* the module */
4320
/**************/
4321
4322
/*[clinic input]
4323
_imp.lock_held
4324
4325
Return True if the import lock is currently held, else False.
4326
4327
On platforms without threads, return False.
4328
[clinic start generated code]*/
4329
4330
static PyObject *
4331
_imp_lock_held_impl(PyObject *module)
4332
/*[clinic end generated code: output=8b89384b5e1963fc input=9b088f9b217d9bdf]*/
4333
0
{
4334
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4335
0
    return PyBool_FromLong(PyMutex_IsLocked(&IMPORT_LOCK(interp).mutex));
4336
0
}
4337
4338
/*[clinic input]
4339
@permit_long_docstring_body
4340
_imp.acquire_lock
4341
4342
Acquires the interpreter's import lock for the current thread.
4343
4344
This lock should be used by import hooks to ensure thread-safety when importing
4345
modules. On platforms without threads, this function does nothing.
4346
[clinic start generated code]*/
4347
4348
static PyObject *
4349
_imp_acquire_lock_impl(PyObject *module)
4350
/*[clinic end generated code: output=1aff58cb0ee1b026 input=e1a4ef049d34e7dd]*/
4351
64.2k
{
4352
64.2k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4353
64.2k
    _PyImport_AcquireLock(interp);
4354
64.2k
    Py_RETURN_NONE;
4355
64.2k
}
4356
4357
/*[clinic input]
4358
_imp.release_lock
4359
4360
Release the interpreter's import lock.
4361
4362
On platforms without threads, this function does nothing.
4363
[clinic start generated code]*/
4364
4365
static PyObject *
4366
_imp_release_lock_impl(PyObject *module)
4367
/*[clinic end generated code: output=7faab6d0be178b0a input=934fb11516dd778b]*/
4368
64.2k
{
4369
64.2k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4370
64.2k
    if (!_PyRecursiveMutex_IsLockedByCurrentThread(&IMPORT_LOCK(interp))) {
4371
0
        PyErr_SetString(PyExc_RuntimeError,
4372
0
                        "not holding the import lock");
4373
0
        return NULL;
4374
0
    }
4375
64.2k
    _PyImport_ReleaseLock(interp);
4376
64.2k
    Py_RETURN_NONE;
4377
64.2k
}
4378
4379
4380
/*[clinic input]
4381
_imp._fix_co_filename
4382
4383
    code: object(type="PyCodeObject *", subclass_of="&PyCode_Type")
4384
        Code object to change.
4385
4386
    path: unicode
4387
        File path to use.
4388
    /
4389
4390
Changes code.co_filename to specify the passed-in file path.
4391
[clinic start generated code]*/
4392
4393
static PyObject *
4394
_imp__fix_co_filename_impl(PyObject *module, PyCodeObject *code,
4395
                           PyObject *path)
4396
/*[clinic end generated code: output=1d002f100235587d input=895ba50e78b82f05]*/
4397
4398
5.59k
{
4399
5.59k
    update_compiled_module(code, path);
4400
4401
5.59k
    Py_RETURN_NONE;
4402
5.59k
}
4403
4404
4405
/*[clinic input]
4406
_imp.create_builtin
4407
4408
    spec: object
4409
    /
4410
4411
Create an extension module.
4412
[clinic start generated code]*/
4413
4414
static PyObject *
4415
_imp_create_builtin(PyObject *module, PyObject *spec)
4416
/*[clinic end generated code: output=ace7ff22271e6f39 input=37f966f890384e47]*/
4417
532
{
4418
532
    PyThreadState *tstate = _PyThreadState_GET();
4419
4420
532
    PyObject *name = PyObject_GetAttrString(spec, "name");
4421
532
    if (name == NULL) {
4422
0
        return NULL;
4423
0
    }
4424
4425
532
    if (!PyUnicode_Check(name)) {
4426
0
        PyErr_Format(PyExc_TypeError,
4427
0
                     "name must be string, not %.200s",
4428
0
                     Py_TYPE(name)->tp_name);
4429
0
        Py_DECREF(name);
4430
0
        return NULL;
4431
0
    }
4432
4433
532
    if (PyUnicode_GetLength(name) == 0) {
4434
0
        PyErr_Format(PyExc_ValueError, "name must not be empty");
4435
0
        Py_DECREF(name);
4436
0
        return NULL;
4437
0
    }
4438
4439
532
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
4440
532
    Py_DECREF(name);
4441
532
    return mod;
4442
532
}
4443
4444
4445
/*[clinic input]
4446
_imp.extension_suffixes
4447
4448
Returns the list of file suffixes used to identify extension modules.
4449
[clinic start generated code]*/
4450
4451
static PyObject *
4452
_imp_extension_suffixes_impl(PyObject *module)
4453
/*[clinic end generated code: output=0bf346e25a8f0cd3 input=ecdeeecfcb6f839e]*/
4454
56
{
4455
56
    PyObject *list;
4456
4457
56
    list = PyList_New(0);
4458
56
    if (list == NULL)
4459
0
        return NULL;
4460
56
#ifdef HAVE_DYNAMIC_LOADING
4461
56
    const char *suffix;
4462
56
    unsigned int index = 0;
4463
4464
224
    while ((suffix = _PyImport_DynLoadFiletab[index])) {
4465
168
        PyObject *item = PyUnicode_FromString(suffix);
4466
168
        if (item == NULL) {
4467
0
            Py_DECREF(list);
4468
0
            return NULL;
4469
0
        }
4470
168
        if (PyList_Append(list, item) < 0) {
4471
0
            Py_DECREF(list);
4472
0
            Py_DECREF(item);
4473
0
            return NULL;
4474
0
        }
4475
168
        Py_DECREF(item);
4476
168
        index += 1;
4477
168
    }
4478
56
#endif
4479
56
    return list;
4480
56
}
4481
4482
/*[clinic input]
4483
_imp.init_frozen
4484
4485
    name: unicode
4486
    /
4487
4488
Initializes a frozen module.
4489
[clinic start generated code]*/
4490
4491
static PyObject *
4492
_imp_init_frozen_impl(PyObject *module, PyObject *name)
4493
/*[clinic end generated code: output=fc0511ed869fd69c input=13019adfc04f3fb3]*/
4494
0
{
4495
0
    PyThreadState *tstate = _PyThreadState_GET();
4496
0
    int ret;
4497
4498
0
    ret = PyImport_ImportFrozenModuleObject(name);
4499
0
    if (ret < 0)
4500
0
        return NULL;
4501
0
    if (ret == 0) {
4502
0
        Py_RETURN_NONE;
4503
0
    }
4504
0
    return import_add_module(tstate, name);
4505
0
}
4506
4507
/*[clinic input]
4508
_imp.find_frozen
4509
4510
    name: unicode
4511
    /
4512
    *
4513
    withdata: bool = False
4514
4515
Return info about the corresponding frozen module (if there is one) or None.
4516
4517
The returned info (a 2-tuple):
4518
4519
 * data         the raw marshalled bytes
4520
 * is_package   whether or not it is a package
4521
 * origname     the originally frozen module's name, or None if not
4522
                a stdlib module (this will usually be the same as
4523
                the module's current name)
4524
[clinic start generated code]*/
4525
4526
static PyObject *
4527
_imp_find_frozen_impl(PyObject *module, PyObject *name, int withdata)
4528
/*[clinic end generated code: output=8c1c3c7f925397a5 input=22a8847c201542fd]*/
4529
12.5k
{
4530
12.5k
    struct frozen_info info;
4531
12.5k
    frozen_status status = find_frozen(name, &info);
4532
12.5k
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
4533
12.2k
        Py_RETURN_NONE;
4534
12.2k
    }
4535
337
    else if (status == FROZEN_BAD_NAME) {
4536
0
        Py_RETURN_NONE;
4537
0
    }
4538
337
    else if (status != FROZEN_OKAY) {
4539
0
        set_frozen_error(status, name);
4540
0
        return NULL;
4541
0
    }
4542
4543
337
    PyObject *data = NULL;
4544
337
    if (withdata) {
4545
0
        data = PyMemoryView_FromMemory((char *)info.data, info.size, PyBUF_READ);
4546
0
        if (data == NULL) {
4547
0
            return NULL;
4548
0
        }
4549
0
    }
4550
4551
337
    PyObject *origname = NULL;
4552
337
    if (info.origname != NULL && info.origname[0] != '\0') {
4553
337
        origname = PyUnicode_FromString(info.origname);
4554
337
        if (origname == NULL) {
4555
0
            Py_XDECREF(data);
4556
0
            return NULL;
4557
0
        }
4558
337
    }
4559
4560
337
    PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
4561
337
                                    info.is_package ? Py_True : Py_False,
4562
337
                                    origname ? origname : Py_None);
4563
337
    Py_XDECREF(origname);
4564
337
    Py_XDECREF(data);
4565
337
    return result;
4566
337
}
4567
4568
/*[clinic input]
4569
_imp.get_frozen_object
4570
4571
    name: unicode
4572
    data as dataobj: object = None
4573
    /
4574
4575
Create a code object for a frozen module.
4576
[clinic start generated code]*/
4577
4578
static PyObject *
4579
_imp_get_frozen_object_impl(PyObject *module, PyObject *name,
4580
                            PyObject *dataobj)
4581
/*[clinic end generated code: output=54368a673a35e745 input=034bdb88f6460b7b]*/
4582
337
{
4583
337
    struct frozen_info info = {0};
4584
337
    Py_buffer buf = {0};
4585
337
    if (PyObject_CheckBuffer(dataobj)) {
4586
0
        if (PyObject_GetBuffer(dataobj, &buf, PyBUF_SIMPLE) != 0) {
4587
0
            return NULL;
4588
0
        }
4589
0
        info.data = (const char *)buf.buf;
4590
0
        info.size = buf.len;
4591
0
    }
4592
337
    else if (dataobj != Py_None) {
4593
0
        _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
4594
0
        return NULL;
4595
0
    }
4596
337
    else {
4597
337
        frozen_status status = find_frozen(name, &info);
4598
337
        if (status != FROZEN_OKAY) {
4599
0
            set_frozen_error(status, name);
4600
0
            return NULL;
4601
0
        }
4602
337
    }
4603
4604
337
    if (info.nameobj == NULL) {
4605
0
        info.nameobj = name;
4606
0
    }
4607
337
    if (info.size == 0) {
4608
        /* Does not contain executable code. */
4609
0
        set_frozen_error(FROZEN_INVALID, name);
4610
0
        return NULL;
4611
0
    }
4612
4613
337
    PyInterpreterState *interp = _PyInterpreterState_GET();
4614
337
    PyObject *codeobj = unmarshal_frozen_code(interp, &info);
4615
337
    if (dataobj != Py_None) {
4616
0
        PyBuffer_Release(&buf);
4617
0
    }
4618
337
    return codeobj;
4619
337
}
4620
4621
/*[clinic input]
4622
_imp.is_frozen_package
4623
4624
    name: unicode
4625
    /
4626
4627
Returns True if the module name is of a frozen package.
4628
[clinic start generated code]*/
4629
4630
static PyObject *
4631
_imp_is_frozen_package_impl(PyObject *module, PyObject *name)
4632
/*[clinic end generated code: output=e70cbdb45784a1c9 input=81b6cdecd080fbb8]*/
4633
28
{
4634
28
    struct frozen_info info;
4635
28
    frozen_status status = find_frozen(name, &info);
4636
28
    if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
4637
0
        set_frozen_error(status, name);
4638
0
        return NULL;
4639
0
    }
4640
28
    return PyBool_FromLong(info.is_package);
4641
28
}
4642
4643
/*[clinic input]
4644
_imp.is_builtin
4645
4646
    name: unicode
4647
    /
4648
4649
Returns True if the module name corresponds to a built-in module.
4650
[clinic start generated code]*/
4651
4652
static PyObject *
4653
_imp_is_builtin_impl(PyObject *module, PyObject *name)
4654
/*[clinic end generated code: output=3bfd1162e2d3be82 input=86befdac021dd1c7]*/
4655
13.0k
{
4656
13.0k
    return PyLong_FromLong(is_builtin(name));
4657
13.0k
}
4658
4659
/*[clinic input]
4660
_imp.is_frozen
4661
4662
    name: unicode
4663
    /
4664
4665
Returns True if the module name corresponds to a frozen module.
4666
[clinic start generated code]*/
4667
4668
static PyObject *
4669
_imp_is_frozen_impl(PyObject *module, PyObject *name)
4670
/*[clinic end generated code: output=01f408f5ec0f2577 input=7301dbca1897d66b]*/
4671
28
{
4672
28
    struct frozen_info info;
4673
28
    frozen_status status = find_frozen(name, &info);
4674
28
    if (status != FROZEN_OKAY) {
4675
0
        Py_RETURN_FALSE;
4676
0
    }
4677
28
    Py_RETURN_TRUE;
4678
28
}
4679
4680
/*[clinic input]
4681
_imp._frozen_module_names
4682
4683
Returns the list of available frozen modules.
4684
[clinic start generated code]*/
4685
4686
static PyObject *
4687
_imp__frozen_module_names_impl(PyObject *module)
4688
/*[clinic end generated code: output=80609ef6256310a8 input=76237fbfa94460d2]*/
4689
0
{
4690
0
    return list_frozen_module_names();
4691
0
}
4692
4693
/*[clinic input]
4694
_imp._override_frozen_modules_for_tests
4695
4696
    override: int
4697
    /
4698
4699
(internal-only) Override PyConfig.use_frozen_modules.
4700
4701
(-1: "off", 1: "on", 0: no override)
4702
See frozen_modules() in Lib/test/support/import_helper.py.
4703
[clinic start generated code]*/
4704
4705
static PyObject *
4706
_imp__override_frozen_modules_for_tests_impl(PyObject *module, int override)
4707
/*[clinic end generated code: output=36d5cb1594160811 input=8f1f95a3ef21aec3]*/
4708
0
{
4709
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4710
0
    OVERRIDE_FROZEN_MODULES(interp) = override;
4711
0
    Py_RETURN_NONE;
4712
0
}
4713
4714
/*[clinic input]
4715
_imp._override_multi_interp_extensions_check
4716
4717
    override: int
4718
    /
4719
4720
(internal-only) Override PyInterpreterConfig.check_multi_interp_extensions.
4721
4722
(-1: "never", 1: "always", 0: no override)
4723
[clinic start generated code]*/
4724
4725
static PyObject *
4726
_imp__override_multi_interp_extensions_check_impl(PyObject *module,
4727
                                                  int override)
4728
/*[clinic end generated code: output=3ff043af52bbf280 input=e086a2ea181f92ae]*/
4729
0
{
4730
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4731
0
    if (_Py_IsMainInterpreter(interp)) {
4732
0
        PyErr_SetString(PyExc_RuntimeError,
4733
0
                        "_imp._override_multi_interp_extensions_check() "
4734
0
                        "cannot be used in the main interpreter");
4735
0
        return NULL;
4736
0
    }
4737
#ifdef Py_GIL_DISABLED
4738
    PyErr_SetString(PyExc_RuntimeError,
4739
                    "_imp._override_multi_interp_extensions_check() "
4740
                    "cannot be used in the free-threaded build");
4741
    return NULL;
4742
#else
4743
0
    int oldvalue = OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp);
4744
0
    OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK(interp) = override;
4745
0
    return PyLong_FromLong(oldvalue);
4746
0
#endif
4747
0
}
4748
4749
#ifdef HAVE_DYNAMIC_LOADING
4750
4751
/*[clinic input]
4752
_imp.create_dynamic
4753
4754
    spec: object
4755
    file: object = NULL
4756
    /
4757
4758
Create an extension module.
4759
[clinic start generated code]*/
4760
4761
static PyObject *
4762
_imp_create_dynamic_impl(PyObject *module, PyObject *spec, PyObject *file)
4763
/*[clinic end generated code: output=83249b827a4fde77 input=c31b954f4cf4e09d]*/
4764
124
{
4765
124
    FILE *fp = NULL;
4766
124
    PyObject *mod = NULL;
4767
124
    PyThreadState *tstate = _PyThreadState_GET();
4768
4769
124
    struct _Py_ext_module_loader_info info;
4770
124
    if (_Py_ext_module_loader_info_init_from_spec(&info, spec) < 0) {
4771
0
        return NULL;
4772
0
    }
4773
4774
124
    struct extensions_cache_value *cached = NULL;
4775
124
    mod = import_find_extension(tstate, &info, &cached);
4776
124
    if (mod != NULL) {
4777
0
        assert(!_PyErr_Occurred(tstate));
4778
0
        assert(cached != NULL);
4779
        /* The module might not have md_def set in certain reload cases. */
4780
0
        assert(_PyModule_GetDefOrNull(mod) == NULL
4781
0
                || cached->def == _PyModule_GetDefOrNull(mod));
4782
0
        assert_singlephase(cached);
4783
0
        goto finally;
4784
0
    }
4785
124
    else if (_PyErr_Occurred(tstate)) {
4786
0
        goto finally;
4787
0
    }
4788
    /* Otherwise it must be multi-phase init or the first time it's loaded. */
4789
4790
    /* If the module was added to the global cache
4791
     * but def->m_base.m_copy was cleared (e.g. subinterp fini)
4792
     * then we have to do a little dance here. */
4793
124
    if (cached != NULL) {
4794
0
        assert(cached->def->m_base.m_copy == NULL);
4795
        /* For now we clear the cache and move on. */
4796
0
        _extensions_cache_delete(info.path, info.name);
4797
0
    }
4798
4799
124
    if (PySys_Audit("import", "OOOOO", info.name, info.filename,
4800
124
                    Py_None, Py_None, Py_None) < 0)
4801
0
    {
4802
0
        goto finally;
4803
0
    }
4804
4805
    /* We would move this (and the fclose() below) into
4806
     * _PyImport_GetModuleExportHooks(), but it isn't clear if the intervening
4807
     * code relies on fp still being open. */
4808
124
    if (file != NULL) {
4809
0
        fp = Py_fopen(info.filename, "r");
4810
0
        if (fp == NULL) {
4811
0
            goto finally;
4812
0
        }
4813
0
    }
4814
4815
124
    PyModInitFunction p0 = NULL;
4816
124
    PyModExportFunction ex0 = NULL;
4817
124
    _PyImport_GetModuleExportHooks(&info, fp, &p0, &ex0);
4818
124
    if (ex0) {
4819
0
        mod = import_run_modexport(tstate, ex0, &info, spec);
4820
        // Modules created from slots handle GIL enablement (Py_mod_gil slot)
4821
        // when they're created.
4822
0
        goto finally;
4823
0
    }
4824
124
    if (p0 == NULL) {
4825
0
        goto finally;
4826
0
    }
4827
4828
#ifdef Py_GIL_DISABLED
4829
    // This call (and the corresponding call to _PyImport_CheckGILForModule())
4830
    // would ideally be inside import_run_extension(). They are kept in the
4831
    // callers for now because that would complicate the control flow inside
4832
    // import_run_extension(). It should be possible to restructure
4833
    // import_run_extension() to address this.
4834
    _PyEval_EnableGILTransient(tstate);
4835
#endif
4836
124
    mod = import_run_extension(
4837
124
                    tstate, p0, &info, spec, get_modules_dict(tstate, true));
4838
#ifdef Py_GIL_DISABLED
4839
    if (_PyImport_CheckGILForModule(mod, info.name) < 0) {
4840
        Py_CLEAR(mod);
4841
        goto finally;
4842
    }
4843
#endif
4844
4845
124
finally:
4846
124
    if (fp != NULL) {
4847
0
        fclose(fp);
4848
0
    }
4849
124
    _Py_ext_module_loader_info_clear(&info);
4850
124
    return mod;
4851
124
}
4852
4853
/*[clinic input]
4854
_imp.exec_dynamic -> int
4855
4856
    mod: object
4857
    /
4858
4859
Initialize an extension module.
4860
[clinic start generated code]*/
4861
4862
static int
4863
_imp_exec_dynamic_impl(PyObject *module, PyObject *mod)
4864
/*[clinic end generated code: output=f5720ac7b465877d input=9fdbfcb250280d3a]*/
4865
124
{
4866
124
    return exec_builtin_or_dynamic(mod);
4867
124
}
4868
4869
4870
#endif /* HAVE_DYNAMIC_LOADING */
4871
4872
/*[clinic input]
4873
_imp.exec_builtin -> int
4874
4875
    mod: object
4876
    /
4877
4878
Initialize a built-in module.
4879
[clinic start generated code]*/
4880
4881
static int
4882
_imp_exec_builtin_impl(PyObject *module, PyObject *mod)
4883
/*[clinic end generated code: output=0262447b240c038e input=7beed5a2f12a60ca]*/
4884
532
{
4885
532
    return exec_builtin_or_dynamic(mod);
4886
532
}
4887
4888
/*[clinic input]
4889
_imp.source_hash
4890
4891
    key: long
4892
    source: Py_buffer
4893
[clinic start generated code]*/
4894
4895
static PyObject *
4896
_imp_source_hash_impl(PyObject *module, long key, Py_buffer *source)
4897
/*[clinic end generated code: output=edb292448cf399ea input=9aaad1e590089789]*/
4898
0
{
4899
0
    union {
4900
0
        uint64_t x;
4901
0
        char data[sizeof(uint64_t)];
4902
0
    } hash;
4903
0
    hash.x = _Py_KeyedHash((uint64_t)key, source->buf, source->len);
4904
#if !PY_LITTLE_ENDIAN
4905
    // Force to little-endian. There really ought to be a succinct standard way
4906
    // to do this.
4907
    for (size_t i = 0; i < sizeof(hash.data)/2; i++) {
4908
        char tmp = hash.data[i];
4909
        hash.data[i] = hash.data[sizeof(hash.data) - i - 1];
4910
        hash.data[sizeof(hash.data) - i - 1] = tmp;
4911
    }
4912
#endif
4913
0
    return PyBytes_FromStringAndSize(hash.data, sizeof(hash.data));
4914
0
}
4915
4916
4917
PyDoc_STRVAR(doc_imp,
4918
"(Extremely) low-level import machinery bits as used by importlib.");
4919
4920
static PyMethodDef imp_methods[] = {
4921
    _IMP_EXTENSION_SUFFIXES_METHODDEF
4922
    _IMP_LOCK_HELD_METHODDEF
4923
    _IMP_ACQUIRE_LOCK_METHODDEF
4924
    _IMP_RELEASE_LOCK_METHODDEF
4925
    _IMP_FIND_FROZEN_METHODDEF
4926
    _IMP_GET_FROZEN_OBJECT_METHODDEF
4927
    _IMP_IS_FROZEN_PACKAGE_METHODDEF
4928
    _IMP_CREATE_BUILTIN_METHODDEF
4929
    _IMP_INIT_FROZEN_METHODDEF
4930
    _IMP_IS_BUILTIN_METHODDEF
4931
    _IMP_IS_FROZEN_METHODDEF
4932
    _IMP__FROZEN_MODULE_NAMES_METHODDEF
4933
    _IMP__OVERRIDE_FROZEN_MODULES_FOR_TESTS_METHODDEF
4934
    _IMP__OVERRIDE_MULTI_INTERP_EXTENSIONS_CHECK_METHODDEF
4935
    _IMP_CREATE_DYNAMIC_METHODDEF
4936
    _IMP_EXEC_DYNAMIC_METHODDEF
4937
    _IMP_EXEC_BUILTIN_METHODDEF
4938
    _IMP__FIX_CO_FILENAME_METHODDEF
4939
    _IMP_SOURCE_HASH_METHODDEF
4940
    {NULL, NULL}  /* sentinel */
4941
};
4942
4943
4944
static int
4945
imp_module_exec(PyObject *module)
4946
28
{
4947
28
    const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
4948
28
    PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
4949
28
    if (PyModule_Add(module, "check_hash_based_pycs", pyc_mode) < 0) {
4950
0
        return -1;
4951
0
    }
4952
4953
28
    if (PyModule_AddIntConstant(
4954
28
            module, "pyc_magic_number_token", PYC_MAGIC_NUMBER_TOKEN) < 0)
4955
0
    {
4956
0
        return -1;
4957
0
    }
4958
4959
28
    return 0;
4960
28
}
4961
4962
4963
static PyModuleDef_Slot imp_slots[] = {
4964
    {Py_mod_exec, imp_module_exec},
4965
    {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
4966
    {Py_mod_gil, Py_MOD_GIL_NOT_USED},
4967
    {0, NULL}
4968
};
4969
4970
static struct PyModuleDef imp_module = {
4971
    PyModuleDef_HEAD_INIT,
4972
    .m_name = "_imp",
4973
    .m_doc = doc_imp,
4974
    .m_size = 0,
4975
    .m_methods = imp_methods,
4976
    .m_slots = imp_slots,
4977
};
4978
4979
PyMODINIT_FUNC
4980
PyInit__imp(void)
4981
28
{
4982
28
    return PyModuleDef_Init(&imp_module);
4983
28
}