Coverage Report

Created: 2026-01-09 06:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython3/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
0
{
47
0
    return !_Py_IsMainInterpreter(interp)
48
0
        && !(interp->feature_flags & Py_RTFLAGS_USE_MAIN_OBMALLOC)
49
0
        && interp->ceval.own_gil;
50
0
}
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
1.78k
#define INITTAB _PyRuntime.imports.inittab
74
436
#define LAST_MODULE_INDEX _PyRuntime.imports.last_module_index
75
1.04k
#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
5.15M
    (interp)->imports.modules
86
#define MODULES_BY_INDEX(interp) \
87
242
    (interp)->imports.modules_by_index
88
#define IMPORTLIB(interp) \
89
1.62k
    (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
1.25k
    (interp)->imports.override_frozen_modules
94
#ifdef HAVE_DLOPEN
95
#  define DLOPENFLAGS(interp) \
96
56
        (interp)->imports.dlopenflags
97
#endif
98
#define IMPORT_FUNC(interp) \
99
2.83M
    (interp)->imports.import_func
100
101
#define IMPORT_LOCK(interp) \
102
18.3k
    (interp)->imports.lock
103
104
#define FIND_AND_LOAD(interp) \
105
1.33k
    (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
6.11k
{
128
6.11k
    _PyRecursiveMutex_Lock(&IMPORT_LOCK(interp));
129
6.11k
}
130
131
void
132
_PyImport_ReleaseLock(PyInterpreterState *interp)
133
6.11k
{
134
6.11k
    _PyRecursiveMutex_Unlock(&IMPORT_LOCK(interp));
135
6.11k
}
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
22
{
152
22
    assert(MODULES(interp) == NULL);
153
22
    MODULES(interp) = PyDict_New();
154
22
    if (MODULES(interp) == NULL) {
155
0
        return NULL;
156
0
    }
157
22
    return MODULES(interp);
158
22
}
159
160
PyObject *
161
_PyImport_GetModules(PyInterpreterState *interp)
162
823k
{
163
823k
    return MODULES(interp);
164
823k
}
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
4.32M
{
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
4.32M
    PyObject *modules = MODULES(tstate->interp);
195
4.32M
    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
4.32M
    return modules;
204
4.32M
}
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
2
{
216
2
    PyThreadState *tstate = _PyThreadState_GET();
217
2
    PyObject *modules = get_modules_dict(tstate, true);
218
2
    return PyObject_SetItem(modules, name, m);
219
2
}
220
221
int
222
_PyImport_SetModuleString(const char *name, PyObject *m)
223
26
{
224
26
    PyThreadState *tstate = _PyThreadState_GET();
225
26
    PyObject *modules = get_modules_dict(tstate, true);
226
26
    return PyMapping_SetItemString(modules, name, m);
227
26
}
228
229
static PyObject *
230
import_get_module(PyThreadState *tstate, PyObject *name)
231
4.32M
{
232
4.32M
    PyObject *modules = get_modules_dict(tstate, false);
233
4.32M
    if (modules == NULL) {
234
0
        return NULL;
235
0
    }
236
237
4.32M
    PyObject *m;
238
4.32M
    Py_INCREF(modules);
239
4.32M
    (void)PyMapping_GetOptionalItem(modules, name, &m);
240
4.32M
    Py_DECREF(modules);
241
4.32M
    return m;
242
4.32M
}
243
244
static int
245
import_ensure_initialized(PyInterpreterState *interp, PyObject *mod, PyObject *name)
246
4.02M
{
247
4.02M
    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
4.02M
    int rc = PyObject_GetOptionalAttr(mod, &_Py_ID(__spec__), &spec);
255
4.02M
    if (rc > 0) {
256
4.02M
        rc = _PyModuleSpec_IsInitializing(spec);
257
4.02M
        Py_DECREF(spec);
258
4.02M
    }
259
4.02M
    if (rc == 0) {
260
4.02M
        goto done;
261
4.02M
    }
262
171
    else if (rc < 0) {
263
0
        return rc;
264
0
    }
265
266
    /* Wait until module is done importing. */
267
171
    PyObject *value = PyObject_CallMethodOneArg(
268
171
        IMPORTLIB(interp), &_Py_ID(_lock_unlock_module), name);
269
171
    if (value == NULL) {
270
0
        return -1;
271
0
    }
272
171
    Py_DECREF(value);
273
274
4.02M
done:
275
    /* When -X importtime=2, print an import time entry even if an
276
       imported module has already been loaded.
277
     */
278
4.02M
    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
4.02M
    return 0;
287
171
}
288
289
static void remove_importlib_frames(PyThreadState *tstate);
290
291
PyObject *
292
PyImport_GetModule(PyObject *name)
293
823k
{
294
823k
    PyThreadState *tstate = _PyThreadState_GET();
295
823k
    PyObject *mod;
296
297
823k
    mod = import_get_module(tstate, name);
298
823k
    if (mod != NULL && mod != Py_None) {
299
823k
        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
823k
    }
305
823k
    return mod;
306
823k
}
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
66
{
315
66
    PyObject *m;
316
66
    if (PyMapping_GetOptionalItem(modules, name, &m) < 0) {
317
0
        return NULL;
318
0
    }
319
66
    if (m != NULL && PyModule_Check(m)) {
320
22
        return m;
321
22
    }
322
44
    Py_XDECREF(m);
323
44
    m = PyModule_NewObject(name);
324
44
    if (m == NULL)
325
0
        return NULL;
326
44
    if (PyObject_SetItem(modules, name, m) != 0) {
327
0
        Py_DECREF(m);
328
0
        return NULL;
329
0
    }
330
331
44
    return m;
332
44
}
333
334
static PyObject *
335
import_add_module(PyThreadState *tstate, PyObject *name)
336
66
{
337
66
    PyObject *modules = get_modules_dict(tstate, false);
338
66
    if (modules == NULL) {
339
0
        return NULL;
340
0
    }
341
342
66
    PyObject *m;
343
66
    Py_BEGIN_CRITICAL_SECTION(modules);
344
66
    m = import_add_module_lock_held(modules, name);
345
66
    Py_END_CRITICAL_SECTION();
346
66
    return m;
347
66
}
348
349
PyObject *
350
PyImport_AddModuleRef(const char *name)
351
22
{
352
22
    PyObject *name_obj = PyUnicode_FromString(name);
353
22
    if (name_obj == NULL) {
354
0
        return NULL;
355
0
    }
356
22
    PyThreadState *tstate = _PyThreadState_GET();
357
22
    PyObject *module = import_add_module(tstate, name_obj);
358
22
    Py_DECREF(name_obj);
359
22
    return module;
360
22
}
361
362
363
PyObject *
364
PyImport_AddModuleObject(PyObject *name)
365
22
{
366
22
    PyThreadState *tstate = _PyThreadState_GET();
367
22
    PyObject *mod = import_add_module(tstate, name);
368
22
    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
22
    PyObject *ref = PyWeakref_NewRef(mod, NULL);
383
22
    Py_DECREF(mod);
384
22
    if (ref == NULL) {
385
0
        return NULL;
386
0
    }
387
22
    mod = _PyWeakref_GET_REF(ref);
388
22
    Py_DECREF(ref);
389
22
    Py_XDECREF(mod);
390
391
22
    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
22
    return mod; /* borrowed reference */
397
22
}
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
436
{
445
436
    return _Py_atomic_add_ssize(&LAST_MODULE_INDEX, 1) + 1;
446
436
}
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
0
#ifndef NDEBUG
459
0
    struct extensions_cache_value *cached = _find_cached_def(def);
460
0
    assert(cached == NULL || index == _get_cached_module_index(cached));
461
0
#endif
462
0
    return index;
463
0
}
464
465
static void
466
_set_module_index(PyModuleDef *def, Py_ssize_t index)
467
44
{
468
44
    assert(index > 0);
469
44
    if (index == def->m_base.m_index) {
470
        /* There's nothing to do. */
471
44
    }
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
44
}
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
44
{
515
44
    assert(index > 0);
516
517
44
    if (MODULES_BY_INDEX(interp) == NULL) {
518
22
        MODULES_BY_INDEX(interp) = PyList_New(0);
519
22
        if (MODULES_BY_INDEX(interp) == NULL) {
520
0
            return -1;
521
0
        }
522
22
    }
523
524
154
    while (PyList_GET_SIZE(MODULES_BY_INDEX(interp)) <= index) {
525
110
        if (PyList_Append(MODULES_BY_INDEX(interp), Py_None) < 0) {
526
0
            return -1;
527
0
        }
528
110
    }
529
530
44
    return PyList_SetItem(MODULES_BY_INDEX(interp), index, Py_NewRef(module));
531
44
}
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
1.48k
# define PKGCONTEXT pkgcontext
821
822
const char *
823
_PyImport_ResolveNameWithPackageContext(const char *name)
824
88
{
825
88
    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
88
    return name;
833
88
}
834
835
const char *
836
_PyImport_SwapPackageContext(const char *newcontext)
837
696
{
838
696
    const char *oldcontext = PKGCONTEXT;
839
696
    PKGCONTEXT = newcontext;
840
696
    return oldcontext;
841
696
}
842
843
#ifdef HAVE_DLOPEN
844
int
845
_PyImport_GetDLOpenFlags(PyInterpreterState *interp)
846
56
{
847
56
    return DLOPENFLAGS(interp);
848
56
}
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
348
exec_builtin_or_dynamic(PyObject *mod) {
861
348
    void *state;
862
863
348
    if (!PyModule_Check(mod)) {
864
0
        return 0;
865
0
    }
866
867
348
    state = PyModule_GetState(mod);
868
348
    if (state) {
869
        /* Already initialized; skip reload */
870
0
        return 0;
871
0
    }
872
873
348
    return PyModule_Exec(mod);
874
348
}
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
480
{
973
480
    PyMutex_Lock(&_PyRuntime.imports.extensions.mutex);
974
480
}
975
976
static inline void
977
extensions_lock_release(void)
978
480
{
979
480
    PyMutex_Unlock(&_PyRuntime.imports.extensions.mutex);
980
480
}
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
44
{
1041
44
    struct extensions_cache_value *value
1042
44
            = PyMem_RawMalloc(sizeof(struct extensions_cache_value));
1043
44
    if (value == NULL) {
1044
0
        PyErr_NoMemory();
1045
0
        return NULL;
1046
0
    }
1047
44
    *value = (struct extensions_cache_value){0};
1048
44
    return value;
1049
44
}
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
44
{
1060
44
    assert(cached->m_index > 0);
1061
44
    return cached->m_index;
1062
44
}
1063
1064
static void
1065
fixup_cached_def(struct extensions_cache_value *value)
1066
44
{
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
44
    PyModuleDef *def = value->def;
1077
44
    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
44
    _Py_SetImmortalUntracked((PyObject *)def);
1082
1083
44
    def->m_base.m_init = value->m_init;
1084
1085
44
    assert(value->m_index > 0);
1086
44
    _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
44
    assert(def->m_base.m_copy == NULL
1091
44
           || def->m_base.m_init == NULL
1092
44
           || value->m_dict != NULL);
1093
44
    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
44
}
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
44
{
1109
44
    Py_XDECREF(oldbase->m_copy);
1110
44
}
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
44
{
1128
44
    assert(value != NULL);
1129
    /* This should only have been called without an m_dict already set. */
1130
44
    assert(value->m_dict == NULL);
1131
44
    if (m_dict == NULL) {
1132
44
        return 0;
1133
44
    }
1134
44
    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
436
{
1218
436
    const char *str1_data = _PyUnicode_AsUTF8NoNUL(str1);
1219
436
    const char *str2_data = _PyUnicode_AsUTF8NoNUL(str2);
1220
436
    if (str1_data == NULL || str2_data == NULL) {
1221
0
        return NULL;
1222
0
    }
1223
436
    Py_ssize_t str1_len = strlen(str1_data);
1224
436
    Py_ssize_t str2_len = strlen(str2_data);
1225
1226
    /* Make sure sep and the NULL byte won't cause an overflow. */
1227
436
    assert(SIZE_MAX - str1_len - str2_len > 2);
1228
436
    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
436
    char *key = PyMem_RawMalloc(size);
1232
436
    if (key == NULL) {
1233
0
        PyErr_NoMemory();
1234
0
        return NULL;
1235
0
    }
1236
1237
436
    memcpy(key, str1_data, str1_len);
1238
436
    key[str1_len] = sep;
1239
436
    memcpy(key + str1_len + 1, str2_data, str2_len);
1240
436
    key[size - 1] = '\0';
1241
436
    assert(strlen(key) == size - 1);
1242
436
    return key;
1243
436
}
1244
1245
static Py_uhash_t
1246
hashtable_hash_str(const void *key)
1247
524
{
1248
524
    return Py_HashBuffer(key, strlen((const char *)key));
1249
524
}
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
392
{
1260
392
    PyMem_RawFree(ptr);
1261
392
}
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
0
{
1273
0
    if (value == NULL) {
1274
        /* It was previously deleted. */
1275
0
        return 0;
1276
0
    }
1277
0
    struct hashtable_next_match_def_data *data
1278
0
            = (struct hashtable_next_match_def_data *)user_data;
1279
0
    struct extensions_cache_value *cur
1280
0
            = (struct extensions_cache_value *)value;
1281
0
    if (cur->def == data->def) {
1282
0
        data->matched = cur;
1283
0
        return 1;
1284
0
    }
1285
0
    return 0;
1286
0
}
1287
1288
static struct extensions_cache_value *
1289
_find_cached_def(PyModuleDef *def)
1290
0
{
1291
0
    struct hashtable_next_match_def_data data = {0};
1292
0
    (void)_Py_hashtable_foreach(
1293
0
            EXTENSIONS.hashtable, hashtable_next_match_def, &data);
1294
0
    return data.matched;
1295
0
}
1296
#endif
1297
1298
436
#define HTSEP ':'
1299
1300
static int
1301
_extensions_cache_init(void)
1302
22
{
1303
22
    _Py_hashtable_allocator_t alloc = {PyMem_RawMalloc, PyMem_RawFree};
1304
22
    EXTENSIONS.hashtable = _Py_hashtable_new_full(
1305
22
        hashtable_hash_str,
1306
22
        hashtable_compare_str,
1307
22
        hashtable_destroy_str,  // key
1308
22
        del_extensions_cache_value,  // value
1309
22
        &alloc
1310
22
    );
1311
22
    if (EXTENSIONS.hashtable == NULL) {
1312
0
        PyErr_NoMemory();
1313
0
        return -1;
1314
0
    }
1315
22
    return 0;
1316
22
}
1317
1318
static _Py_hashtable_entry_t *
1319
_extensions_cache_find_unlocked(PyObject *path, PyObject *name,
1320
                                void **p_key)
1321
480
{
1322
480
    if (EXTENSIONS.hashtable == NULL) {
1323
44
        return NULL;
1324
44
    }
1325
436
    void *key = hashtable_key_from_2_strings(path, name, HTSEP);
1326
436
    if (key == NULL) {
1327
0
        return NULL;
1328
0
    }
1329
436
    _Py_hashtable_entry_t *entry =
1330
436
            _Py_hashtable_get_entry(EXTENSIONS.hashtable, key);
1331
436
    if (p_key != NULL) {
1332
44
        *p_key = key;
1333
44
    }
1334
392
    else {
1335
392
        hashtable_destroy_str(key);
1336
392
    }
1337
436
    return entry;
1338
436
}
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
436
{
1344
436
    struct extensions_cache_value *value = NULL;
1345
436
    extensions_lock_acquire();
1346
1347
436
    _Py_hashtable_entry_t *entry =
1348
436
            _extensions_cache_find_unlocked(path, name, NULL);
1349
436
    if (entry == NULL) {
1350
        /* It was never added. */
1351
436
        goto finally;
1352
436
    }
1353
0
    value = (struct extensions_cache_value *)entry->value;
1354
1355
436
finally:
1356
436
    extensions_lock_release();
1357
436
    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
44
{
1367
44
    struct extensions_cache_value *value = NULL;
1368
44
    void *key = NULL;
1369
44
    struct extensions_cache_value *newvalue = NULL;
1370
44
    PyModuleDef_Base olddefbase = def->m_base;
1371
1372
44
    assert(def != NULL);
1373
44
    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
44
    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
44
    assert(def->m_base.m_copy == NULL || m_dict != NULL);
1379
44
    assert((origin == _Py_ext_module_origin_DYNAMIC) == (name != path));
1380
44
    assert(origin != _Py_ext_module_origin_CORE || m_dict == NULL);
1381
1382
44
    extensions_lock_acquire();
1383
1384
44
    if (EXTENSIONS.hashtable == NULL) {
1385
22
        if (_extensions_cache_init() < 0) {
1386
0
            goto finally;
1387
0
        }
1388
22
    }
1389
1390
    /* Create a cached value to populate for the module. */
1391
44
    _Py_hashtable_entry_t *entry =
1392
44
            _extensions_cache_find_unlocked(path, name, &key);
1393
44
    value = entry == NULL
1394
44
        ? NULL
1395
44
        : (struct extensions_cache_value *)entry->value;
1396
44
    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
44
    newvalue = alloc_extensions_cache_value();
1408
44
    if (newvalue == NULL) {
1409
0
        goto finally;
1410
0
    }
1411
1412
    /* Populate the new cache value data. */
1413
44
    *newvalue = (struct extensions_cache_value){
1414
44
        .def=def,
1415
44
        .m_init=m_init,
1416
44
        .m_index=m_index,
1417
        /* m_dict is set by set_cached_m_dict(). */
1418
44
        .origin=origin,
1419
#ifdef Py_GIL_DISABLED
1420
        .md_requires_gil=requires_gil,
1421
#endif
1422
44
    };
1423
44
#ifndef Py_GIL_DISABLED
1424
44
    (void)requires_gil;
1425
44
#endif
1426
44
    if (init_cached_m_dict(newvalue, m_dict) < 0) {
1427
0
        goto finally;
1428
0
    }
1429
44
    fixup_cached_def(newvalue);
1430
1431
44
    if (entry == NULL) {
1432
        /* It was never added. */
1433
44
        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
44
        key = NULL;
1439
44
    }
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
44
    value = newvalue;
1458
1459
44
finally:
1460
44
    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
44
    else {
1467
44
        cleanup_old_cached_def(&olddefbase);
1468
44
    }
1469
1470
44
finally_oldvalue:
1471
44
    extensions_lock_release();
1472
44
    if (key != NULL) {
1473
0
        hashtable_destroy_str(key);
1474
0
    }
1475
1476
44
    return value;
1477
44
}
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
348
{
1604
348
    if (_Py_IsMainInterpreter(tstate->interp)) {
1605
348
        return tstate;
1606
348
    }
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
0
#ifndef NDEBUG
1613
0
    PyThreadState *old_tstate = PyThreadState_Swap(main_tstate);
1614
0
    assert(old_tstate == tstate);
1615
#else
1616
    (void)PyThreadState_Swap(main_tstate);
1617
#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
436
{
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
436
    if (path == name) {
1676
408
        if (PyUnicode_CompareWithASCIIString(name, "sys") == 0) {
1677
44
            return 1;
1678
44
        }
1679
364
        if (PyUnicode_CompareWithASCIIString(name, "builtins") == 0) {
1680
44
            return 1;
1681
44
        }
1682
364
    }
1683
348
    return 0;
1684
436
}
1685
1686
1687
static _Py_ext_module_kind
1688
_get_extension_kind(PyModuleDef *def, bool check_size)
1689
392
{
1690
392
    _Py_ext_module_kind kind;
1691
392
    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
0
        kind = _Py_ext_module_kind_SINGLEPHASE;
1695
0
    }
1696
392
    else if (def->m_slots != NULL) {
1697
348
        kind = _Py_ext_module_kind_MULTIPHASE;
1698
348
    }
1699
44
    else if (check_size && def->m_size == -1) {
1700
44
        kind = _Py_ext_module_kind_SINGLEPHASE;
1701
44
    }
1702
0
    else if (def->m_base.m_init != NULL) {
1703
0
        kind = _Py_ext_module_kind_SINGLEPHASE;
1704
0
    }
1705
0
    else {
1706
        // This is probably single-phase init, but a multi-phase
1707
        // module *can* have NULL m_slots.
1708
0
        kind = _Py_ext_module_kind_UNKNOWN;
1709
0
    }
1710
392
    return kind;
1711
392
}
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
348
    do {                                                            \
1718
348
        _Py_ext_module_kind kind = _get_extension_kind(def, false); \
1719
348
        assert(kind == _Py_ext_module_kind_MULTIPHASE               \
1720
348
                /* m_slots can be NULL. */                          \
1721
348
                || kind == _Py_ext_module_kind_UNKNOWN);            \
1722
348
    } while (0)
1723
1724
#define assert_singlephase_def(def)                                 \
1725
44
    do {                                                            \
1726
44
        _Py_ext_module_kind kind = _get_extension_kind(def, true);  \
1727
44
        assert(kind == _Py_ext_module_kind_SINGLEPHASE              \
1728
44
                || kind == _Py_ext_module_kind_UNKNOWN);            \
1729
44
    } while (0)
1730
1731
#define assert_singlephase(cached)                                          \
1732
0
    do {                                                                    \
1733
0
        _Py_ext_module_kind kind = _get_extension_kind(cached->def, true);  \
1734
0
        assert(kind == _Py_ext_module_kind_SINGLEPHASE);                    \
1735
0
    } 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
44
{
1758
44
    struct extensions_cache_value *cached = NULL;
1759
44
    PyModInitFunction m_init = NULL;
1760
44
    PyObject *m_dict = NULL;
1761
1762
    /* Set up for _extensions_cache_set(). */
1763
44
    if (singlephase == NULL) {
1764
0
        assert(def->m_base.m_init == NULL);
1765
0
        assert(def->m_base.m_copy == NULL);
1766
0
    }
1767
44
    else {
1768
44
        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
44
        else if (singlephase->m_dict == NULL) {
1781
            /* It must be a core builtin module. */
1782
44
            assert(is_core_module(tstate->interp, name, path));
1783
44
            assert(def->m_size == -1);
1784
44
            assert(def->m_base.m_copy == NULL);
1785
44
            assert(def->m_base.m_init == NULL);
1786
44
        }
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
44
    }
1798
1799
    /* Add the module's def to the global cache. */
1800
    // XXX Why special-case the main interpreter?
1801
44
    if (_Py_IsMainInterpreter(tstate->interp) || def->m_size == -1) {
1802
44
#ifndef NDEBUG
1803
44
        cached = _extensions_cache_get(path, name);
1804
44
        assert(cached == NULL || cached->def == def);
1805
44
#endif
1806
44
        cached = _extensions_cache_set(
1807
44
                path, name, def, m_init, singlephase->m_index, m_dict,
1808
44
                singlephase->origin, singlephase->md_requires_gil);
1809
44
        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
44
    }
1815
1816
44
    return cached;
1817
44
}
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
44
{
1826
44
    assert(mod != NULL && PyModule_Check(mod));
1827
44
    assert(cached->def == _PyModule_GetDefOrNull(mod));
1828
1829
44
    Py_ssize_t index = _get_cached_module_index(cached);
1830
44
    if (_modules_by_index_set(tstate->interp, index, mod) < 0) {
1831
0
        return -1;
1832
0
    }
1833
1834
44
    if (modules != NULL) {
1835
44
        if (PyObject_SetItem(modules, name, mod) < 0) {
1836
0
            return -1;
1837
0
        }
1838
44
    }
1839
1840
44
    return 0;
1841
44
}
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
348
{
1960
    /* Only single-phase init modules will be in the cache. */
1961
348
    struct extensions_cache_value *cached
1962
348
            = _extensions_cache_get(info->path, info->name);
1963
348
    if (cached == NULL) {
1964
348
        return NULL;
1965
348
    }
1966
348
    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
348
{
2035
    /* Core modules go through _PyImport_FixupBuiltin(). */
2036
348
    assert(!is_core_module(tstate->interp, info->name, info->path));
2037
2038
348
    PyObject *mod = NULL;
2039
348
    PyModuleDef *def = NULL;
2040
348
    struct extensions_cache_value *cached = NULL;
2041
348
    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
348
    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
348
    PyThreadState *main_tstate = switch_to_main_interpreter(tstate);
2092
348
    if (main_tstate == NULL) {
2093
0
        return NULL;
2094
0
    }
2095
348
    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
348
    struct _Py_ext_module_loader_result res;
2103
348
    int rc = _PyImport_RunModInitFunc(p0, info, &res);
2104
348
    if (rc < 0) {
2105
        /* We discard res.def. */
2106
0
        assert(res.module == NULL);
2107
0
    }
2108
348
    else {
2109
348
        assert(!PyErr_Occurred());
2110
348
        assert(res.err == NULL);
2111
2112
348
        mod = res.module;
2113
348
        res.module = NULL;
2114
348
        def = res.def;
2115
348
        assert(def != NULL);
2116
2117
        /* Do anything else that should be done
2118
         * while still using the main interpreter. */
2119
348
        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
348
    }
2177
2178
348
main_finally:
2179
    /* Switch back to the subinterpreter. */
2180
348
    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
348
    if (rc < 0) {
2194
0
        _Py_ext_module_loader_result_apply_error(&res, name_buf);
2195
0
        goto error;
2196
0
    }
2197
2198
348
    if (res.kind == _Py_ext_module_kind_MULTIPHASE) {
2199
348
        assert_multiphase_def(def);
2200
348
        assert(mod == NULL);
2201
        /* Note that we cheat a little by not repeating the calls
2202
         * to _PyImport_GetModuleExportHooks() and _PyImport_RunModInitFunc(). */
2203
348
        mod = PyModule_FromDefAndSpec(def, spec);
2204
348
        if (mod == NULL) {
2205
0
            goto error;
2206
0
        }
2207
348
    }
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
348
    _Py_ext_module_loader_result_clear(&res);
2244
348
    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
348
}
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
44
{
2307
44
    int res = -1;
2308
44
    assert(mod != NULL && PyModule_Check(mod));
2309
2310
44
    PyObject *nameobj;
2311
44
    nameobj = PyUnicode_InternFromString(name);
2312
44
    if (nameobj == NULL) {
2313
0
        return -1;
2314
0
    }
2315
2316
44
    PyModuleDef *def = _PyModule_GetDefOrNull(mod);
2317
44
    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
44
    assert(is_core_module(tstate->interp, nameobj, nameobj));
2328
44
    assert_singlephase_def(def);
2329
44
    assert(def->m_size == -1);
2330
44
    assert(def->m_base.m_copy == NULL);
2331
44
    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
44
    struct extensions_cache_value *cached
2338
44
            = _extensions_cache_get(nameobj, nameobj);
2339
44
    if (cached == NULL) {
2340
44
        struct singlephase_global_update singlephase = {
2341
44
            .m_index=def->m_base.m_index,
2342
            /* We don't want def->m_base.m_copy populated. */
2343
44
            .m_dict=NULL,
2344
44
            .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
44
        };
2350
44
        cached = update_global_state_for_extension(
2351
44
                tstate, nameobj, nameobj, def, &singlephase);
2352
44
        if (cached == NULL) {
2353
0
            goto finally;
2354
0
        }
2355
44
    }
2356
2357
44
    if (finish_singlephase_extension(tstate, mod, cached, nameobj, modules) < 0) {
2358
0
        goto finally;
2359
0
    }
2360
2361
44
    res = 0;
2362
2363
44
finally:
2364
44
    Py_DECREF(nameobj);
2365
44
    return res;
2366
44
}
2367
2368
/* Helper to test for built-in module */
2369
2370
static int
2371
is_builtin(PyObject *name)
2372
1.39k
{
2373
1.39k
    int i;
2374
1.39k
    struct _inittab *inittab = INITTAB;
2375
48.4k
    for (i = 0; inittab[i].name != NULL; i++) {
2376
47.3k
        if (_PyUnicode_EqualToASCIIString(name, inittab[i].name)) {
2377
298
            if (inittab[i].initfunc == NULL)
2378
0
                return -1;
2379
298
            else
2380
298
                return 1;
2381
298
        }
2382
47.3k
    }
2383
1.09k
    return 0;
2384
1.39k
}
2385
2386
static struct _inittab*
2387
lookup_inittab_entry(const struct _Py_ext_module_loader_info* info)
2388
320
{
2389
6.23k
    for (struct _inittab *p = INITTAB; p->name != NULL; p++) {
2390
6.23k
        if (_PyUnicode_EqualToASCIIString(info->name, p->name)) {
2391
320
            return p;
2392
320
        }
2393
6.23k
    }
2394
    // not found
2395
0
    return NULL;
2396
320
}
2397
2398
static PyObject*
2399
create_builtin(
2400
    PyThreadState *tstate, PyObject *name,
2401
    PyObject *spec,
2402
    PyModInitFunction initfunc)
2403
320
{
2404
320
    struct _Py_ext_module_loader_info info;
2405
320
    if (_Py_ext_module_loader_info_init_for_builtin(&info, name) < 0) {
2406
0
        return NULL;
2407
0
    }
2408
2409
320
    struct extensions_cache_value *cached = NULL;
2410
320
    PyObject *mod = import_find_extension(tstate, &info, &cached);
2411
320
    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
320
    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
320
    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
320
    PyModInitFunction p0 = NULL;
2434
320
    if (initfunc == NULL) {
2435
320
        struct _inittab *entry = lookup_inittab_entry(&info);
2436
320
        if (entry == NULL) {
2437
0
            mod = NULL;
2438
0
            _PyErr_SetModuleNotFoundError(name);
2439
0
            goto finally;
2440
0
        }
2441
2442
320
        p0 = (PyModInitFunction)entry->initfunc;
2443
320
    }
2444
0
    else {
2445
0
        p0 = initfunc;
2446
0
    }
2447
2448
320
    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
320
    mod = import_run_extension(
2466
320
                    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
320
finally:
2475
320
    _Py_ext_module_loader_info_clear(&info);
2476
320
    return mod;
2477
320
}
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
22
{
2586
22
    size_t size;
2587
858
    for (size = 0; PyImport_Inittab[size].name != NULL; size++)
2588
836
        ;
2589
22
    size++;
2590
2591
    /* Make the copy. */
2592
22
    struct _inittab *copied = _PyMem_DefaultRawMalloc(size * sizeof(struct _inittab));
2593
22
    if (copied == NULL) {
2594
0
        return -1;
2595
0
    }
2596
22
    memcpy(copied, PyImport_Inittab, size * sizeof(struct _inittab));
2597
22
    INITTAB = copied;
2598
22
    return 0;
2599
22
}
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
22
{
2612
22
    PyObject *list = PyList_New(0);
2613
22
    if (list == NULL) {
2614
0
        return NULL;
2615
0
    }
2616
22
    struct _inittab *inittab = INITTAB;
2617
858
    for (Py_ssize_t i = 0; inittab[i].name != NULL; i++) {
2618
836
        PyObject *name = PyUnicode_FromString(inittab[i].name);
2619
836
        if (name == NULL) {
2620
0
            Py_DECREF(list);
2621
0
            return NULL;
2622
0
        }
2623
836
        if (PyList_Append(list, name) < 0) {
2624
0
            Py_DECREF(name);
2625
0
            Py_DECREF(list);
2626
0
            return NULL;
2627
0
        }
2628
836
        Py_DECREF(name);
2629
836
    }
2630
22
    return list;
2631
22
}
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
22
{
2739
22
    PyObject *m, *d;
2740
2741
22
    m = import_add_module(tstate, name);
2742
22
    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
22
    d = PyModule_GetDict(m);
2747
22
    int r = PyDict_Contains(d, &_Py_ID(__builtins__));
2748
22
    if (r == 0) {
2749
22
        r = PyDict_SetItem(d, &_Py_ID(__builtins__), PyEval_GetBuiltins());
2750
22
    }
2751
22
    if (r < 0) {
2752
0
        remove_module(tstate, name);
2753
0
        Py_DECREF(m);
2754
0
        return NULL;
2755
0
    }
2756
2757
22
    Py_INCREF(d);
2758
22
    Py_DECREF(m);
2759
22
    return d;
2760
22
}
2761
2762
static PyObject *
2763
exec_code_in_module(PyThreadState *tstate, PyObject *name,
2764
                    PyObject *module_dict, PyObject *code_object)
2765
22
{
2766
22
    PyObject *v, *m;
2767
2768
22
    v = PyEval_EvalCode(code_object, module_dict, module_dict);
2769
22
    if (v == NULL) {
2770
0
        remove_module(tstate, name);
2771
0
        return NULL;
2772
0
    }
2773
22
    Py_DECREF(v);
2774
2775
22
    m = import_get_module(tstate, name);
2776
22
    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
22
    return m;
2783
22
}
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
343
{
2842
343
    PyObject *oldname;
2843
2844
343
    if (PyUnicode_Compare(co->co_filename, newname) == 0)
2845
343
        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
560
{
2865
560
    const struct _module_alias *entry;
2866
4.20k
    for (entry = aliases; ; entry++) {
2867
4.20k
        if (entry->name == NULL) {
2868
            /* It isn't an alias. */
2869
450
            return false;
2870
450
        }
2871
3.75k
        if (strcmp(name, entry->name) == 0) {
2872
110
            if (alias != NULL) {
2873
110
                *alias = entry->orig;
2874
110
            }
2875
110
            return true;
2876
110
        }
2877
3.75k
    }
2878
560
}
2879
2880
static bool
2881
use_frozen(void)
2882
1.25k
{
2883
1.25k
    PyInterpreterState *interp = _PyInterpreterState_GET();
2884
1.25k
    int override = OVERRIDE_FROZEN_MODULES(interp);
2885
1.25k
    if (override > 0) {
2886
0
        return true;
2887
0
    }
2888
1.25k
    else if (override < 0) {
2889
0
        return false;
2890
0
    }
2891
1.25k
    else {
2892
1.25k
        return interp->config.use_frozen_modules;
2893
1.25k
    }
2894
1.25k
}
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
1.41k
{
3024
1.41k
    const struct _frozen *p;
3025
    // We always use the bootstrap modules.
3026
5.31k
    for (p = _PyImport_FrozenBootstrap; ; p++) {
3027
5.31k
        if (p->name == NULL) {
3028
            // We hit the end-of-list sentinel value.
3029
1.25k
            break;
3030
1.25k
        }
3031
4.06k
        if (strcmp(name, p->name) == 0) {
3032
154
            return p;
3033
154
        }
3034
4.06k
    }
3035
    // Prefer custom modules, if any.  Frozen stdlib modules can be
3036
    // disabled here by setting "code" to NULL in the array entry.
3037
1.25k
    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
1.25k
    if (use_frozen()) {
3049
15.2k
        for (p = _PyImport_FrozenStdlib; ; p++) {
3050
15.2k
            if (p->name == NULL) {
3051
852
                break;
3052
852
            }
3053
14.4k
            if (strcmp(name, p->name) == 0) {
3054
406
                return p;
3055
406
            }
3056
14.4k
        }
3057
10.2k
        for (p = _PyImport_FrozenTest; ; p++) {
3058
10.2k
            if (p->name == NULL) {
3059
852
                break;
3060
852
            }
3061
9.37k
            if (strcmp(name, p->name) == 0) {
3062
0
                return p;
3063
0
            }
3064
9.37k
        }
3065
852
    }
3066
852
    return NULL;
3067
1.25k
}
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
1.41k
{
3081
1.41k
    if (info != NULL) {
3082
1.41k
        memset(info, 0, sizeof(*info));
3083
1.41k
    }
3084
3085
1.41k
    if (nameobj == NULL || nameobj == Py_None) {
3086
0
        return FROZEN_BAD_NAME;
3087
0
    }
3088
1.41k
    const char *name = PyUnicode_AsUTF8(nameobj);
3089
1.41k
    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
1.41k
    const struct _frozen *p = look_up_frozen(name);
3099
1.41k
    if (p == NULL) {
3100
852
        return FROZEN_NOT_FOUND;
3101
852
    }
3102
560
    if (info != NULL) {
3103
560
        info->nameobj = nameobj;  // borrowed
3104
560
        info->data = (const char *)p->code;
3105
560
        info->size = p->size;
3106
560
        info->is_package = p->is_package;
3107
560
        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
560
        info->origname = name;
3113
560
        info->is_alias = resolve_module_alias(name, _PyImport_FrozenAliases,
3114
560
                                              &info->origname);
3115
560
    }
3116
560
    if (p->code == NULL) {
3117
        /* It is frozen but marked as un-importable. */
3118
0
        return FROZEN_EXCLUDED;
3119
0
    }
3120
560
    if (p->code[0] == '\0' || p->size == 0) {
3121
        /* Does not contain executable code. */
3122
0
        return FROZEN_INVALID;
3123
0
    }
3124
560
    return FROZEN_OKAY;
3125
560
}
3126
3127
static PyObject *
3128
unmarshal_frozen_code(PyInterpreterState *interp, struct frozen_info *info)
3129
269
{
3130
269
    PyObject *co = PyMarshal_ReadObjectFromString(info->data, info->size);
3131
269
    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
269
    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
269
    return co;
3146
269
}
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
22
{
3157
22
    PyThreadState *tstate = _PyThreadState_GET();
3158
22
    PyObject *co, *m, *d = NULL;
3159
22
    int err;
3160
3161
22
    struct frozen_info info;
3162
22
    frozen_status status = find_frozen(name, &info);
3163
22
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
3164
0
        return 0;
3165
0
    }
3166
22
    else if (status == FROZEN_BAD_NAME) {
3167
0
        return 0;
3168
0
    }
3169
22
    else if (status != FROZEN_OKAY) {
3170
0
        set_frozen_error(status, name);
3171
0
        return -1;
3172
0
    }
3173
22
    co = unmarshal_frozen_code(tstate->interp, &info);
3174
22
    if (co == NULL) {
3175
0
        return -1;
3176
0
    }
3177
22
    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
22
    d = module_dict_for_exec(tstate, name);
3196
22
    if (d == NULL) {
3197
0
        goto err_return;
3198
0
    }
3199
22
    m = exec_code_in_module(tstate, name, d, co);
3200
22
    if (m == NULL) {
3201
0
        goto err_return;
3202
0
    }
3203
22
    Py_DECREF(m);
3204
    /* Set __origname__ (consumed in FrozenImporter._setup_module()). */
3205
22
    PyObject *origname;
3206
22
    if (info.origname) {
3207
22
        origname = PyUnicode_FromString(info.origname);
3208
22
        if (origname == NULL) {
3209
0
            goto err_return;
3210
0
        }
3211
22
    }
3212
0
    else {
3213
0
        origname = Py_NewRef(Py_None);
3214
0
    }
3215
22
    err = PyDict_SetItemString(d, "__origname__", origname);
3216
22
    Py_DECREF(origname);
3217
22
    if (err != 0) {
3218
0
        goto err_return;
3219
0
    }
3220
22
    Py_DECREF(d);
3221
22
    Py_DECREF(co);
3222
22
    return 1;
3223
3224
0
err_return:
3225
0
    Py_XDECREF(d);
3226
0
    Py_DECREF(co);
3227
0
    return -1;
3228
22
}
3229
3230
int
3231
PyImport_ImportFrozenModule(const char *name)
3232
22
{
3233
22
    PyObject *nameobj;
3234
22
    int ret;
3235
22
    nameobj = PyUnicode_InternFromString(name);
3236
22
    if (nameobj == NULL)
3237
0
        return -1;
3238
22
    ret = PyImport_ImportFrozenModuleObject(nameobj);
3239
22
    Py_DECREF(nameobj);
3240
22
    return ret;
3241
22
}
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
22
{
3255
22
    PyObject *name = PyUnicode_FromString("_imp");
3256
22
    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
22
    PyObject *attrs = Py_BuildValue("{sO}", "name", name);
3265
22
    if (attrs == NULL) {
3266
0
        goto error;
3267
0
    }
3268
22
    PyObject *spec = _PyNamespace_New(attrs);
3269
22
    Py_DECREF(attrs);
3270
22
    if (spec == NULL) {
3271
0
        goto error;
3272
0
    }
3273
3274
    // Create the _imp module from its definition.
3275
22
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
3276
22
    Py_CLEAR(name);
3277
22
    Py_DECREF(spec);
3278
22
    if (mod == NULL) {
3279
0
        goto error;
3280
0
    }
3281
22
    assert(mod != Py_None);  // not found
3282
3283
    // Execute the _imp module: call imp_module_exec().
3284
22
    if (exec_builtin_or_dynamic(mod) < 0) {
3285
0
        Py_DECREF(mod);
3286
0
        goto error;
3287
0
    }
3288
22
    return mod;
3289
3290
0
error:
3291
0
    Py_XDECREF(name);
3292
0
    return NULL;
3293
22
}
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
22
{
3309
22
    assert(!_PyErr_Occurred(tstate));
3310
3311
22
    PyInterpreterState *interp = tstate->interp;
3312
22
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
3313
3314
    // Import _importlib through its frozen version, _frozen_importlib.
3315
22
    if (verbose) {
3316
0
        PySys_FormatStderr("import _frozen_importlib # frozen\n");
3317
0
    }
3318
22
    if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
3319
0
        return -1;
3320
0
    }
3321
3322
22
    PyObject *importlib = PyImport_AddModuleRef("_frozen_importlib");
3323
22
    if (importlib == NULL) {
3324
0
        return -1;
3325
0
    }
3326
22
    IMPORTLIB(interp) = importlib;
3327
3328
    // Import the _imp module
3329
22
    if (verbose) {
3330
0
        PySys_FormatStderr("import _imp # builtin\n");
3331
0
    }
3332
22
    PyObject *imp_mod = bootstrap_imp(tstate);
3333
22
    if (imp_mod == NULL) {
3334
0
        return -1;
3335
0
    }
3336
22
    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
22
    PyObject *value = PyObject_CallMethod(importlib, "_install",
3343
22
                                          "OO", sysmod, imp_mod);
3344
22
    Py_DECREF(imp_mod);
3345
22
    if (value == NULL) {
3346
0
        return -1;
3347
0
    }
3348
22
    Py_DECREF(value);
3349
3350
22
    assert(!_PyErr_Occurred(tstate));
3351
22
    return 0;
3352
22
}
3353
3354
3355
static int
3356
init_importlib_external(PyInterpreterState *interp)
3357
22
{
3358
22
    PyObject *value;
3359
22
    value = PyObject_CallMethod(IMPORTLIB(interp),
3360
22
                                "_install_external_importers", "");
3361
22
    if (value == NULL) {
3362
0
        return -1;
3363
0
    }
3364
22
    Py_DECREF(value);
3365
22
    return 0;
3366
22
}
3367
3368
PyObject *
3369
_PyImport_GetImportlibLoader(PyInterpreterState *interp,
3370
                             const char *loader_name)
3371
22
{
3372
22
    return PyObject_GetAttrString(IMPORTLIB(interp), loader_name);
3373
22
}
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
22
{
3501
    // Get the __import__ function
3502
22
    PyObject *import_func;
3503
22
    if (PyDict_GetItemStringRef(interp->builtins, "__import__", &import_func) <= 0) {
3504
0
        return -1;
3505
0
    }
3506
22
    IMPORT_FUNC(interp) = import_func;
3507
22
    return 0;
3508
22
}
3509
3510
int
3511
_PyImport_IsDefaultImportFunc(PyInterpreterState *interp, PyObject *func)
3512
2.83M
{
3513
2.83M
    return func == IMPORT_FUNC(interp);
3514
2.83M
}
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
21.4k
{
3523
21.4k
    PyObject *pname;
3524
21.4k
    PyObject *result;
3525
3526
21.4k
    pname = PyUnicode_FromString(name);
3527
21.4k
    if (pname == NULL)
3528
0
        return NULL;
3529
21.4k
    result = PyImport_Import(pname);
3530
21.4k
    Py_DECREF(pname);
3531
21.4k
    return result;
3532
21.4k
}
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
481
{
3564
481
    const char *importlib_filename = "<frozen importlib._bootstrap>";
3565
481
    const char *external_filename = "<frozen importlib._bootstrap_external>";
3566
481
    const char *remove_frames = "_call_with_frames_removed";
3567
481
    int always_trim = 0;
3568
481
    int in_importlib = 0;
3569
481
    PyObject **prev_link, **outer_link = NULL;
3570
481
    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
481
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3577
481
    if (exc == NULL || _PyInterpreterState_GetConfig(tstate->interp)->verbose) {
3578
0
        goto done;
3579
0
    }
3580
3581
481
    if (PyType_IsSubtype(Py_TYPE(exc), (PyTypeObject *) PyExc_ImportError)) {
3582
481
        always_trim = 1;
3583
481
    }
3584
3585
481
    assert(PyExceptionInstance_Check(exc));
3586
481
    base_tb = PyException_GetTraceback(exc);
3587
481
    prev_link = &base_tb;
3588
481
    PyObject *tb = base_tb;
3589
1.44k
    while (tb != NULL) {
3590
962
        assert(PyTraceBack_Check(tb));
3591
962
        PyTracebackObject *traceback = (PyTracebackObject *)tb;
3592
962
        PyObject *next = (PyObject *) traceback->tb_next;
3593
962
        PyFrameObject *frame = traceback->tb_frame;
3594
962
        PyCodeObject *code = PyFrame_GetCode(frame);
3595
962
        int now_in_importlib;
3596
3597
962
        now_in_importlib = _PyUnicode_EqualToASCIIString(code->co_filename, importlib_filename) ||
3598
0
                           _PyUnicode_EqualToASCIIString(code->co_filename, external_filename);
3599
962
        if (now_in_importlib && !in_importlib) {
3600
            /* This is the link to this chunk of importlib tracebacks */
3601
481
            outer_link = prev_link;
3602
481
        }
3603
962
        in_importlib = now_in_importlib;
3604
3605
962
        if (in_importlib &&
3606
962
            (always_trim ||
3607
962
             _PyUnicode_EqualToASCIIString(code->co_name, remove_frames))) {
3608
962
            Py_XSETREF(*outer_link, Py_XNewRef(next));
3609
962
            prev_link = outer_link;
3610
962
        }
3611
0
        else {
3612
0
            prev_link = (PyObject **) &traceback->tb_next;
3613
0
        }
3614
962
        Py_DECREF(code);
3615
962
        tb = next;
3616
962
    }
3617
481
    if (base_tb == NULL) {
3618
481
        base_tb = Py_None;
3619
481
        Py_INCREF(Py_None);
3620
481
    }
3621
481
    PyException_SetTraceback(exc, base_tb);
3622
481
done:
3623
481
    Py_XDECREF(base_tb);
3624
481
    _PyErr_SetRaisedException(tstate, exc);
3625
481
}
3626
3627
3628
static PyObject *
3629
resolve_name(PyThreadState *tstate, PyObject *name, PyObject *globals, int level)
3630
59
{
3631
59
    PyObject *abs_name;
3632
59
    PyObject *package = NULL;
3633
59
    PyObject *spec = NULL;
3634
59
    Py_ssize_t last_dot;
3635
59
    PyObject *base;
3636
59
    int level_up;
3637
3638
59
    if (globals == NULL) {
3639
0
        _PyErr_SetString(tstate, PyExc_KeyError, "'__name__' not in globals");
3640
0
        goto error;
3641
0
    }
3642
59
    if (!PyDict_Check(globals)) {
3643
0
        _PyErr_SetString(tstate, PyExc_TypeError, "globals must be a dict");
3644
0
        goto error;
3645
0
    }
3646
59
    if (PyDict_GetItemRef(globals, &_Py_ID(__package__), &package) < 0) {
3647
0
        goto error;
3648
0
    }
3649
59
    if (package == Py_None) {
3650
0
        Py_DECREF(package);
3651
0
        package = NULL;
3652
0
    }
3653
59
    if (PyDict_GetItemRef(globals, &_Py_ID(__spec__), &spec) < 0) {
3654
0
        goto error;
3655
0
    }
3656
3657
59
    if (package != NULL) {
3658
59
        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
59
        else if (spec != NULL && spec != Py_None) {
3664
59
            int equal;
3665
59
            PyObject *parent = PyObject_GetAttr(spec, &_Py_ID(parent));
3666
59
            if (parent == NULL) {
3667
0
                goto error;
3668
0
            }
3669
3670
59
            equal = PyObject_RichCompareBool(package, parent, Py_EQ);
3671
59
            Py_DECREF(parent);
3672
59
            if (equal < 0) {
3673
0
                goto error;
3674
0
            }
3675
59
            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
59
        }
3682
59
    }
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
59
    last_dot = PyUnicode_GET_LENGTH(package);
3740
59
    if (last_dot == 0) {
3741
0
        goto no_parent_error;
3742
0
    }
3743
3744
59
    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
59
    Py_XDECREF(spec);
3758
59
    base = PyUnicode_Substring(package, 0, last_dot);
3759
59
    Py_DECREF(package);
3760
59
    if (base == NULL || PyUnicode_GET_LENGTH(name) == 0) {
3761
36
        return base;
3762
36
    }
3763
3764
23
    abs_name = PyUnicode_FromFormat("%U.%U", base, name);
3765
23
    Py_DECREF(base);
3766
23
    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
1.33k
{
3782
1.33k
    PyObject *mod = NULL;
3783
1.33k
    PyInterpreterState *interp = tstate->interp;
3784
1.33k
    int import_time = _PyInterpreterState_GetConfig(interp)->import_time;
3785
1.33k
#define import_level FIND_AND_LOAD(interp).import_level
3786
1.33k
#define accumulated FIND_AND_LOAD(interp).accumulated
3787
3788
1.33k
    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
1.33k
    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
1.33k
    if (PyDTrace_IMPORT_FIND_LOAD_START_ENABLED())
3805
0
        PyDTrace_IMPORT_FIND_LOAD_START(PyUnicode_AsUTF8(abs_name));
3806
3807
1.33k
    mod = PyObject_CallMethodObjArgs(IMPORTLIB(interp), &_Py_ID(_find_and_load),
3808
1.33k
                                     abs_name, IMPORT_FUNC(interp), NULL);
3809
3810
1.33k
    if (PyDTrace_IMPORT_FIND_LOAD_DONE_ENABLED())
3811
0
        PyDTrace_IMPORT_FIND_LOAD_DONE(PyUnicode_AsUTF8(abs_name),
3812
0
                                       mod != NULL);
3813
3814
1.33k
    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
1.33k
    return mod;
3829
1.33k
#undef import_level
3830
1.33k
#undef accumulated
3831
1.33k
}
3832
3833
PyObject *
3834
PyImport_ImportModuleLevelObject(PyObject *name, PyObject *globals,
3835
                                 PyObject *locals, PyObject *fromlist,
3836
                                 int level)
3837
3.19M
{
3838
3.19M
    PyThreadState *tstate = _PyThreadState_GET();
3839
3.19M
    PyObject *abs_name = NULL;
3840
3.19M
    PyObject *final_mod = NULL;
3841
3.19M
    PyObject *mod = NULL;
3842
3.19M
    PyInterpreterState *interp = tstate->interp;
3843
3.19M
    int has_from;
3844
3845
3.19M
    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
3.19M
    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
3.19M
    if (level < 0) {
3859
0
        _PyErr_SetString(tstate, PyExc_ValueError, "level must be >= 0");
3860
0
        goto error;
3861
0
    }
3862
3863
3.19M
    if (level > 0) {
3864
59
        abs_name = resolve_name(tstate, name, globals, level);
3865
59
        if (abs_name == NULL)
3866
0
            goto error;
3867
59
    }
3868
3.19M
    else {  /* level == 0 */
3869
3.19M
        if (PyUnicode_GET_LENGTH(name) == 0) {
3870
0
            _PyErr_SetString(tstate, PyExc_ValueError, "Empty module name");
3871
0
            goto error;
3872
0
        }
3873
3.19M
        abs_name = Py_NewRef(name);
3874
3.19M
    }
3875
3876
3.19M
    mod = import_get_module(tstate, abs_name);
3877
3.19M
    if (mod == NULL && _PyErr_Occurred(tstate)) {
3878
0
        goto error;
3879
0
    }
3880
3881
3.19M
    if (mod != NULL && mod != Py_None) {
3882
3.19M
        if (import_ensure_initialized(tstate->interp, mod, abs_name) < 0) {
3883
0
            goto error;
3884
0
        }
3885
3.19M
    }
3886
1.33k
    else {
3887
1.33k
        Py_XDECREF(mod);
3888
1.33k
        mod = import_find_and_load(tstate, abs_name);
3889
1.33k
        if (mod == NULL) {
3890
481
            goto error;
3891
481
        }
3892
1.33k
    }
3893
3894
3.19M
    has_from = 0;
3895
3.19M
    if (fromlist != NULL && fromlist != Py_None) {
3896
305k
        has_from = PyObject_IsTrue(fromlist);
3897
305k
        if (has_from < 0)
3898
0
            goto error;
3899
305k
    }
3900
3.19M
    if (!has_from) {
3901
3.19M
        Py_ssize_t len = PyUnicode_GET_LENGTH(name);
3902
3.19M
        if (level == 0 || len > 0) {
3903
3.19M
            Py_ssize_t dot;
3904
3905
3.19M
            dot = PyUnicode_FindChar(name, '.', 0, len, 1);
3906
3.19M
            if (dot == -2) {
3907
0
                goto error;
3908
0
            }
3909
3910
3.19M
            if (dot == -1) {
3911
                /* No dot in module name, simple exit */
3912
3.19M
                final_mod = Py_NewRef(mod);
3913
3.19M
                goto error;
3914
3.19M
            }
3915
3916
4.62k
            if (level == 0) {
3917
4.62k
                PyObject *front = PyUnicode_Substring(name, 0, dot);
3918
4.62k
                if (front == NULL) {
3919
0
                    goto error;
3920
0
                }
3921
3922
4.62k
                final_mod = PyImport_ImportModuleLevelObject(front, NULL, NULL, NULL, 0);
3923
4.62k
                Py_DECREF(front);
3924
4.62k
            }
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
4.62k
        }
3948
0
        else {
3949
0
            final_mod = Py_NewRef(mod);
3950
0
        }
3951
3.19M
    }
3952
1.01k
    else {
3953
1.01k
        int has_path = PyObject_HasAttrWithError(mod, &_Py_ID(__path__));
3954
1.01k
        if (has_path < 0) {
3955
0
            goto error;
3956
0
        }
3957
1.01k
        if (has_path) {
3958
52
            final_mod = PyObject_CallMethodObjArgs(
3959
52
                        IMPORTLIB(interp), &_Py_ID(_handle_fromlist),
3960
52
                        mod, fromlist, IMPORT_FUNC(interp), NULL);
3961
52
        }
3962
960
        else {
3963
960
            final_mod = Py_NewRef(mod);
3964
960
        }
3965
1.01k
    }
3966
3967
3.19M
  error:
3968
3.19M
    Py_XDECREF(abs_name);
3969
3.19M
    Py_XDECREF(mod);
3970
3.19M
    if (final_mod == NULL) {
3971
481
        remove_importlib_frames(tstate);
3972
481
    }
3973
3.19M
    return final_mod;
3974
3.19M
}
3975
3976
PyObject *
3977
PyImport_ImportModuleLevel(const char *name, PyObject *globals, PyObject *locals,
3978
                           PyObject *fromlist, int level)
3979
57.5k
{
3980
57.5k
    PyObject *nameobj, *mod;
3981
57.5k
    nameobj = PyUnicode_FromString(name);
3982
57.5k
    if (nameobj == NULL)
3983
0
        return NULL;
3984
57.5k
    mod = PyImport_ImportModuleLevelObject(nameobj, globals, locals,
3985
57.5k
                                           fromlist, level);
3986
57.5k
    Py_DECREF(nameobj);
3987
57.5k
    return mod;
3988
57.5k
}
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
304k
{
4028
304k
    PyThreadState *tstate = _PyThreadState_GET();
4029
304k
    PyObject *globals = NULL;
4030
304k
    PyObject *import = NULL;
4031
304k
    PyObject *builtins = NULL;
4032
304k
    PyObject *r = NULL;
4033
4034
304k
    PyObject *from_list = PyList_New(0);
4035
304k
    if (from_list == NULL) {
4036
0
        goto err;
4037
0
    }
4038
4039
    /* Get the builtins from current globals */
4040
304k
    globals = PyEval_GetGlobals();  // borrowed
4041
304k
    if (globals != NULL) {
4042
246k
        Py_INCREF(globals);
4043
        // XXX Use _PyEval_EnsureBuiltins()?
4044
246k
        builtins = PyObject_GetItem(globals, &_Py_ID(__builtins__));
4045
246k
        if (builtins == NULL) {
4046
            // XXX Fall back to interp->builtins or sys.modules['builtins']?
4047
0
            goto err;
4048
0
        }
4049
246k
    }
4050
57.5k
    else if (_PyErr_Occurred(tstate)) {
4051
0
        goto err;
4052
0
    }
4053
57.5k
    else {
4054
        /* No globals -- use standard builtins, and fake globals */
4055
57.5k
        globals = PyDict_New();
4056
57.5k
        if (globals == NULL) {
4057
0
            goto err;
4058
0
        }
4059
57.5k
        if (_PyEval_EnsureBuiltinsWithModule(tstate, globals, &builtins) < 0) {
4060
0
            goto err;
4061
0
        }
4062
57.5k
    }
4063
4064
    /* Get the __import__ function from the builtins */
4065
304k
    if (PyDict_Check(builtins)) {
4066
246k
        import = PyObject_GetItem(builtins, &_Py_ID(__import__));
4067
246k
        if (import == NULL) {
4068
0
            _PyErr_SetObject(tstate, PyExc_KeyError, &_Py_ID(__import__));
4069
0
        }
4070
246k
    }
4071
57.5k
    else
4072
57.5k
        import = PyObject_GetAttr(builtins, &_Py_ID(__import__));
4073
304k
    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
304k
    r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
4080
304k
                              globals, from_list, 0, NULL);
4081
304k
    if (r == NULL)
4082
0
        goto err;
4083
304k
    Py_DECREF(r);
4084
4085
304k
    r = import_get_module(tstate, module_name);
4086
304k
    if (r == NULL && !_PyErr_Occurred(tstate)) {
4087
0
        _PyErr_SetObject(tstate, PyExc_KeyError, module_name);
4088
0
    }
4089
4090
304k
  err:
4091
304k
    Py_XDECREF(globals);
4092
304k
    Py_XDECREF(builtins);
4093
304k
    Py_XDECREF(import);
4094
304k
    Py_XDECREF(from_list);
4095
4096
304k
    return r;
4097
304k
}
4098
4099
4100
/*********************/
4101
/* runtime lifecycle */
4102
/*********************/
4103
4104
PyStatus
4105
_PyImport_Init(void)
4106
22
{
4107
22
    if (INITTAB != NULL) {
4108
0
        return _PyStatus_ERR("global import state already initialized");
4109
0
    }
4110
22
    if (init_builtin_modules_table() != 0) {
4111
0
        return PyStatus_NoMemory();
4112
0
    }
4113
22
    return _PyStatus_OK();
4114
22
}
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
22
{
4147
    // XXX Initialize here: interp->modules and interp->import_func.
4148
    // XXX Initialize here: sys.modules and sys.meta_path.
4149
4150
22
    if (importlib) {
4151
        /* This call sets up builtin and frozen import support */
4152
22
        if (init_importlib(tstate, sysmod) < 0) {
4153
0
            return _PyStatus_ERR("failed to initialize importlib");
4154
0
        }
4155
22
    }
4156
4157
22
    return _PyStatus_OK();
4158
22
}
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
22
{
4212
22
    PyObject *path_hooks = PySys_GetAttrString("path_hooks");
4213
22
    if (path_hooks == NULL) {
4214
0
        return -1;
4215
0
    }
4216
4217
22
    if (verbose) {
4218
0
        PySys_WriteStderr("# installing zipimport hook\n");
4219
0
    }
4220
4221
22
    PyObject *zipimporter = PyImport_ImportModuleAttrString("zipimport", "zipimporter");
4222
22
    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
22
    else {
4229
        /* sys.path_hooks.insert(0, zipimporter) */
4230
22
        int err = PyList_Insert(path_hooks, 0, zipimporter);
4231
22
        Py_DECREF(zipimporter);
4232
22
        if (err < 0) {
4233
0
            Py_DECREF(path_hooks);
4234
0
            return -1;
4235
0
        }
4236
22
        if (verbose) {
4237
0
            PySys_WriteStderr("# installed zipimport hook\n");
4238
0
        }
4239
22
    }
4240
22
    Py_DECREF(path_hooks);
4241
4242
22
    return 0;
4243
22
}
4244
4245
PyStatus
4246
_PyImport_InitExternal(PyThreadState *tstate)
4247
22
{
4248
22
    int verbose = _PyInterpreterState_GetConfig(tstate->interp)->verbose;
4249
4250
    // XXX Initialize here: sys.path_hooks and sys.path_importer_cache.
4251
4252
22
    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
22
    if (init_zipimport(tstate, verbose) != 0) {
4258
0
        PyErr_Print();
4259
0
        return _PyStatus_ERR("initializing zipimport failed");
4260
0
    }
4261
4262
22
    return _PyStatus_OK();
4263
22
}
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
8.17k
{
4290
8.17k
    PyObject *mod = PyImport_Import(modname);
4291
8.17k
    if (mod == NULL) {
4292
0
        return NULL;
4293
0
    }
4294
8.17k
    PyObject *result = PyObject_GetAttr(mod, attrname);
4295
8.17k
    Py_DECREF(mod);
4296
8.17k
    return result;
4297
8.17k
}
4298
4299
PyObject *
4300
PyImport_ImportModuleAttrString(const char *modname, const char *attrname)
4301
3.58k
{
4302
3.58k
    PyObject *pmodname = PyUnicode_FromString(modname);
4303
3.58k
    if (pmodname == NULL) {
4304
0
        return NULL;
4305
0
    }
4306
3.58k
    PyObject *pattrname = PyUnicode_FromString(attrname);
4307
3.58k
    if (pattrname == NULL) {
4308
0
        Py_DECREF(pmodname);
4309
0
        return NULL;
4310
0
    }
4311
3.58k
    PyObject *result = PyImport_ImportModuleAttr(pmodname, pattrname);
4312
3.58k
    Py_DECREF(pattrname);
4313
3.58k
    Py_DECREF(pmodname);
4314
3.58k
    return result;
4315
3.58k
}
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
6.11k
{
4352
6.11k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4353
6.11k
    _PyImport_AcquireLock(interp);
4354
6.11k
    Py_RETURN_NONE;
4355
6.11k
}
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
6.11k
{
4369
6.11k
    PyInterpreterState *interp = _PyInterpreterState_GET();
4370
6.11k
    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
6.11k
    _PyImport_ReleaseLock(interp);
4376
6.11k
    Py_RETURN_NONE;
4377
6.11k
}
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
343
{
4399
343
    update_compiled_module(code, path);
4400
4401
343
    Py_RETURN_NONE;
4402
343
}
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
298
{
4418
298
    PyThreadState *tstate = _PyThreadState_GET();
4419
4420
298
    PyObject *name = PyObject_GetAttrString(spec, "name");
4421
298
    if (name == NULL) {
4422
0
        return NULL;
4423
0
    }
4424
4425
298
    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
298
    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
298
    PyObject *mod = create_builtin(tstate, name, spec, NULL);
4440
298
    Py_DECREF(name);
4441
298
    return mod;
4442
298
}
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
44
{
4455
44
    PyObject *list;
4456
4457
44
    list = PyList_New(0);
4458
44
    if (list == NULL)
4459
0
        return NULL;
4460
44
#ifdef HAVE_DYNAMIC_LOADING
4461
44
    const char *suffix;
4462
44
    unsigned int index = 0;
4463
4464
176
    while ((suffix = _PyImport_DynLoadFiletab[index])) {
4465
132
        PyObject *item = PyUnicode_FromString(suffix);
4466
132
        if (item == NULL) {
4467
0
            Py_DECREF(list);
4468
0
            return NULL;
4469
0
        }
4470
132
        if (PyList_Append(list, item) < 0) {
4471
0
            Py_DECREF(list);
4472
0
            Py_DECREF(item);
4473
0
            return NULL;
4474
0
        }
4475
132
        Py_DECREF(item);
4476
132
        index += 1;
4477
132
    }
4478
44
#endif
4479
44
    return list;
4480
44
}
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
1.09k
{
4530
1.09k
    struct frozen_info info;
4531
1.09k
    frozen_status status = find_frozen(name, &info);
4532
1.09k
    if (status == FROZEN_NOT_FOUND || status == FROZEN_DISABLED) {
4533
852
        Py_RETURN_NONE;
4534
852
    }
4535
247
    else if (status == FROZEN_BAD_NAME) {
4536
0
        Py_RETURN_NONE;
4537
0
    }
4538
247
    else if (status != FROZEN_OKAY) {
4539
0
        set_frozen_error(status, name);
4540
0
        return NULL;
4541
0
    }
4542
4543
247
    PyObject *data = NULL;
4544
247
    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
247
    PyObject *origname = NULL;
4552
247
    if (info.origname != NULL && info.origname[0] != '\0') {
4553
247
        origname = PyUnicode_FromString(info.origname);
4554
247
        if (origname == NULL) {
4555
0
            Py_XDECREF(data);
4556
0
            return NULL;
4557
0
        }
4558
247
    }
4559
4560
247
    PyObject *result = PyTuple_Pack(3, data ? data : Py_None,
4561
247
                                    info.is_package ? Py_True : Py_False,
4562
247
                                    origname ? origname : Py_None);
4563
247
    Py_XDECREF(origname);
4564
247
    Py_XDECREF(data);
4565
247
    return result;
4566
247
}
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
247
{
4583
247
    struct frozen_info info = {0};
4584
247
    Py_buffer buf = {0};
4585
247
    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
247
    else if (dataobj != Py_None) {
4593
0
        _PyArg_BadArgument("get_frozen_object", "argument 2", "bytes", dataobj);
4594
0
        return NULL;
4595
0
    }
4596
247
    else {
4597
247
        frozen_status status = find_frozen(name, &info);
4598
247
        if (status != FROZEN_OKAY) {
4599
0
            set_frozen_error(status, name);
4600
0
            return NULL;
4601
0
        }
4602
247
    }
4603
4604
247
    if (info.nameobj == NULL) {
4605
0
        info.nameobj = name;
4606
0
    }
4607
247
    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
247
    PyInterpreterState *interp = _PyInterpreterState_GET();
4614
247
    PyObject *codeobj = unmarshal_frozen_code(interp, &info);
4615
247
    if (dataobj != Py_None) {
4616
0
        PyBuffer_Release(&buf);
4617
0
    }
4618
247
    return codeobj;
4619
247
}
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
22
{
4634
22
    struct frozen_info info;
4635
22
    frozen_status status = find_frozen(name, &info);
4636
22
    if (status != FROZEN_OKAY && status != FROZEN_EXCLUDED) {
4637
0
        set_frozen_error(status, name);
4638
0
        return NULL;
4639
0
    }
4640
22
    return PyBool_FromLong(info.is_package);
4641
22
}
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
1.39k
{
4656
1.39k
    return PyLong_FromLong(is_builtin(name));
4657
1.39k
}
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
22
{
4672
22
    struct frozen_info info;
4673
22
    frozen_status status = find_frozen(name, &info);
4674
22
    if (status != FROZEN_OKAY) {
4675
0
        Py_RETURN_FALSE;
4676
0
    }
4677
22
    Py_RETURN_TRUE;
4678
22
}
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
28
{
4765
28
    FILE *fp = NULL;
4766
28
    PyObject *mod = NULL;
4767
28
    PyThreadState *tstate = _PyThreadState_GET();
4768
4769
28
    struct _Py_ext_module_loader_info info;
4770
28
    if (_Py_ext_module_loader_info_init_from_spec(&info, spec) < 0) {
4771
0
        return NULL;
4772
0
    }
4773
4774
28
    struct extensions_cache_value *cached = NULL;
4775
28
    mod = import_find_extension(tstate, &info, &cached);
4776
28
    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
28
    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
28
    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
28
    if (PySys_Audit("import", "OOOOO", info.name, info.filename,
4800
28
                    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
28
    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
28
    PyModInitFunction p0 = NULL;
4816
28
    PyModExportFunction ex0 = NULL;
4817
28
    _PyImport_GetModuleExportHooks(&info, fp, &p0, &ex0);
4818
28
    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
28
    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
28
    mod = import_run_extension(
4837
28
                    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
28
finally:
4846
28
    if (fp != NULL) {
4847
0
        fclose(fp);
4848
0
    }
4849
28
    _Py_ext_module_loader_info_clear(&info);
4850
28
    return mod;
4851
28
}
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
28
{
4866
28
    return exec_builtin_or_dynamic(mod);
4867
28
}
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
298
{
4885
298
    return exec_builtin_or_dynamic(mod);
4886
298
}
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
22
{
4947
22
    const wchar_t *mode = _Py_GetConfig()->check_hash_pycs_mode;
4948
22
    PyObject *pyc_mode = PyUnicode_FromWideChar(mode, -1);
4949
22
    if (PyModule_Add(module, "check_hash_based_pycs", pyc_mode) < 0) {
4950
0
        return -1;
4951
0
    }
4952
4953
22
    if (PyModule_AddIntConstant(
4954
22
            module, "pyc_magic_number_token", PYC_MAGIC_NUMBER_TOKEN) < 0)
4955
0
    {
4956
0
        return -1;
4957
0
    }
4958
4959
22
    return 0;
4960
22
}
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
22
{
4982
22
    return PyModuleDef_Init(&imp_module);
4983
22
}